1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Compare commits

...

23 commits

Author SHA1 Message Date
Kegan Myers 50c1251b85
Merge branch 'canary' into canary 2019-02-18 02:25:07 -06:00
Kegan Myers 94460eee55 Add 'unified' SSR compilation target 2019-02-17 23:48:33 -06:00
Timon Borter f9fedaeba6 recreate stdChannel (or saga middleware). (#6330) 2019-02-17 20:57:59 +01:00
Tim Neutkens 9f2eb85de3 v8.0.2-canary.3 2019-02-17 20:48:43 +01:00
Tim Neutkens a1ccc19a1f
Pass through arguments of the next cli correctly (#6327)
Arguments that held the same name as one of the default commands were filtered out, causing issues.

For example `next build build` would get rid of the second `build` parameter.

Fixes #6263
2019-02-17 20:13:10 +01:00
Tim Neutkens dd9811b206
Fix recursive hydration of next/dynamic (#6326)
Fixes #5347

The main issue is that we were waiting only 1 level of dynamic imports, so the dynamic imports nested inside other dynamic import files were not awaited. This would cause either a flash of loading states or you wouldn't see the loading state (because of preload) but it would then show a hydration warning in development.

Thanks to @arthens for providing the reproduction that I modelled the tests after.
2019-02-17 19:52:00 +01:00
Ahmed Tarek 5cef35b811 Fix style importing (#6322) 2019-02-17 13:32:58 +01:00
Tim Neutkens 774af7fa0b v8.0.2-canary.2 2019-02-17 13:15:42 +01:00
Joshua Scott 46d870ab8a Fix url in docs (#6323) 2019-02-17 12:57:17 +01:00
Joe Haddad 7078f6567d Make build output friendlier (#6320)
Success:
![image](https://user-images.githubusercontent.com/616428/52907314-5e636480-322d-11e9-9420-b348663a3a7a.png)

Error:
![image](https://user-images.githubusercontent.com/616428/52907318-6c18ea00-322d-11e9-848d-e615d6af747d.png)

Warnings:
![image](https://user-images.githubusercontent.com/616428/52907353-2d376400-322e-11e9-9778-370f36912491.png)

---

We can still make build error output friendlier, but this is a good start.
2019-02-17 12:56:48 +01:00
Tim Neutkens 3882979236 v8.0.2-canary.1 2019-02-16 17:12:27 +01:00
Joe Haddad 56b1f81ace Fix development mode output (#6312)
* Remove usage of WebpackBar and Friendly Errors

* Add new clearConsole helper

* Add new simplified output for development mode

* Add an explicit bootstrapping mode

* Add missing returns

* Use existing output style

* Adjust first output to say Waiting on

* Only print URL if present
2019-02-16 17:09:49 +01:00
Tim Neutkens 036f5bf11b v8.0.2-canary.0 2019-02-16 16:41:30 +01:00
Tim Neutkens 708c537fc6 Merge branch 'master' into canary 2019-02-16 16:38:42 +01:00
JJ Kasper 5d779a0289 Add falling back to fetch based pinging for onDemandEntries (#6310)
After discussion, I added falling back to fetch based pinging when the WebSocket fails to connect. I also added an example of how to proxy the onDemandEntries WebSocket when using a custom server. Fixes: #6296
2019-02-15 22:22:21 +01:00
Connor Davis 1e5d0908d0 Block Certain Env Keys That Are Used Internally (#6260)
Closes: #6244 

This will block the following keys:
```
NODE_.+
__.+
```

There doesn't seem to be a way to simulate a failed build or else I'd add tests for it.
2019-02-15 17:49:40 +01:00
Timon Borter d2ef34429c push redux-saga to major release 1.0.1. (#6300) 2019-02-14 19:05:27 +01:00
Felix Mosheev 04ce3e7174 Use process.browser instead of env probing (#6286) 2019-02-14 19:05:08 +01:00
Joe Haddad 9bb8fbf535
Update webpack message formatter (#6299) 2019-02-14 11:13:35 -05:00
Tim Neutkens 4051ffcb01 [experimental] Rendering to AMP (#6218)
* Add initial AMP implementation

* Implement experimental feature flag

* Implement feedback from sbenz

* Add next/amp and `useAmp` hook

* Use /:path*/amp instead

* Add canonical

* Add amphtml tag

* Add ampEnabled for rel=“amphtml”

* Remove extra type
2019-02-14 10:22:57 -05:00
Joe Haddad 36946f9709
Remove lerna bootstrap (#6289) 2019-02-14 08:33:00 -05:00
Jonathan Reed 7dbe837ae4 fixes hashed statics readme (#6293)
# Description

* Fixes incorrect assertion of configuration file in the `with-hashed-statics` README as well as adds link to line for updating
2019-02-13 19:53:42 +01:00
Gary Meehan 126eb49867 Fix README links (#6284) 2019-02-13 10:53:04 -05:00
69 changed files with 1504 additions and 481 deletions

View file

@ -9,9 +9,6 @@ jobs:
- run:
name: Installing dependencies
command: yarn install
- run:
name: Bootstrapping
command: yarn bootstrap
- run:
name: Linting
command: yarn lint
@ -31,4 +28,4 @@ workflows:
version: 2
build-and-deploy:
jobs:
- build
- build

View file

@ -20,6 +20,6 @@
before_cache: [
"rm -rf node_modules/.cache"
],
before_script: ["npm run bootstrap"],
before_script: [],
after_script: ["npm run coveralls"]
}

View file

@ -765,7 +765,7 @@ class MyLink extends React.Component {
const { router } = this.props
router.prefetch('/dynamic')
}
render() {
const { router } = this.props
return (
@ -773,7 +773,7 @@ class MyLink extends React.Component {
<a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}>
A route transition will happen after 100ms
</a>
</div>
</div>
)
}
}
@ -1343,7 +1343,7 @@ module.exports = {
```js
// Example next.config.js for adding a loader that depends on babel-loader
// This source was taken from the @zeit/next-mdx plugin source:
// This source was taken from the @zeit/next-mdx plugin source:
// https://github.com/zeit/next-plugins/blob/master/packages/next-mdx
module.exports = {
webpack: (config, {}) => {
@ -1464,7 +1464,7 @@ module.exports = {
}
```
注意Next.js 运行时将会自动添加前缀,但是对于`/static`是没有效果的,如果你想这些静态资源也能使用 CDN你需要自己添加前缀。有一个方法可以判断你的环境来加前缀如 [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration)。
注意Next.js 运行时将会自动添加前缀,但是对于`/static`是没有效果的,如果你想这些静态资源也能使用 CDN你需要自己添加前缀。有一个方法可以判断你的环境来加前缀如 [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration-build-time)。
<a id="production-deployment" style="display: none"></a>
## 项目部署

View file

@ -19,10 +19,6 @@ steps:
yarn install
displayName: 'Install dependencies'
- script: |
yarn bootstrap
displayName: 'Lerna bootstrap'
- script: |
yarn test
displayName: 'Run tests'

View file

@ -3,10 +3,9 @@
Our Commitment to Open Source can be found [here](https://zeit.co/blog/oss)
1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device.
2. Install yarn: `npm install -g yarn`
3. Install the dependencies: `yarn`
4. Run `yarn run bootstrap`, which will link all repositories locally
5. Run `yarn run dev` to build and watch for code changes
1. Install yarn: `npm install -g yarn`
1. Install the dependencies: `yarn`
1. Run `yarn run dev` to build and watch for code changes
## To run tests

View file

@ -0,0 +1,9 @@
# The key "<your key>" under "env" in next.config.js is not allowed.
#### Why This Error Occurred
Next.js configures internal variables for replacement itself. These start with `__` or `NODE_`, for this reason they are not allowed as values for `env` in `next.config.js`
#### Possible Ways to Fix It
Rename the specified key so that it does not start with `__` or `NODE_`.

View file

@ -0,0 +1,29 @@
# onDemandEntries WebSocket unavailable
#### Why This Error Occurred
By default Next.js uses a random port to create a WebSocket to receive pings from the client letting it know to keep pages active. For some reason when the client tried to connect to this WebSocket the connection fails.
#### Possible Ways to Fix It
If you don't mind the fetch requests in your network console then you don't have to do anything as the fallback to fetch works fine. If you do, then depending on your set up you might need configure settings using the below config options from `next.config.js`:
```js
module.exports = {
onDemandEntries: {
// optionally configure a port for the onDemandEntries WebSocket, not needed by default
websocketPort: 3001,
// optionally configure a proxy path for the onDemandEntries WebSocket, not need by default
websocketProxyPath: '/hmr',
// optionally configure a proxy port for the onDemandEntries WebSocket, not need by default
websocketProxyPort: 7002,
},
}
```
If you are using a custom server with SSL configured, you might want to take a look at [the example](https://github.com/zeit/next.js/tree/canary/examples/custom-server-proxy-websocket) showing how to proxy the WebSocket connection through your custom server
### Useful Links
- [onDemandEntries config](https://github.com/zeit/next.js#configuring-the-ondemandentries)
- [Custom server proxying example](https://github.com/zeit/next.js/tree/canary/examples/custom-server-proxy-websocket)

View file

@ -0,0 +1,38 @@
# Custom server with Proxying onDemandEntries WebSocket
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/segmentio/create-next-app) with [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) or [npx](https://github.com/zkat/npx#readme) to bootstrap the example:
```bash
npx create-next-app --example custom-server-proxy-websocket custom-server-proxy-websocket
# or
yarn create next-app --example custom-server-proxy-websocket custom-server-proxy-websocket
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/custom-server-proxy-websocket
cd custom-server-proxy-websocket
```
Install it and run:
```bash
npm install
npm run ssl
npm run dev
# or
yarn
yarn ssl
yarn dev
```
## The idea behind the example
The example shows how you can use SSL with a custom server and still use onDemandEntries WebSocket from Next.js using [node-http-proxy](https://github.com/nodejitsu/node-http-proxy#readme) and [ExpressJS](https://github.com/expressjs/express).

View file

@ -0,0 +1,7 @@
#!/bin/sh
# Generate self-signed certificate (only meant for testing don't use in production...)
# requires openssl be installed and in the $PATH
openssl genrsa -out localhost.key 2048
openssl req -new -x509 -key localhost.key -out localhost.cert -days 3650 -subj /CN=localhost

View file

@ -0,0 +1,6 @@
module.exports = {
onDemandEntries: {
websocketPort: 3001,
websocketProxyPort: 3000
}
}

View file

@ -0,0 +1,21 @@
{
"name": "custom-server-proxy-websocket",
"version": "1.0.0",
"main": "server.js",
"license": "MIT",
"scripts": {
"dev": "node server.js",
"build": "next build",
"ssl": "./genSSL.sh",
"start": "NODE_ENV=production node server.js"
},
"dependencies": {
"express": "4.16.4",
"next": "8.0.1",
"react": "16.8.2",
"react-dom": "16.8.2"
},
"devDependencies": {
"http-proxy": "1.17.0"
}
}

View file

@ -0,0 +1,10 @@
import Link from 'next/link'
export default () => (
<div>
<h3>Another</h3>
<Link href='/'>
<a>Index</a>
</Link>
</div>
)

View file

@ -0,0 +1,10 @@
import Link from 'next/link'
export default () => (
<div>
<h3>Index</h3>
<Link href='/another'>
<a>Another</a>
</Link>
</div>
)

View file

@ -0,0 +1,43 @@
const express = require('express')
const Next = require('next')
const https = require('https')
const fs = require('fs')
const app = express()
const port = 3000
const isDev = process.env.NODE_ENV !== 'production'
const next = Next({ dev: isDev })
// Set up next
next.prepare()
// Set up next handler
app.use(next.getRequestHandler())
// Set up https.Server options with SSL
const options = {
key: fs.readFileSync('./localhost.key'),
cert: fs.readFileSync('./localhost.cert')
}
// Create http server using express app as requestHandler
const server = https.createServer(options, app)
// Set up proxying for Next's onDemandEntries WebSocket to allow
// using our SSL
if (isDev) {
const CreateProxyServer = require('http-proxy').createProxyServer
const proxy = CreateProxyServer({
target: {
host: 'localhost',
port: 3001
}
})
server.on('upgrade', (req, socket, head) => {
proxy.ws(req, socket, head)
})
}
server.listen(port, () => {
console.log(`Server listening at http://localhost:${port}`)
})

View file

@ -41,4 +41,4 @@ now
This example shows how to import images, videos, etc. from `/static` and get the URL with a hash query allowing to use better cache without problems.
This example supports `.svg`, `.png` and `.txt` extensions, but it can be configured to support any possible extension changing the `extensions` array in the `.babelrc` file.
This example supports `.svg`, `.png` and `.txt` extensions, but it can be configured to support any possible extension changing the `extensions` array in the `next.config.js` [file](https://github.com/zeit/next.js/blob/canary/examples/with-hashed-statics/next.config.js#L4).

View file

@ -21,7 +21,7 @@ class MyMobxApp extends App {
constructor(props) {
super(props)
const isServer = typeof window === 'undefined'
const isServer = !process.browser;
this.mobxStore = isServer
? props.initialMobxState
: initializeStore(props.initialMobxState)

View file

@ -1,7 +1,7 @@
import { action, observable } from 'mobx'
import { useStaticRendering } from 'mobx-react'
const isServer = typeof window === 'undefined'
const isServer = !process.browser
useStaticRendering(isServer)
class Store {
@ -25,7 +25,8 @@ class Store {
}
let store = null
export function initializeStore(initialData) {
export function initializeStore (initialData) {
// Always make a new store if server, otherwise state is shared between requests
if (isServer) {
return new Store(isServer, initialData)

View file

@ -49,6 +49,6 @@ This example features:
* An app with next-sass
This example uses next-sass without css-modules. The config can be found in `next.config.js`, change `withSass()` to `withSass({cssModules: true})` if you use css-modules. Then in the code, you import the stylesheet as `import style '../styles/style.scss'` and use it like `<div className={style.example}>`.
This example uses next-sass without css-modules. The config can be found in `next.config.js`, change `withSass()` to `withSass({cssModules: true})` if you use css-modules. Then in the code, you import the stylesheet as `import style from '../styles/style.scss'` and use it like `<div className={style.example}>`.
[Learn more](https://github.com/zeit/next-plugins/tree/master/packages/next-sass)

View file

@ -11,13 +11,13 @@
"es6-promise": "4.1.1",
"isomorphic-unfetch": "2.0.0",
"next": "latest",
"next-redux-saga": "3.0.0",
"next-redux-saga": "4.0.0",
"next-redux-wrapper": "2.0.0",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react-redux": "5.0.7",
"redux": "4.0.0",
"redux-saga": "0.16.0"
"redux": "4.0.1",
"redux-saga": "1.0.1"
},
"devDependencies": {
"redux-devtools-extension": "2.13.2"

View file

@ -29,4 +29,4 @@ class MyApp extends App {
}
}
export default withRedux(createStore)(withReduxSaga({ async: true })(MyApp))
export default withRedux(createStore)(withReduxSaga(MyApp))

View file

@ -1,7 +1,6 @@
/* global fetch */
import { delay } from 'redux-saga'
import { all, call, put, take, takeLatest } from 'redux-saga/effects'
import { all, call, delay, put, take, takeLatest } from 'redux-saga/effects'
import es6promise from 'es6-promise'
import 'isomorphic-unfetch'
@ -13,7 +12,7 @@ function * runClockSaga () {
yield take(actionTypes.START_CLOCK)
while (true) {
yield put(tickClock(false))
yield call(delay, 1000)
yield delay(1000)
}
}

View file

@ -1,11 +1,9 @@
import { createStore, applyMiddleware } from 'redux'
import { applyMiddleware, createStore } from 'redux'
import createSagaMiddleware from 'redux-saga'
import rootReducer, { exampleInitialState } from './reducer'
import rootSaga from './saga'
const sagaMiddleware = createSagaMiddleware()
const bindMiddleware = middleware => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension')
@ -15,17 +13,15 @@ const bindMiddleware = middleware => {
}
function configureStore (initialState = exampleInitialState) {
const sagaMiddleware = createSagaMiddleware()
const store = createStore(
rootReducer,
initialState,
bindMiddleware([sagaMiddleware])
)
store.runSagaTask = () => {
store.sagaTask = sagaMiddleware.run(rootSaga)
}
store.sagaTask = sagaMiddleware.run(rootSaga)
store.runSagaTask()
return store
}

View file

@ -17,5 +17,5 @@
"registry": "https://registry.npmjs.org/"
}
},
"version": "8.0.1"
"version": "8.0.2-canary.3"
}

View file

@ -6,7 +6,6 @@
],
"scripts": {
"lerna": "lerna",
"bootstrap": "lerna bootstrap",
"dev": "lerna run build --stream --parallel",
"testonly": "jest",
"testall": "yarn check && npm run testonly -- --coverage --forceExit --runInBand --reporters=default --reporters=jest-junit",
@ -61,6 +60,7 @@
"@zeit/next-css": "1.0.2-canary.2",
"@zeit/next-sass": "1.0.2-canary.2",
"@zeit/next-typescript": "1.1.2-canary.0",
"amphtml-validator": "1.0.23",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "9.0.0",
"babel-jest": "23.6.0",
@ -84,8 +84,8 @@
"node-sass": "4.9.2",
"pre-commit": "1.2.2",
"prettier": "1.15.3",
"react": "16.6.3",
"react-dom": "16.6.3",
"react": "16.8.0",
"react-dom": "16.8.0",
"release": "5.0.3",
"request-promise-core": "1.1.1",
"rimraf": "2.6.2",

View file

@ -0,0 +1 @@
module.exports = require('./dist/lib/amp')

View file

@ -0,0 +1,6 @@
import React from 'react'
import {IsAmpContext} from './amphtml-context'
export function useAmp() {
return React.useContext(IsAmpContext)
}

View file

@ -0,0 +1,3 @@
import * as React from 'react'
export const IsAmpContext: React.Context<any> = React.createContext(false)

View file

@ -25,7 +25,7 @@ import React from 'react'
import PropTypes from 'prop-types'
const ALL_INITIALIZERS = []
const READY_INITIALIZERS = new Map()
const READY_INITIALIZERS = []
let initialized = false
function load (loader) {
@ -138,11 +138,13 @@ function createLoadableComponent (loadFn, options) {
// Client only
if (!initialized && typeof window !== 'undefined' && typeof opts.webpack === 'function') {
const moduleIds = opts.webpack()
for (const moduleId of moduleIds) {
READY_INITIALIZERS.set(moduleId, () => {
return init()
})
}
READY_INITIALIZERS.push((ids) => {
for (const moduleId of moduleIds) {
if (ids.indexOf(moduleId) !== -1) {
return init()
}
}
})
}
return class LoadableComponent extends React.Component {
@ -273,17 +275,17 @@ function LoadableMap (opts) {
Loadable.Map = LoadableMap
function flushInitializers (initializers) {
function flushInitializers (initializers, ids) {
let promises = []
while (initializers.length) {
let init = initializers.pop()
promises.push(init())
promises.push(init(ids))
}
return Promise.all(promises).then(() => {
if (initializers.length) {
return flushInitializers(initializers)
return flushInitializers(initializers, ids)
}
})
}
@ -294,24 +296,14 @@ Loadable.preloadAll = () => {
})
}
Loadable.preloadReady = (webpackIds) => {
return new Promise((resolve, reject) => {
const initializers = webpackIds.reduce((allInitalizers, moduleId) => {
const initializer = READY_INITIALIZERS.get(moduleId)
if (!initializer) {
return allInitalizers
}
allInitalizers.push(initializer)
return allInitalizers
}, [])
initialized = true
// Make sure the object is cleared
READY_INITIALIZERS.clear()
Loadable.preloadReady = (ids) => {
return new Promise((resolve) => {
const res = () => {
initialized = true
return resolve()
}
// We always will resolve, errors should be handled within loading UIs.
flushInitializers(initializers).then(resolve, resolve)
flushInitializers(READY_INITIALIZERS, ids).then(res, res)
})
}

View file

@ -1,6 +1,6 @@
{
"name": "next-server",
"version": "8.0.1",
"version": "8.0.2-canary.3",
"main": "./index.js",
"license": "MIT",
"files": [
@ -12,7 +12,8 @@
"head.js",
"link.js",
"router.js",
"next-config.js"
"next-config.js",
"amp.js"
],
"scripts": {
"build": "taskr",

View file

@ -1,9 +1,10 @@
import findUp from 'find-up'
import {CONFIG_FILE} from 'next-server/constants'
const targets = ['server', 'serverless']
const targets = ['server', 'serverless', 'unified']
const defaultConfig = {
env: [],
webpack: null,
webpackDevMiddleware: null,
poweredByHeader: true,
@ -21,6 +22,9 @@ const defaultConfig = {
websocketPort: 0,
websocketProxyPath: '/',
websocketProxyPort: null
},
experimental: {
amp: false
}
}
@ -47,6 +51,12 @@ export default function loadConfig (phase, dir, customConfig) {
if (userConfig.target && !targets.includes(userConfig.target)) {
throw new Error(`Specified target is invalid. Provided: "${userConfig.target}" should be one of ${targets.join(', ')}`)
}
if (userConfig.experimental) {
userConfig.experimental = {
...defaultConfig.experimental,
...userConfig.experimental
}
}
if (userConfig.onDemandEntries) {
userConfig.onDemandEntries = {
...defaultConfig.onDemandEntries,

View file

@ -30,6 +30,7 @@ export default class Server {
distDir: string
buildId: string
renderOpts: {
ampEnabled: boolean,
staticMarkup: boolean,
buildId: string,
generateEtags: boolean,
@ -53,6 +54,7 @@ export default class Server {
this.buildId = this.readBuildId()
this.renderOpts = {
ampEnabled: this.nextConfig.experimental.amp,
staticMarkup,
buildId: this.buildId,
generateEtags,
@ -160,6 +162,29 @@ export default class Server {
]
if (this.nextConfig.useFileSystemPublicRoutes) {
if (this.nextConfig.experimental.amp) {
// It's very important to keep this route's param optional.
// (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack.
// See more: https://github.com/zeit/next.js/issues/2617
routes.push({
match: route('/:path*/amp'),
fn: async (req, res, params, parsedUrl) => {
let pathname
if (!params.path) {
pathname = '/'
} else {
pathname = '/' + params.path.join('/')
}
const { query } = parsedUrl
if (!pathname) {
throw new Error('pathname is undefined')
}
await this.renderToAMP(req, res, pathname, query, parsedUrl)
},
})
}
// It's very important to keep this route's param optional.
// (but it should support as many params as needed, separated by '/')
// Otherwise this will lead to a pretty simple DOS attack.
@ -223,6 +248,31 @@ export default class Server {
return
}
if (this.nextConfig.poweredByHeader) {
res.setHeader('X-Powered-By', 'Next.js ' + process.env.__NEXT_VERSION)
}
return this.sendHTML(req, res, html)
}
public async renderToAMP(req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery = {}, parsedUrl?: UrlWithParsedQuery): Promise<void> {
if (!this.nextConfig.experimental.amp) {
throw new Error('"experimental.amp" is not enabled in "next.config.js"')
}
const url: any = req.url
if (isInternalUrl(url)) {
return this.handleRequest(req, res, parsedUrl)
}
if (isBlockedPage(pathname)) {
return this.render404(req, res, parsedUrl)
}
const html = await this.renderToAMPHTML(req, res, pathname, query)
// Request was ended by the user
if (html === null) {
return
}
if (this.nextConfig.poweredByHeader) {
res.setHeader('X-Powered-By', 'Next.js ' + process.env.NEXT_VERSION)
}
@ -234,10 +284,17 @@ export default class Server {
return renderToHTML(req, res, pathname, query, {...result, ...opts})
}
public async renderToHTML(req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery = {}): Promise<string|null> {
public async renderToAMPHTML(req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery = {}): Promise<string|null> {
if (!this.nextConfig.experimental.amp) {
throw new Error('"experimental.amp" is not enabled in "next.config.js"')
}
return this.renderToHTML(req, res, pathname, query, {amphtml: true})
}
public async renderToHTML(req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery = {}, {amphtml}: {amphtml?: boolean} = {}): Promise<string|null> {
try {
// To make sure the try/catch is executed
const html = await this.renderToHTMLWithComponents(req, res, pathname, query, this.renderOpts)
const html = await this.renderToHTMLWithComponents(req, res, pathname, query, {...this.renderOpts, amphtml})
return html
} catch (err) {
if (err.code === 'ENOENT') {

View file

@ -1,4 +1,4 @@
import {IncomingMessage, ServerResponse} from 'http'
import { IncomingMessage, ServerResponse } from 'http'
import { ParsedUrlQuery } from 'querystring'
import React from 'react'
import { renderToString, renderToStaticMarkup } from 'react-dom/server'
@ -7,15 +7,26 @@ import { loadGetInitialProps, isResSent } from '../lib/utils'
import Head, { defaultHead } from '../lib/head'
import Loadable from '../lib/loadable'
import LoadableCapture from '../lib/loadable-capture'
import {getDynamicImportBundles, Manifest as ReactLoadableManifest, ManifestItem} from './get-dynamic-import-bundles'
import {getPageFiles, BuildManifest} from './get-page-files'
import {
getDynamicImportBundles,
Manifest as ReactLoadableManifest,
ManifestItem,
} from './get-dynamic-import-bundles'
import { getPageFiles, BuildManifest } from './get-page-files'
import { IsAmpContext } from '../lib/amphtml-context'
type Enhancer = (Component: React.ComponentType) => React.ComponentType
type ComponentsEnhancer = {enhanceApp?: Enhancer, enhanceComponent?: Enhancer}|Enhancer
type ComponentsEnhancer =
| { enhanceApp?: Enhancer; enhanceComponent?: Enhancer }
| Enhancer
function enhanceComponents(options: ComponentsEnhancer, App: React.ComponentType, Component: React.ComponentType): {
function enhanceComponents(
options: ComponentsEnhancer,
App: React.ComponentType,
Component: React.ComponentType,
): {
App: React.ComponentType
Component: React.ComponentType,
} {
// For backwards compatibility
if (typeof options === 'function') {
@ -27,11 +38,16 @@ function enhanceComponents(options: ComponentsEnhancer, App: React.ComponentType
return {
App: options.enhanceApp ? options.enhanceApp(App) : App,
Component: options.enhanceComponent ? options.enhanceComponent(Component) : Component,
Component: options.enhanceComponent
? options.enhanceComponent(Component)
: Component,
}
}
function render(renderElementToString: (element: React.ReactElement<any>) => string, element: React.ReactElement<any>): {html: string, head: any} {
function render(
renderElementToString: (element: React.ReactElement<any>) => string,
element: React.ReactElement<any>,
): { html: string; head: any } {
let html
let head
@ -45,75 +61,101 @@ function render(renderElementToString: (element: React.ReactElement<any>) => str
}
type RenderOpts = {
staticMarkup: boolean,
buildId: string,
runtimeConfig?: {[key: string]: any},
assetPrefix?: string,
err?: Error|null,
nextExport?: boolean,
dev?: boolean,
buildManifest: BuildManifest,
reactLoadableManifest: ReactLoadableManifest,
Component: React.ComponentType,
Document: React.ComponentType,
App: React.ComponentType,
ErrorDebug?: React.ComponentType<{error: Error}>,
ampEnabled: boolean
staticMarkup: boolean
buildId: string
runtimeConfig?: { [key: string]: any }
assetPrefix?: string
err?: Error | null
nextExport?: boolean
dev?: boolean
amphtml?: boolean
buildManifest: BuildManifest
reactLoadableManifest: ReactLoadableManifest
Component: React.ComponentType
Document: React.ComponentType
App: React.ComponentType
ErrorDebug?: React.ComponentType<{ error: Error }>,
}
function renderDocument(Document: React.ComponentType, {
props,
docProps,
pathname,
query,
buildId,
assetPrefix,
runtimeConfig,
nextExport,
dynamicImportsIds,
err,
dev,
staticMarkup,
devFiles,
files,
dynamicImports,
}: RenderOpts & {
props: any,
docProps: any,
pathname: string,
query: ParsedUrlQuery,
dynamicImportsIds: string[],
dynamicImports: ManifestItem[],
files: string[]
devFiles: string[],
}): string {
return '<!DOCTYPE html>' + renderToStaticMarkup(
<Document
__NEXT_DATA__={{
props, // The result of getInitialProps
page: pathname, // The rendered page
query, // querystring parsed / passed by the user
buildId, // buildId is used to facilitate caching of page bundles, we send it to the client so that pageloader knows where to load bundles
assetPrefix: assetPrefix === '' ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML
runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML
nextExport, // If this is a page exported by `next export`
dynamicIds: dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds,
err: (err) ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
}}
staticMarkup={staticMarkup}
devFiles={devFiles}
files={files}
dynamicImports={dynamicImports}
assetPrefix={assetPrefix}
{...docProps}
/>,
function renderDocument(
Document: React.ComponentType,
{
ampEnabled = false,
props,
docProps,
pathname,
asPath,
query,
buildId,
assetPrefix,
runtimeConfig,
nextExport,
dynamicImportsIds,
err,
dev,
amphtml,
staticMarkup,
devFiles,
files,
dynamicImports,
}: RenderOpts & {
props: any
docProps: any
pathname: string
asPath: string | undefined
query: ParsedUrlQuery
amphtml: boolean
dynamicImportsIds: string[]
dynamicImports: ManifestItem[]
files: string[]
devFiles: string[],
},
): string {
return (
'<!DOCTYPE html>' +
renderToStaticMarkup(
<IsAmpContext.Provider value={amphtml}>
<Document
__NEXT_DATA__={{
props, // The result of getInitialProps
page: pathname, // The rendered page
query, // querystring parsed / passed by the user
buildId, // buildId is used to facilitate caching of page bundles, we send it to the client so that pageloader knows where to load bundles
assetPrefix: assetPrefix === '' ? undefined : assetPrefix, // send assetPrefix to the client side when configured, otherwise don't sent in the resulting HTML
runtimeConfig, // runtimeConfig if provided, otherwise don't sent in the resulting HTML
nextExport, // If this is a page exported by `next export`
dynamicIds:
dynamicImportsIds.length === 0 ? undefined : dynamicImportsIds,
err: err ? serializeError(dev, err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
}}
ampEnabled={ampEnabled}
asPath={encodeURI(asPath || '')}
amphtml={amphtml}
staticMarkup={staticMarkup}
devFiles={devFiles}
files={files}
dynamicImports={dynamicImports}
assetPrefix={assetPrefix}
{...docProps}
/>
</IsAmpContext.Provider>,
)
)
}
export async function renderToHTML(req: IncomingMessage, res: ServerResponse, pathname: string, query: ParsedUrlQuery, renderOpts: RenderOpts): Promise<string|null> {
export async function renderToHTML(
req: IncomingMessage,
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery,
renderOpts: RenderOpts,
): Promise<string | null> {
const {
err,
dev = false,
staticMarkup = false,
amphtml = false,
App,
Document,
Component,
@ -127,22 +169,28 @@ export async function renderToHTML(req: IncomingMessage, res: ServerResponse, pa
if (dev) {
const { isValidElementType } = require('react-is')
if (!isValidElementType(Component)) {
throw new Error(`The default export is not a React Component in page: "${pathname}"`)
throw new Error(
`The default export is not a React Component in page: "${pathname}"`,
)
}
if (!isValidElementType(App)) {
throw new Error(`The default export is not a React Component in page: "/_app"`)
throw new Error(
`The default export is not a React Component in page: "/_app"`,
)
}
if (!isValidElementType(Document)) {
throw new Error(`The default export is not a React Component in page: "/_document"`)
throw new Error(
`The default export is not a React Component in page: "/_document"`,
)
}
}
const asPath = req.url
const ctx = { err, req, res, pathname, query, asPath }
const router = new Router(pathname, query, asPath)
const props = await loadGetInitialProps(App, {Component, router, ctx})
const props = await loadGetInitialProps(App, { Component, router, ctx })
// the response might be finished on the getInitialProps call
if (isResSent(res)) return null
@ -156,23 +204,35 @@ export async function renderToHTML(req: IncomingMessage, res: ServerResponse, pa
]
const reactLoadableModules: string[] = []
const renderPage = (options: ComponentsEnhancer = {}): {html: string, head: any} => {
const renderElementToString = staticMarkup ? renderToStaticMarkup : renderToString
const renderPage = (
options: ComponentsEnhancer = {},
): { html: string; head: any } => {
const renderElementToString = staticMarkup
? renderToStaticMarkup
: renderToString
if (err && ErrorDebug) {
return render(renderElementToString, <ErrorDebug error={err} />)
}
const {App: EnhancedApp, Component: EnhancedComponent} = enhanceComponents(options, App, Component)
const {
App: EnhancedApp,
Component: EnhancedComponent,
} = enhanceComponents(options, App, Component)
return render(renderElementToString,
<LoadableCapture report={(moduleName) => reactLoadableModules.push(moduleName)}>
<EnhancedApp
Component={EnhancedComponent}
router={router}
{...props}
/>
</LoadableCapture>,
return render(
renderElementToString,
<IsAmpContext.Provider value={amphtml}>
<LoadableCapture
report={(moduleName) => reactLoadableModules.push(moduleName)}
>
<EnhancedApp
Component={EnhancedComponent}
router={router}
{...props}
/>
</LoadableCapture>
</IsAmpContext.Provider>,
)
}
@ -180,14 +240,18 @@ export async function renderToHTML(req: IncomingMessage, res: ServerResponse, pa
// the response might be finished on the getInitialProps call
if (isResSent(res)) return null
const dynamicImports = [...getDynamicImportBundles(reactLoadableManifest, reactLoadableModules)]
const dynamicImports = [
...getDynamicImportBundles(reactLoadableManifest, reactLoadableModules),
]
const dynamicImportsIds: any = dynamicImports.map((bundle) => bundle.id)
return renderDocument(Document, {
...renderOpts,
props,
docProps,
asPath,
pathname,
amphtml,
query,
dynamicImportsIds,
dynamicImports,
@ -201,10 +265,17 @@ function errorToJSON(err: Error): Error {
return { name, message, stack }
}
function serializeError(dev: boolean|undefined, err: Error): Error & {statusCode?: number} {
function serializeError(
dev: boolean | undefined,
err: Error,
): Error & { statusCode?: number } {
if (dev) {
return errorToJSON(err)
}
return { name: 'Internal Server Error.', message: '500 - Internal Server Error.', statusCode: 500 }
return {
name: 'Internal Server Error.',
message: '500 - Internal Server Error.',
statusCode: 500,
}
}

View file

@ -4,7 +4,7 @@ import pathMatch from './lib/path-match'
export const route = pathMatch()
type Params = {[param: string]: string}
type Params = {[param: string]: any}
export type Route = {
match: (pathname: string|undefined) => false|Params,

View file

@ -35,7 +35,7 @@ try {
}
// update file's data
file.data = Buffer.from(result.outputText.replace(/process\.env\.NEXT_VERSION/, `"${require('./package.json').version}"`), 'utf8')
file.data = Buffer.from(result.outputText.replace(/process\.env\.__NEXT_VERSION/, `"${require('./package.json').version}"`), 'utf8')
})
}
} catch (err) {

View file

@ -227,7 +227,7 @@ function HiThere() {
export default HiThere
```
To use more sophisticated CSS-in-JS solutions, you typically have to implement style flushing for server-side rendering. We enable this by allowing you to define your own [custom `<Document>`](#user-content-custom-document) component that wraps each page.
To use more sophisticated CSS-in-JS solutions, you typically have to implement style flushing for server-side rendering. We enable this by allowing you to define your own [custom `<Document>`](#custom-document) component that wraps each page.
#### Importing CSS / Sass / Less / Stylus files
@ -836,7 +836,7 @@ You can add `prefetch` prop to any `<Link>` and Next.js will prefetch those page
```jsx
import Link from 'next/link'
function Header() {
function Header() {
return (
<nav>
<ul>
@ -870,7 +870,7 @@ Most prefetching needs are addressed by `<Link />`, but we also expose an impera
```jsx
import { withRouter } from 'next/router'
function MyLink({ router }) {
function MyLink({ router }) {
return (
<div>
<a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}>
@ -1082,7 +1082,7 @@ function Home() {
<p>HOME PAGE is here!</p>
</div>
)
}
}
export default Home
```
@ -1684,10 +1684,10 @@ export default Index
> :warning: Note that this option is not available when using `target: 'serverless'`
> :warning: Generally you want to use build-time configuration to provide your configuration.
> :warning: Generally you want to use build-time configuration to provide your configuration.
The reason for this is that runtime configuration adds a small rendering / initialization overhead.
The `next/config` module gives your app access to the `publicRuntimeConfig` and `serverRuntimeConfig` stored in your `next.config.js`.
The `next/config` module gives your app access to the `publicRuntimeConfig` and `serverRuntimeConfig` stored in your `next.config.js`.
Place any server-only runtime config under a `serverRuntimeConfig` property.
@ -1742,7 +1742,7 @@ module.exports = {
}
```
Note: Next.js will automatically use that prefix in the scripts it loads, but this has no effect whatsoever on `/static`. If you want to serve those assets over the CDN, you'll have to introduce the prefix yourself. One way of introducing a prefix that works inside your components and varies by environment is documented [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration).
Note: Next.js will automatically use that prefix in the scripts it loads, but this has no effect whatsoever on `/static`. If you want to serve those assets over the CDN, you'll have to introduce the prefix yourself. One way of introducing a prefix that works inside your components and varies by environment is documented [in this example](https://github.com/zeit/next.js/tree/master/examples/with-universal-configuration-build-time).
If your CDN is on a separate domain and you would like assets to be requested using a [CORS aware request](https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_settings_attributes) you can set a config option for that.

1
packages/next/amp.js Normal file
View file

@ -0,0 +1 @@
module.exports = require('next-server/amp')

View file

@ -4,6 +4,7 @@ import arg from 'arg'
import { existsSync } from 'fs'
import startServer from '../server/lib/start-server'
import { printAndExit } from '../server/lib/utils'
import { startedDevelopmentServer } from '../build/output'
const args = arg({
// Types
@ -55,10 +56,12 @@ if (!existsSync(join(dir, 'pages'))) {
}
const port = args['--port'] || 3000
const appUrl = `http://${args['--hostname'] || 'localhost'}:${port}`
startedDevelopmentServer(appUrl)
startServer({dir, dev: true}, port, args['--hostname'])
.then(async (app) => {
// tslint:disable-next-line
console.log(`> Ready on http://${args['--hostname'] || 'localhost'}:${port}`)
await app.prepare()
})
.catch((err) => {

View file

@ -37,12 +37,12 @@ const args = arg({
// Version is inlined into the file using taskr build pipeline
if (args['--version']) {
// tslint:disable-next-line
console.log(`Next.js v${process.env.NEXT_VERSION}`)
console.log(`Next.js v${process.env.__NEXT_VERSION}`)
process.exit(0)
}
// Check if we are running `next <subcommand>` or `next`
const foundCommand = args._.find((cmd) => commands.includes(cmd))
const foundCommand = commands.includes(args._[0])
// Makes sure the `next <subcommand> --help` case is covered
// This help message is only showed for `next --help`
@ -73,8 +73,8 @@ if (args['--inspect']) {
nodeArguments.push('--inspect')
}
const command = foundCommand || defaultCommand
const forwardedArgs = args._.filter((arg) => arg !== command)
const command = foundCommand ? args._[0] : defaultCommand
const forwardedArgs = foundCommand ? args._.slice(1) : args._
// Make sure the `next <subcommand> --help` case is covered
if (args['--help']) {

View file

@ -1,11 +1,13 @@
import webpack from 'webpack'
export type CompilerResult = {
errors: Error[],
errors: Error[]
warnings: Error[]
}
export function runCompiler (config: webpack.Configuration[]): Promise<CompilerResult> {
export function runCompiler(
config: webpack.Configuration[]
): Promise<CompilerResult> {
return new Promise(async (resolve, reject) => {
const compiler = webpack(config)
compiler.run((err, multiStats: any) => {
@ -13,17 +15,25 @@ export function runCompiler (config: webpack.Configuration[]): Promise<CompilerR
return reject(err)
}
const result: CompilerResult = multiStats.stats.reduce((result: CompilerResult, stat: webpack.Stats): CompilerResult => {
if (stat.compilation.errors.length > 0) {
result.errors.push(...stat.compilation.errors)
}
const result: CompilerResult = multiStats.stats.reduce(
(result: CompilerResult, stat: webpack.Stats): CompilerResult => {
const { errors, warnings } = stat.toJson({
all: false,
warnings: true,
errors: true,
})
if (errors.length > 0) {
result.errors.push(...errors)
}
if (stat.compilation.warnings.length > 0) {
result.warnings.push(...stat.compilation.warnings)
}
if (warnings.length > 0) {
result.warnings.push(...warnings)
}
return result
}, {errors: [], warnings: []})
return result
},
{ errors: [], warnings: [] }
)
resolve(result)
})

View file

@ -2,6 +2,7 @@ import {join} from 'path'
import {stringify} from 'querystring'
import {PAGES_DIR_ALIAS, DOT_NEXT_ALIAS} from '../lib/constants'
import {ServerlessLoaderQuery} from './webpack/loaders/next-serverless-loader'
import {UnifiedLoaderQuery} from './webpack/loaders/next-unified-loader'
type PagesMapping = {
[page: string]: string
@ -30,7 +31,7 @@ type Entrypoints = {
server: WebpackEntrypoints
}
export function createEntrypoints(pages: PagesMapping, target: 'server'|'serverless', buildId: string, config: any): Entrypoints {
export function createEntrypoints(pages: PagesMapping, target: 'server'|'serverless'|'unified', buildId: string, config: any): Entrypoints {
const client: WebpackEntrypoints = {}
const server: WebpackEntrypoints = {}
@ -60,6 +61,22 @@ export function createEntrypoints(pages: PagesMapping, target: 'server'|'serverl
client[bundlePath] = `next-client-pages-loader?${stringify({page, absolutePagePath})}!`
})
if(target === 'unified') {
const pagesArray: Array<String> = []
const absolutePagePaths: Array<String> = []
Object.keys(pages).forEach((page) => {
if(page === '/_document') {
return
}
pagesArray.push(page)
absolutePagePaths.push(pages[page])
});
const unifiedLoaderOptions: UnifiedLoaderQuery = {pages: pagesArray.join(','), absolutePagePaths: absolutePagePaths.join(','), ...defaultServerlessOptions};
server['index.js'] = `next-unified-loader?${stringify(unifiedLoaderOptions)}!`
}
return {
client,
server

View file

@ -3,36 +3,53 @@ import nanoid from 'nanoid'
import loadConfig from 'next-server/next-config'
import { PHASE_PRODUCTION_BUILD } from 'next-server/constants'
import getBaseWebpackConfig from './webpack-config'
import {generateBuildId} from './generate-build-id'
import {writeBuildId} from './write-build-id'
import {isWriteable} from './is-writeable'
import {runCompiler, CompilerResult} from './compiler'
import { generateBuildId } from './generate-build-id'
import { writeBuildId } from './write-build-id'
import { isWriteable } from './is-writeable'
import { runCompiler, CompilerResult } from './compiler'
import globModule from 'glob'
import {promisify} from 'util'
import {createPagesMapping, createEntrypoints} from './entries'
import { promisify } from 'util'
import { createPagesMapping, createEntrypoints } from './entries'
import formatWebpackMessages from '../client/dev-error-overlay/format-webpack-messages'
import chalk from 'chalk'
const glob = promisify(globModule)
function collectPages (directory: string, pageExtensions: string[]): Promise<string[]> {
return glob(`**/*.+(${pageExtensions.join('|')})`, {cwd: directory})
function collectPages(
directory: string,
pageExtensions: string[]
): Promise<string[]> {
return glob(`**/*.+(${pageExtensions.join('|')})`, { cwd: directory })
}
function printTreeView(list: string[]) {
list
.sort((a, b) => a > b ? 1 : -1)
.sort((a, b) => (a > b ? 1 : -1))
.forEach((item, i) => {
const corner = i === 0 ? list.length === 1 ? '─' : '┌' : i === list.length - 1 ? '└' : '├'
const corner =
i === 0
? list.length === 1
? '─'
: '┌'
: i === list.length - 1
? '└'
: '├'
console.log(` \x1b[90m${corner}\x1b[39m ${item}`)
})
console.log()
}
export default async function build (dir: string, conf = null): Promise<void> {
if (!await isWriteable(dir)) {
throw new Error('> Build directory is not writeable. https://err.sh/zeit/next.js/build-dir-not-writeable')
export default async function build(dir: string, conf = null): Promise<void> {
if (!(await isWriteable(dir))) {
throw new Error(
'> Build directory is not writeable. https://err.sh/zeit/next.js/build-dir-not-writeable'
)
}
console.log('Creating an optimized production build ...')
console.log()
const config = loadConfig(PHASE_PRODUCTION_BUILD, dir, conf)
const buildId = await generateBuildId(config.generateBuildId, nanoid)
const distDir = join(dir, config.distDir)
@ -42,34 +59,66 @@ export default async function build (dir: string, conf = null): Promise<void> {
const pages = createPagesMapping(pagePaths, config.pageExtensions)
const entrypoints = createEntrypoints(pages, config.target, buildId, config)
const configs: any = await Promise.all([
getBaseWebpackConfig(dir, { buildId, isServer: false, config, target: config.target, entrypoints: entrypoints.client }),
getBaseWebpackConfig(dir, { buildId, isServer: true, config, target: config.target, entrypoints: entrypoints.server })
getBaseWebpackConfig(dir, {
buildId,
isServer: false,
config,
target: config.target,
entrypoints: entrypoints.client,
}),
getBaseWebpackConfig(dir, {
buildId,
isServer: true,
config,
target: config.target,
entrypoints: entrypoints.server,
}),
])
let result: CompilerResult = {warnings: [], errors: []}
if (config.target === 'serverless') {
if (config.publicRuntimeConfig) throw new Error('Cannot use publicRuntimeConfig with target=serverless https://err.sh/zeit/next.js/serverless-publicRuntimeConfig')
let result: CompilerResult = { warnings: [], errors: [] }
if (config.target === 'serverless' || config.target === 'unified') {
if (config.publicRuntimeConfig)
throw new Error(
`Cannot use publicRuntimeConfig with target=${config.target} https://err.sh/zeit/next.js/serverless-publicRuntimeConfig`
)
const clientResult = await runCompiler([configs[0]])
// Fail build if clientResult contains errors
if(clientResult.errors.length > 0) {
result = {warnings: [...clientResult.warnings], errors: [...clientResult.errors]}
if (clientResult.errors.length > 0) {
result = {
warnings: [...clientResult.warnings],
errors: [...clientResult.errors],
}
} else {
const serverResult = await runCompiler([configs[1]])
result = {warnings: [...clientResult.warnings, ...serverResult.warnings], errors: [...clientResult.errors, ...serverResult.errors]}
result = {
warnings: [...clientResult.warnings, ...serverResult.warnings],
errors: [...clientResult.errors, ...serverResult.errors],
}
}
} else {
result = await runCompiler(configs)
}
if (result.warnings.length > 0) {
console.warn('> Emitted warnings from webpack')
result.warnings.forEach((warning) => console.warn(warning))
}
result = formatWebpackMessages(result)
if (result.errors.length > 0) {
result.errors.forEach((error) => console.error(error))
// Only keep the first error. Others are often indicative
// of the same problem, but confuse the reader with noise.
if (result.errors.length > 1) {
result.errors.length = 1
}
console.error(chalk.red('Failed to compile.\n'))
console.error(result.errors.join('\n\n'))
console.error()
throw new Error('> Build failed because of webpack errors')
} else if (result.warnings.length > 0) {
console.warn(chalk.yellow('Compiled with warnings.\n'))
console.warn(result.warnings.join('\n\n'))
console.warn()
} else {
console.log(chalk.green('Compiled successfully.\n'))
}
printTreeView(Object.keys(pages))

View file

@ -0,0 +1,13 @@
// This file is derived from Jest:
// https://github.com/facebook/jest/blob/d9d501ac342212b8a58ddb23a31518beb7b56f47/packages/jest-util/src/specialChars.ts#L18
const isWindows = process.platform === 'win32'
const isInteractive = process.stdout.isTTY
export function clearConsole() {
if (!isInteractive) {
return
}
process.stdout.write(isWindows ? '\x1B[2J\x1B[0f' : '\x1B[2J\x1B[3J\x1B[H')
}

View file

@ -0,0 +1,110 @@
import createStore from 'unistore'
import { store, OutputState } from './store'
import formatWebpackMessages from '../../client/dev-error-overlay/format-webpack-messages'
export function startedDevelopmentServer(appUrl: string) {
store.setState({ appUrl })
}
let previousClient: any = null
let previousServer: any = null
type WebpackStatus =
| { loading: true }
| {
loading: false
errors: string[] | null
warnings: string[] | null
}
type WebpackStatusStore = {
client: WebpackStatus
server: WebpackStatus
}
enum WebpackStatusPhase {
COMPILING = 1,
COMPILED_WITH_ERRORS = 2,
COMPILED_WITH_WARNINGS = 3,
COMPILED = 4,
}
function getWebpackStatusPhase(status: WebpackStatus): WebpackStatusPhase {
if (status.loading) {
return WebpackStatusPhase.COMPILING
}
if (status.errors) {
return WebpackStatusPhase.COMPILED_WITH_ERRORS
}
if (status.warnings) {
return WebpackStatusPhase.COMPILED_WITH_WARNINGS
}
return WebpackStatusPhase.COMPILED
}
const webpackStore = createStore<WebpackStatusStore>()
webpackStore.subscribe(state => {
const { client, server } = state
const [{ status }] = [
{ status: client, phase: getWebpackStatusPhase(client) },
{ status: server, phase: getWebpackStatusPhase(server) },
].sort((a, b) => a.phase.valueOf() - b.phase.valueOf())
const { bootstrap: bootstrapping, appUrl } = store.getState()
if (bootstrapping && status.loading) {
return
}
let nextStoreState: OutputState = {
bootstrap: false,
appUrl: appUrl!,
...status,
}
store.setState(nextStoreState, true)
})
export function watchCompiler(client: any, server: any) {
if (previousClient === client && previousServer === server) {
return
}
webpackStore.setState({
client: { loading: true },
server: { loading: true },
})
function tapCompiler(
key: string,
compiler: any,
onEvent: (status: WebpackStatus) => void
) {
compiler.hooks.invalid.tap(`NextJsInvalid-${key}`, () => {
onEvent({ loading: true })
})
compiler.hooks.done.tap(`NextJsDone-${key}`, (stats: any) => {
const { errors, warnings } = formatWebpackMessages(
stats.toJson({ all: false, warnings: true, errors: true })
)
onEvent({
loading: false,
errors: errors && errors.length ? errors : null,
warnings: warnings && warnings.length ? warnings : null,
})
})
}
tapCompiler('client', client, status =>
webpackStore.setState({ client: status })
)
tapCompiler('server', server, status =>
webpackStore.setState({ server: status })
)
previousClient = client
previousServer = server
}

View file

@ -0,0 +1,56 @@
import chalk from 'chalk'
import createStore from 'unistore'
import { clearConsole } from './clearConsole'
export type OutputState =
| { bootstrap: true; appUrl: string | null }
| ({ bootstrap: false; appUrl: string | null } & (
| { loading: true }
| {
loading: false
errors: string[] | null
warnings: string[] | null
}))
export const store = createStore<OutputState>({ appUrl: null, bootstrap: true })
store.subscribe(state => {
clearConsole()
if (state.bootstrap) {
console.log(chalk.cyan('Starting the development server ...'))
if (state.appUrl) {
console.log()
console.log(` > Waiting on ${state.appUrl!}`)
}
return
}
if (state.loading) {
console.log('Compiling ...')
return
}
if (state.errors) {
console.log(chalk.red('Failed to compile.'))
console.log()
console.log(state.errors[0])
return
}
if (state.warnings) {
console.log(chalk.yellow('Compiled with warnings.'))
console.log()
console.log(state.warnings.join('\n\n'))
return
}
console.log(chalk.green('Compiled successfully!'))
if (state.appUrl) {
console.log()
console.log(` > Ready on ${state.appUrl!}`)
}
console.log()
console.log('Note that pages will be compiled when you first load them.')
})

View file

@ -2,8 +2,6 @@ import path from 'path'
import webpack from 'webpack'
import resolve from 'resolve'
import CaseSensitivePathPlugin from 'case-sensitive-paths-webpack-plugin'
import FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin'
import WebpackBar from 'webpackbar'
import NextJsSsrImportPlugin from './webpack/plugins/nextjs-ssr-import'
import NextJsSSRModuleCachePlugin from './webpack/plugins/nextjs-ssr-module-cache'
import NextJsRequireCacheHotReloader from './webpack/plugins/nextjs-require-cache-hot-reloader'
@ -26,7 +24,7 @@ function externalsConfig (isServer, target) {
// When the serverless target is used all node_modules will be compiled into the output bundles
// So that the serverless bundles have 0 runtime dependencies
if (!isServer || target === 'serverless') {
if (!isServer || target === 'serverless' || target === 'unified') {
return externals
}
@ -81,7 +79,7 @@ function optimizationConfig ({ dev, isServer, totalPages, target }) {
}
}
if (isServer && target === 'serverless') {
if (isServer && (target === 'serverless' || target === 'unified')) {
return {
splitChunks: false,
minimizer: [
@ -166,7 +164,12 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
.filter((p) => !!p)
const distDir = path.join(dir, config.distDir)
const outputDir = target === 'serverless' ? 'serverless' : SERVER_DIRECTORY
let outputDir = SERVER_DIRECTORY
if (target === 'serverless') {
outputDir = 'serverless'
} else if (target === 'unified') {
outputDir = 'unified'
}
const outputPath = path.join(distDir, isServer ? outputDir : '')
const totalPages = Object.keys(entrypoints).length
const clientEntries = !isServer ? {
@ -278,10 +281,6 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
!isServer && new ReactLoadablePlugin({
filename: REACT_LOADABLE_MANIFEST
}),
new WebpackBar({
name: isServer ? 'server' : 'client'
}),
dev && !isServer && new FriendlyErrorsWebpackPlugin(),
// Even though require.cache is server only we have to clear assets from both compilations
// This is because the client compilation generates the build manifest that's used on the server side
dev && new NextJsRequireCacheHotReloader(),
@ -291,26 +290,28 @@ export default async function getBaseWebpackConfig (dir, {dev = false, isServer
dev && new CaseSensitivePathPlugin(), // Since on macOS the filesystem is case-insensitive this will make sure your path are case-sensitive
!dev && new webpack.HashedModuleIdsPlugin(),
// Removes server/client code by minifier
new webpack.DefinePlugin(Object.assign(
{},
config.env ? Object.keys(config.env)
.reduce((acc, key) => ({
new webpack.DefinePlugin({
...(Object.keys(config.env).reduce((acc, key) => {
if (/^(?:NODE_.+)|(?:__.+)$/i.test(key)) {
throw new Error(`The key "${key}" under "env" in next.config.js is not allowed. https://err.sh/zeit/next.js/env-key-not-allowed`)
}
return {
...acc,
...{ [`process.env.${key}`]: JSON.stringify(config.env[key]) }
}), {}) : {},
{
'process.crossOrigin': JSON.stringify(config.crossOrigin),
'process.browser': JSON.stringify(!isServer)
}
)),
[`process.env.${key}`]: JSON.stringify(config.env[key])
}
}, {})),
'process.crossOrigin': JSON.stringify(config.crossOrigin),
'process.browser': JSON.stringify(!isServer)
}),
// This is used in client/dev-error-overlay/hot-dev-client.js to replace the dist directory
!isServer && dev && new webpack.DefinePlugin({
'process.env.__NEXT_DIST_DIR': JSON.stringify(distDir)
}),
target !== 'serverless' && isServer && new PagesManifestPlugin(),
target !== 'serverless' && target !== 'unified' && isServer && new PagesManifestPlugin(),
!isServer && new BuildManifestPlugin(),
isServer && new NextJsSsrImportPlugin(),
target !== 'serverless' && isServer && new NextJsSSRModuleCachePlugin({outputPath}),
target !== 'serverless' && target !== 'unified' && isServer && new NextJsSSRModuleCachePlugin({ outputPath }),
!dev && new webpack.IgnorePlugin({
checkResource: (resource) => {
return /react-is/.test(resource)

View file

@ -0,0 +1,135 @@
import { loader } from 'webpack';
import { join } from 'path';
import { parse } from 'querystring';
import { BUILD_MANIFEST, REACT_LOADABLE_MANIFEST } from 'next-server/constants';
export type UnifiedLoaderQuery = {
pages: string
distDir: string
absolutePagePaths: string
absoluteAppPath: string
absoluteDocumentPath: string
absoluteErrorPath: string
buildId: string
assetPrefix: string
}
const nextUnifiedLoader: loader.Loader = function() {
const {distDir, absolutePagePaths, pages, buildId, assetPrefix, absoluteAppPath, absoluteDocumentPath, absoluteErrorPath}: UnifiedLoaderQuery =
typeof this.query === 'string' ? parse(this.query.substr(1)) : this.query
const buildManifest = join(distDir, BUILD_MANIFEST).replace(/\\/g, '/')
const reactLoadableManifest = join(distDir, REACT_LOADABLE_MANIFEST).replace(/\\/g, '/')
const parsedPagePaths = absolutePagePaths.split(',')
const parsedPages = pages.split(',')
return `
import {renderToHTML} from 'next-server/dist/server/render'
import buildManifest from '${buildManifest}'
import reactLoadableManifest from '${reactLoadableManifest}'
import Document from '${absoluteDocumentPath}'
import Error from '${absoluteErrorPath}'
import App from '${absoluteAppPath}'
${parsedPagePaths
.map(
(absolutePagePath, index) =>
`import page${index} from '${absolutePagePath}'`,
)
.join('\n')}
const errorPage = '/_error'
const routes = ${JSON.stringify(
Object.assign(
{},
...parsedPages.map((page, index) => ({ [page]: `page${index}` })),
),
).replace(/"(page\d+)"/g, '$1')}
function matchRoute(url) {
let page = '/index'
if (url === '/' && routes.hasOwnProperty(page)) {
return [page, routes[page]]
}
if (routes.hasOwnProperty(url)) {
return [url, routes[url]]
}
const splitUrl = url.split('/');
for (let i = splitUrl.length; i > 0; i--) {
const currentPrefix = splitUrl.slice(0, i).join('/')
if (routes.hasOwnProperty(currentPrefix)) {
return [currentPrefix, routes[currentPrefix]]
}
}
return [errorPage, routes[errorPage]]
};
const errorResponse = { status: 500, body: 'Internal Server Error', headers: {} }
export async function render(url, query = {}, reqHeaders = {}) {
const req = {
headers: reqHeaders,
method: 'GET',
url
}
const [page, Component] = matchRoute(url)
const headers = {}
let body = ''
const res = {
statusCode: 200,
finished: false,
headersSent: false,
setHeader(name, value) {
headers[name.toLowerCase()] = value
},
getHeader(name) {
return headers[name.toLowerCase()]
}
};
const options = {
App,
Document,
buildManifest,
reactLoadableManifest,
buildId: ${JSON.stringify(buildId)},
assetPrefix: ${JSON.stringify(assetPrefix)},
Component
}
try {
if (page === '/_error') {
res.statusCode = 404
}
body = await renderToHTML(req, res, page, query, Object.assign({}, options))
} catch (err) {
if (err.code === 'ENOENT') {
res.statusCode = 404
body = await renderToHTML(req, res, "/_error", query, Object.assign({}, options, {
Component: Error
}))
} else {
console.error(err)
try {
res.statusCode = 500
body = await renderToHTML(req, res, "/_error", query, Object.assign({}, options, {
Component: Error,
err
}))
} catch (e) {
console.error(e)
return errorResponse; // non-html fatal/fallback error
}
}
}
return {
status: res.statusCode,
headers: Object.assign({
'content-type': 'text/html; charset=utf-8',
'content-length': Buffer.byteLength(body)
}, headers),
body
}
}
`;
};
export default nextUnifiedLoader;

View file

@ -1,7 +1,7 @@
/**
MIT License
Copyright (c) 2013-present, Facebook, Inc.
Copyright (c) 2015-present, Facebook, Inc.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@ -21,16 +21,12 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// This file is based on https://github.com/facebook/create-react-app/blob/v1.1.4/packages/react-dev-utils/formatWebpackMessages.js
// It's been edited to remove chalk
// This file is based on https://github.com/facebook/create-react-app/blob/7b1a32be6ec9f99a6c9a3c66813f3ac09c4736b9/packages/react-dev-utils/formatWebpackMessages.js
// It's been edited to remove chalk and CRA-specific logic
'use strict'
// Some custom utilities to prettify Webpack output.
// This is quite hacky and hopefully won't be needed when Webpack fixes this.
// https://github.com/webpack/webpack/issues/2878
var friendlySyntaxErrorLabel = 'Syntax error:'
const friendlySyntaxErrorLabel = 'Syntax error:'
function isLikelyASyntaxError (message) {
return message.indexOf(friendlySyntaxErrorLabel) !== -1
@ -39,112 +35,99 @@ function isLikelyASyntaxError (message) {
// Cleans up webpack error messages.
// eslint-disable-next-line no-unused-vars
function formatMessage (message, isError) {
var lines = message.split('\n')
let lines = message.split('\n')
if (lines.length > 2 && lines[1] === '') {
// Remove extra newline.
// Strip Webpack-added headers off errors/warnings
// https://github.com/webpack/webpack/blob/master/lib/ModuleError.js
lines = lines.filter(line => !/Module [A-z ]+\(from/.test(line))
// Transform parsing error into syntax error
// TODO: move this to our ESLint formatter?
lines = lines.map(line => {
const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(
line
)
if (!parsingError) {
return line
}
const [, errorLine, errorColumn, errorMessage] = parsingError
return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`
})
message = lines.join('\n')
// Smoosh syntax errors (commonly found in CSS)
message = message.replace(
/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g,
`${friendlySyntaxErrorLabel} $3 ($1:$2)\n`
)
// Remove columns from ESLint formatter output (we added these for more
// accurate syntax errors)
message = message.replace(/Line (\d+):\d+:/g, 'Line $1:')
// Clean up export errors
message = message.replace(
/^.*export '(.+?)' was not found in '(.+?)'.*$/gm,
`Attempted import error: '$1' is not exported from '$2'.`
)
message = message.replace(
/^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm,
`Attempted import error: '$2' does not contain a default export (imported as '$1').`
)
message = message.replace(
/^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm,
`Attempted import error: '$1' is not exported from '$3' (imported as '$2').`
)
lines = message.split('\n')
// Remove leading newline
if (lines.length > 2 && lines[1].trim() === '') {
lines.splice(1, 1)
}
// Remove webpack-specific loader notation from filename.
// Before:
// ./~/css-loader!./~/postcss-loader!./src/App.css
// After:
// ./src/App.css
if (lines[0].lastIndexOf('!') !== -1) {
lines[0] = lines[0].substr(lines[0].lastIndexOf('!') + 1)
}
// Remove unnecessary stack added by `thread-loader`
var threadLoaderIndex = -1
lines.forEach(function (line, index) {
if (threadLoaderIndex !== -1) {
return
}
if (/thread.loader/i.test(line)) {
threadLoaderIndex = index
}
})
if (threadLoaderIndex !== -1) {
lines = lines.slice(0, threadLoaderIndex)
}
lines = lines.filter(function (line) {
// Webpack adds a list of entry points to warning messages:
// @ ./src/index.js
// @ multi react-scripts/~/react-dev-utils/webpackHotDevClient.js ...
// It is misleading (and unrelated to the warnings) so we clean it up.
// It is only useful for syntax errors but we have beautiful frames for them.
return line.indexOf(' @ ') !== 0
})
// line #0 is filename
// line #1 is the main error message
if (!lines[0] || !lines[1]) {
return lines.join('\n')
}
// Clean up file name
lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, '$1')
// Cleans up verbose "module not found" messages for files and packages.
if (lines[1].indexOf('Module not found: ') === 0) {
if (lines[1] && lines[1].indexOf('Module not found: ') === 0) {
lines = [
lines[0],
// Clean up message because "Module not found: " is descriptive enough.
lines[1]
.replace("Cannot resolve 'file' or 'directory' ", '')
.replace('Cannot resolve module ', '')
.replace('Error: ', '')
.replace('[CaseSensitivePathsPlugin] ', '')
.replace('Module not found: Cannot find file:', 'Cannot find file:')
]
}
// Cleans up syntax error messages.
if (lines[1].indexOf('Module build failed: ') === 0) {
lines[1] = lines[1].replace(
'Module build failed: SyntaxError:',
friendlySyntaxErrorLabel
)
}
// Clean up export errors.
// TODO: we should really send a PR to Webpack for this.
var exportError = /\s*(.+?)\s*(")?export '(.+?)' was not found in '(.+?)'/
if (lines[1].match(exportError)) {
lines[1] = lines[1].replace(
exportError,
"$1 '$4' does not contain an export named '$3'."
)
}
// Reassemble the message.
message = lines.join('\n')
// Internal stacks are generally useless so we strip them... with the
// exception of stacks containing `webpack:` because they're normally
// from user code generated by WebPack. For more information see
// from user code generated by Webpack. For more information see
// https://github.com/facebook/create-react-app/pull/1050
message = message.replace(
/^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm,
''
) // at ... ...:x:y
message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, '') // at <anonymous>
lines = message.split('\n')
// Remove duplicated newlines
lines = lines.filter(
(line, index, arr) =>
index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim()
)
// Reassemble the message
message = lines.join('\n')
return message.trim()
}
function formatWebpackMessages (json) {
var formattedErrors = json.errors.map(function (message) {
const formattedErrors = json.errors.map(function (message) {
return formatMessage(message, true)
})
var formattedWarnings = json.warnings.map(function (message) {
const formattedWarnings = json.warnings.map(function (message) {
return formatMessage(message, false)
})
var result = {
errors: formattedErrors,
warnings: formattedWarnings
}
const result = { errors: formattedErrors, warnings: formattedWarnings }
if (result.errors.some(isLikelyASyntaxError)) {
// If there are any syntax errors, show just them.
// This prevents a confusing ESLint parsing error
// preceding a much more useful Babel syntax error.
result.errors = result.errors.filter(isLikelyASyntaxError)
}
return result

View file

@ -8,25 +8,37 @@ const wsProtocol = protocol.includes('https') ? 'wss' : 'ws'
const retryTime = 5000
let ws = null
let lastHref = null
let wsConnectTries = 0
let showedWarning = false
export default async ({ assetPrefix }) => {
Router.ready(() => {
Router.events.on('routeChangeComplete', ping)
})
const setup = async (reconnect) => {
const setup = async () => {
if (ws && ws.readyState === ws.OPEN) {
return Promise.resolve()
} else if (wsConnectTries > 1) {
return
}
wsConnectTries++
return new Promise(resolve => {
ws = new WebSocket(`${wsProtocol}://${hostname}:${process.env.NEXT_WS_PORT}${process.env.NEXT_WS_PROXY_PATH}`)
ws.onopen = () => resolve()
ws = new WebSocket(`${wsProtocol}://${hostname}:${process.env.__NEXT_WS_PORT}${process.env.__NEXT_WS_PROXY_PATH}`)
ws.onopen = () => {
wsConnectTries = 0
resolve()
}
ws.onclose = () => {
setTimeout(async () => {
// check if next restarted and we have to reload to get new port
await fetch(`${assetPrefix}/_next/on-demand-entries-ping`)
.then(res => res.status === 200 && location.reload())
.then(res => {
// Only reload if next was restarted and we have a new WebSocket port
if (res.status === 200 && res.headers.get('port') !== process.env.__NEXT_WS_PORT + '') {
location.reload()
}
})
.catch(() => {})
await setup(true)
resolve()
@ -49,11 +61,36 @@ export default async ({ assetPrefix }) => {
}
})
}
await setup()
setup()
async function ping () {
if (ws.readyState === ws.OPEN) {
ws.send(Router.pathname)
// Use WebSocket if available
if (ws && ws.readyState === ws.OPEN) {
return ws.send(Router.pathname)
}
if (!showedWarning) {
console.warn('onDemandEntries WebSocket failed to connect, falling back to fetch based pinging. https://err.sh/zeit/next.js/on-demand-entries-websocket-unavailable')
showedWarning = true
}
// If not, fallback to fetch based pinging
try {
const url = `${assetPrefix || ''}/_next/on-demand-entries-ping?page=${Router.pathname}`
const res = await fetch(url, {
credentials: 'same-origin'
})
const payload = await res.json()
if (payload.invalid) {
// Payload can be invalid even if the page does not exist.
// So, we need to make sure it exists before reloading.
const pageRes = await fetch(location.href, {
credentials: 'same-origin'
})
if (pageRes.status === 200) {
location.reload()
}
}
} catch (err) {
console.error(`Error with on-demand-entries-ping: ${err.message}`)
}
}

View file

@ -1,6 +1,6 @@
{
"name": "next",
"version": "8.0.1",
"version": "8.0.2-canary.3",
"description": "The React Framework",
"main": "./dist/server/next.js",
"license": "MIT",
@ -19,7 +19,8 @@
"error.js",
"head.js",
"link.js",
"router.js"
"router.js",
"amp.js"
],
"bin": {
"next": "./dist/bin/next"
@ -58,13 +59,13 @@
"babel-plugin-transform-react-remove-prop-types": "0.4.15",
"cacache": "^11.0.2",
"case-sensitive-paths-webpack-plugin": "2.1.2",
"chalk": "2.4.2",
"cross-spawn": "5.1.0",
"del": "3.0.0",
"event-source-polyfill": "0.0.12",
"find-cache-dir": "2.0.0",
"find-up": "2.1.0",
"fresh": "0.5.2",
"friendly-errors-webpack-plugin": "1.7.0",
"glob": "7.1.2",
"hoist-non-react-statics": "3.2.0",
"http-status": "1.0.1",
@ -72,7 +73,7 @@
"loader-utils": "1.1.0",
"mkdirp-then": "1.2.0",
"nanoid": "1.2.1",
"next-server": "8.0.1",
"next-server": "8.0.2-canary.3",
"prop-types": "15.6.2",
"prop-types-exact": "1.2.0",
"react-error-overlay": "4.0.0",
@ -87,12 +88,12 @@
"terser": "3.16.1",
"tty-aware-progress": "1.0.3",
"unfetch": "3.0.0",
"unistore": "3.2.1",
"url": "0.11.0",
"webpack": "4.29.0",
"webpack-dev-middleware": "3.4.0",
"webpack-hot-middleware": "2.24.3",
"webpack-sources": "1.3.0",
"webpackbar": "3.1.4 ",
"worker-farm": "1.5.2",
"ws": "6.1.2"
},

View file

@ -4,10 +4,6 @@ import PropTypes from 'prop-types'
import {htmlEscapeJsonString} from '../server/htmlescape'
import flush from 'styled-jsx/server'
const Fragment = React.Fragment || function Fragment ({ children }) {
return <div>{children}</div>
}
export default class Document extends Component {
static childContextTypes = {
_documentProps: PropTypes.any,
@ -31,7 +27,7 @@ export default class Document extends Component {
}
render () {
return <html>
return <html amp={this.props.amphtml ? '' : null}>
<Head />
<body>
<Main />
@ -115,10 +111,9 @@ export class Head extends Component {
}
render () {
const { head, styles, assetPrefix, __NEXT_DATA__ } = this.context._documentProps
const { asPath, ampEnabled, head, styles, amphtml, assetPrefix, __NEXT_DATA__ } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
const { page, buildId } = __NEXT_DATA__
const pagePathname = getPagePathname(page)
let children = this.props.children
// show a warning if Head contains <title> (only in development)
@ -134,12 +129,26 @@ export class Head extends Component {
return <head {...this.props}>
{children}
{head}
{page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}${_devOnlyInvalidateCacheQueryString}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />}
{amphtml && <>
<meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"/>
<link rel="canonical" href={asPath === '/amp' ? '/' : asPath.replace(/\/amp$/, '')} />
{/* https://www.ampproject.org/docs/fundamentals/optimize_amp#optimize-the-amp-runtime-loading */}
<link rel="preload" as="script" href="https://cdn.ampproject.org/v0.js" />
{/* Add custom styles before AMP styles to prevent accidental overrides */}
{styles && <style amp-custom="" dangerouslySetInnerHTML={{__html: styles.map((style) => style.props.dangerouslySetInnerHTML.__html)}} />}
<style amp-boilerplate="" dangerouslySetInnerHTML={{__html: `body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}`}}></style>
<noscript><style amp-boilerplate="" dangerouslySetInnerHTML={{__html: `body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}`}}></style></noscript>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</>}
{!amphtml && <>
{ampEnabled && <link rel="amphtml" href={asPath === '/' ? '/amp' : (asPath.replace(/\/$/, '') + '/amp')} />}
{page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages${getPagePathname(page)}${_devOnlyInvalidateCacheQueryString}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />}
<link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages/_app.js${_devOnlyInvalidateCacheQueryString}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />
{this.getPreloadDynamicChunks()}
{this.getPreloadMainLinks()}
{this.getCssLinks()}
{styles || null}
</>}
</head>
}
}
@ -221,25 +230,29 @@ export class NextScript extends Component {
}
render () {
const { staticMarkup, assetPrefix, devFiles, __NEXT_DATA__ } = this.context._documentProps
const { staticMarkup, assetPrefix, amphtml, devFiles, __NEXT_DATA__ } = this.context._documentProps
const { _devOnlyInvalidateCacheQueryString } = this.context
if(amphtml) {
return null
}
const { page, buildId } = __NEXT_DATA__
const pagePathname = getPagePathname(page)
if (process.env.NODE_ENV !== 'production') {
if (this.props.crossOrigin) console.warn('Warning: `NextScript` attribute `crossOrigin` is deprecated. https://err.sh/next.js/doc-crossorigin-deprecated')
}
return <Fragment>
return <>
{devFiles ? devFiles.map((file) => <script key={file} src={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />) : null}
{staticMarkup ? null : <script id="__NEXT_DATA__" type="application/json" nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} dangerouslySetInnerHTML={{
__html: NextScript.getInlineScriptSource(this.context._documentProps)
}} />}
{page !== '/_error' && <script async id={`__NEXT_PAGE__${page}`} src={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />}
{page !== '/_error' && <script async id={`__NEXT_PAGE__${page}`} src={`${assetPrefix}/_next/static/${buildId}/pages${getPagePathname(page)}${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />}
<script async id={`__NEXT_PAGE__/_app`} src={`${assetPrefix}/_next/static/${buildId}/pages/_app.js${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />
{staticMarkup ? null : this.getDynamicChunks()}
{staticMarkup ? null : this.getScripts()}
</Fragment>
</>
}
}

View file

@ -12,6 +12,7 @@ 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'
const glob = promisify(globModule)
@ -167,8 +168,8 @@ export default class HotReloader {
addWsConfig (configs) {
const { websocketProxyPath, websocketProxyPort } = this.config.onDemandEntries
const opts = {
'process.env.NEXT_WS_PORT': websocketProxyPort || this.wsPort,
'process.env.NEXT_WS_PROXY_PATH': JSON.stringify(websocketProxyPath)
'process.env.__NEXT_WS_PORT': websocketProxyPort || this.wsPort,
'process.env.__NEXT_WS_PROXY_PATH': JSON.stringify(websocketProxyPath)
}
configs[0].plugins.push(new webpack.DefinePlugin(opts))
}
@ -259,6 +260,11 @@ export default class HotReloader {
}
async prepareBuildTools (multiCompiler) {
watchCompiler(
multiCompiler.compilers[0],
multiCompiler.compilers[1]
)
// This plugin watches for changes to _document.js and notifies the client side that it should reload the page
multiCompiler.compilers[1].hooks.done.tap('NextjsHotReloaderForServer', (stats) => {
if (!this.initialized) {

View file

@ -91,7 +91,7 @@ export default class DevServer extends Server {
return routes
}
async renderToHTML (req, res, pathname, query) {
async renderToHTML (req, res, pathname, query, options) {
const compilationErr = await this.getCompilationError(pathname)
if (compilationErr) {
res.statusCode = 500
@ -109,7 +109,7 @@ export default class DevServer extends Server {
if (!this.quiet) console.error(err)
}
return super.renderToHTML(req, res, pathname, query)
return super.renderToHTML(req, res, pathname, query, options)
}
async renderErrorToHTML (err, req, res, pathname, query) {

View file

@ -1,6 +1,7 @@
import DynamicEntryPlugin from 'webpack/lib/DynamicEntryPlugin'
import { EventEmitter } from 'events'
import { join } from 'path'
import {parse} from 'url'
import fs from 'fs'
import promisify from '../lib/promisify'
import globModule from 'glob'
@ -152,6 +153,40 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
reloadCallbacks = null
}
function handlePing (pg, socket) {
const page = normalizePage(pg)
const entryInfo = entries[page]
// If there's no entry.
// Then it seems like an weird issue.
if (!entryInfo) {
const message = `Client pings, but there's no entry for page: ${page}`
console.error(message)
return sendJson(socket, { invalid: true })
}
// 404 is an on demand entry but when a new page is added we have to refresh the page
if (page === '/_error') {
sendJson(socket, { invalid: true })
} else {
sendJson(socket, { success: true })
}
// We don't need to maintain active state of anything other than BUILT entries
if (entryInfo.status !== BUILT) return
// If there's an entryInfo
if (!lastAccessPages.includes(page)) {
lastAccessPages.unshift(page)
// Maintain the buffer max length
if (lastAccessPages.length > pagesBufferLength) {
lastAccessPages.pop()
}
}
entryInfo.lastActiveTime = Date.now()
}
return {
waitUntilReloaded () {
if (!reloading) return Promise.resolve(true)
@ -225,37 +260,8 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
wsConnection (ws) {
ws.onmessage = ({ data }) => {
const page = normalizePage(data)
const entryInfo = entries[page]
// If there's no entry.
// Then it seems like an weird issue.
if (!entryInfo) {
const message = `Client pings, but there's no entry for page: ${page}`
console.error(message)
return sendJson(ws, { invalid: true })
}
// 404 is an on demand entry but when a new page is added we have to refresh the page
if (page === '/_error') {
sendJson(ws, { invalid: true })
} else {
sendJson(ws, { success: true })
}
// We don't need to maintain active state of anything other than BUILT entries
if (entryInfo.status !== BUILT) return
// If there's an entryInfo
if (!lastAccessPages.includes(page)) {
lastAccessPages.unshift(page)
// Maintain the buffer max length
if (lastAccessPages.length > pagesBufferLength) {
lastAccessPages.pop()
}
}
entryInfo.lastActiveTime = Date.now()
// `data` should be the page here
handlePing(data, ws)
}
},
@ -280,6 +286,12 @@ export default function onDemandEntryHandler (devMiddleware, multiCompiler, {
} else {
if (!/^\/_next\/on-demand-entries-ping/.test(req.url)) return next()
const { query } = parse(req.url, true)
if (query.page) {
return handlePing(query.page, res)
}
res.statusCode = 200
res.setHeader('port', wsPort)
res.end('200')
@ -328,8 +340,17 @@ export function normalizePage (page) {
return unixPagePath.replace(/\/index$/, '')
}
function sendJson (ws, data) {
ws.send(JSON.stringify(data))
function sendJson (socket, data) {
data = JSON.stringify(data)
// Handle fetch request
if (socket.setHeader) {
socket.setHeader('content-type', 'application/json')
socket.status = 200
return socket.end(data)
}
// Should be WebSocket so just send
socket.send(data)
}
// Make sure only one invalidation happens at a time

View file

@ -40,7 +40,7 @@ try {
if (file.base === 'next-dev.js') result.outputText = result.outputText.replace('// REPLACE_NOOP_IMPORT', `import('./noop');`)
// update file's data
file.data = Buffer.from(result.outputText.replace(/process\.env\.NEXT_VERSION/, `"${require('./package.json').version}"`), 'utf8')
file.data = Buffer.from(result.outputText.replace(/process\.env\.__NEXT_VERSION/, `"${require('./package.json').version}"`), 'utf8')
})
}
} catch (err) {

View file

@ -0,0 +1,9 @@
module.exports = {
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60
},
experimental: {
amp: true
}
}

View file

@ -0,0 +1 @@
export default () => 'Hello World'

View file

@ -0,0 +1,6 @@
import {useAmp} from 'next/amp'
export default () => {
const isAmp = useAmp()
return `Hello ${isAmp ? 'AMP' : 'others'}`
}

View file

@ -0,0 +1,117 @@
/* eslint-env jest */
/* global jasmine */
import { join } from 'path'
import {
nextServer,
nextBuild,
startApp,
stopApp,
renderViaHTTP
} from 'next-test-utils'
import cheerio from 'cheerio'
import amphtmlValidator from 'amphtml-validator'
const appDir = join(__dirname, '../')
let appPort
let server
let app
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
const context = {}
async function validateAMP (html) {
const validator = await amphtmlValidator.getInstance()
const result = validator.validateString(html)
if (result.status !== 'PASS') {
for (let ii = 0; ii < result.errors.length; ii++) {
const error = result.errors[ii]
let msg = 'line ' + error.line + ', col ' + error.col + ': ' + error.message
if (error.specUrl !== null) {
msg += ' (see ' + error.specUrl + ')'
}
((error.severity === 'ERROR') ? console.error : console.warn)(msg)
}
}
expect(result.status).toBe('PASS')
}
describe('AMP Usage', () => {
beforeAll(async () => {
await nextBuild(appDir)
app = nextServer({
dir: join(__dirname, '../'),
dev: false,
quiet: true
})
server = await startApp(app)
context.appPort = appPort = server.address().port
})
afterAll(() => stopApp(server))
describe('With basic usage', () => {
it('should render the page', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/Hello World/)
})
})
describe('With basic AMP usage', () => {
it('should render the page as valid AMP', async () => {
const html = await renderViaHTTP(appPort, '/amp')
await validateAMP(html)
expect(html).toMatch(/Hello World/)
})
it('should add link preload for amp script', async () => {
const html = await renderViaHTTP(appPort, '/amp')
await validateAMP(html)
const $ = cheerio.load(html)
expect($($('link[rel=preload]').toArray().find(i => $(i).attr('href') === 'https://cdn.ampproject.org/v0.js')).attr('href')).toBe('https://cdn.ampproject.org/v0.js')
})
it('should add custom styles before amp boilerplate styles', async () => {
const html = await renderViaHTTP(appPort, '/amp')
await validateAMP(html)
const $ = cheerio.load(html)
const order = []
$('style').toArray().forEach((i) => {
if ($(i).attr('amp-custom') === '') {
order.push('amp-custom')
}
if ($(i).attr('amp-boilerplate') === '') {
order.push('amp-boilerplate')
}
})
expect(order).toEqual(['amp-custom', 'amp-boilerplate', 'amp-boilerplate'])
})
})
describe('With AMP context', () => {
it('should render the normal page that uses the AMP hook', async () => {
const html = await renderViaHTTP(appPort, '/use-amp-hook')
expect(html).toMatch(/Hello others/)
})
it('should render the AMP page that uses the AMP hook', async () => {
const html = await renderViaHTTP(appPort, '/use-amp-hook/amp')
await validateAMP(html)
expect(html).toMatch(/Hello AMP/)
})
})
describe('canonical amphtml', () => {
it('should render link rel amphtml', async () => {
const html = await renderViaHTTP(appPort, '/use-amp-hook')
const $ = cheerio.load(html)
expect($('link[rel=amphtml]').first().attr('href')).toBe('/use-amp-hook/amp')
})
it('should render the AMP page that uses the AMP hook', async () => {
const html = await renderViaHTTP(appPort, '/use-amp-hook/amp')
const $ = cheerio.load(html)
await validateAMP(html)
expect($('link[rel=canonical]').first().attr('href')).toBe('/use-amp-hook')
})
})
})

View file

@ -0,0 +1,8 @@
import dynamic from 'next/dynamic'
const Nested2 = dynamic(() => import('./nested2'))
export default () => <div>
Nested 1
<Nested2 />
</div>

View file

@ -0,0 +1,12 @@
import dynamic from 'next/dynamic'
const BrowserLoaded = dynamic(async () => () => <div>Browser hydrated</div>, {
ssr: false
})
export default () => <div>
<div>
Nested 2
</div>
<BrowserLoaded />
</div>

View file

@ -0,0 +1,5 @@
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('../../components/nested1'))
export default DynamicComponent

View file

@ -37,6 +37,26 @@ export default (context, render) => {
}
})
it('should hydrate nested chunks', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/dynamic/nested')
await check(() => browser.elementByCss('body').text(), /Nested 1/)
await check(() => browser.elementByCss('body').text(), /Nested 2/)
await check(() => browser.elementByCss('body').text(), /Browser hydrated/)
const logs = await browser.log('browser')
logs.forEach(logItem => {
expect(logItem.message).not.toMatch(/Expected server HTML to contain/)
})
} finally {
if (browser) {
browser.close()
}
}
})
it('should render the component Head content', async () => {
let browser
try {

View file

@ -103,4 +103,12 @@ describe('On Demand Entries', () => {
}
}
})
it('should able to ping using fetch fallback', async () => {
const about = await renderViaHTTP(context.appPort, '/_next/on-demand-entries-ping', {page: '/about'})
expect(JSON.parse(about)).toEqual({success: true})
const third = await renderViaHTTP(context.appPort, '/_next/on-demand-entries-ping', {page: '/third'})
expect(JSON.parse(third)).toEqual({success: true})
})
})

View file

@ -0,0 +1 @@
export default () => <div>Hello World</div>

View file

@ -0,0 +1,69 @@
/* eslint-env jest */
/* global jasmine */
import { dirname, join } from 'path'
import {
nextServer,
startApp,
stopApp,
renderViaHTTP
} from 'next-test-utils'
import spawn from 'cross-spawn'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
function runNextCommand (argv, options = {}) {
return new Promise((resolve, reject) => {
console.log(`Running command "next ${argv.join(' ')}"`)
const instance = spawn('node', [join(dirname(require.resolve('next/package')), 'dist/bin/next'), ...argv], { ...options.spawnOptions, cwd: join(__dirname, '..'), stdio: ['ignore', 'pipe', 'pipe'] })
let stderrOutput = ''
if (options.stderr) {
instance.stderr.on('data', function (chunk) {
stderrOutput += chunk
})
}
let stdoutOutput = ''
if (options.stdout) {
instance.stdout.on('data', function (chunk) {
stdoutOutput += chunk
})
}
instance.on('close', () => {
resolve({
stdout: stdoutOutput,
stderr: stderrOutput
})
})
instance.on('error', (err) => {
err.stdout = stdoutOutput
err.stderr = stderrOutput
reject(err)
})
})
}
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})
expect(result.stderr).toBe('')
const app = nextServer({
dir: join(__dirname, '../build'),
dev: false,
quiet: true
})
const server = await startApp(app)
const appPort = server.address().port
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/Hello World/)
await stopApp(server)
})
})
})

View file

@ -2,11 +2,19 @@ const withCSS = require('@zeit/next-css')
const withSass = require('@zeit/next-sass')
const path = require('path')
module.exports = withCSS(withSass({
env: {
...(process.env.ENABLE_ENV_FAIL_UNDERSCORE ? {
'__NEXT_MY_VAR': 'test'
} : {}),
...(process.env.ENABLE_ENV_FAIL_NODE ? {
'NODE_ENV': 'abc'
} : {})
},
onDemandEntries: {
// Make sure entries are not getting disposed.
maxInactiveAge: 1000 * 60 * 60
},
webpack (config, {buildId}) {
webpack (config) {
// 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(

View file

@ -5,18 +5,20 @@ import {
nextServer,
nextBuild,
startApp,
stopApp
stopApp,
runNextCommand
} from 'next-test-utils'
import webdriver from 'next-webdriver'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
const appDir = join(__dirname, '../')
let appPort
let server
describe('Production Config Usage', () => {
beforeAll(async () => {
const appDir = join(__dirname, '../')
await nextBuild(appDir)
const app = nextServer({
dir: join(__dirname, '../'),
@ -37,6 +39,34 @@ describe('Production Config Usage', () => {
})
})
describe('env', () => {
it('should fail with __ in env key', async () => {
const result = await runNextCommand(['build', appDir], {spawnOptions: {
env: {
...process.env,
ENABLE_ENV_FAIL_UNDERSCORE: true
}
},
stdout: 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: {
env: {
...process.env,
ENABLE_ENV_FAIL_NODE: true
}
},
stdout: true,
stderr: true})
expect(result.stderr).toMatch(/The key "NODE_ENV" under/)
})
})
describe('with generateBuildId', () => {
it('should add the custom buildid', async () => {
const browser = await webdriver(appPort, '/')

View file

@ -69,7 +69,14 @@ export function runNextCommand (argv, options = {}) {
const cwd = path.dirname(require.resolve('next/package'))
return new Promise((resolve, reject) => {
console.log(`Running command "next ${argv.join(' ')}"`)
const instance = spawn('node', ['dist/bin/next', ...argv], { cwd, stdio: options.stdout ? ['ignore', 'pipe', 'ignore'] : 'inherit' })
const instance = spawn('node', ['dist/bin/next', ...argv], { ...options.spawnOptions, cwd, stdio: ['ignore', 'pipe', 'pipe'] })
let stderrOutput = ''
if (options.stderr) {
instance.stderr.on('data', function (chunk) {
stderrOutput += chunk
})
}
let stdoutOutput = ''
if (options.stdout) {
@ -80,11 +87,14 @@ export function runNextCommand (argv, options = {}) {
instance.on('close', () => {
resolve({
stdout: stdoutOutput
stdout: stdoutOutput,
stderr: stderrOutput
})
})
instance.on('error', (err) => {
err.stdout = stdoutOutput
err.stderr = stderrOutput
reject(err)
})
})

157
yarn.lock
View file

@ -1879,6 +1879,15 @@ amdefine@>=0.0.4:
resolved "https://registry.yarnpkg.com/amdefine/-/amdefine-1.0.1.tgz#4a5282ac164729e93619bcfd3ad151f817ce91f5"
integrity sha1-SlKCrBZHKek2Gbz9OtFR+BfOkfU=
amphtml-validator@1.0.23:
version "1.0.23"
resolved "https://registry.yarnpkg.com/amphtml-validator/-/amphtml-validator-1.0.23.tgz#dba0c3854289563c0adaac292cd4d6096ee4d7c8"
integrity sha1-26DDhUKJVjwK2qwpLNTWCW7k18g=
dependencies:
colors "1.1.2"
commander "2.9.0"
promise "7.1.1"
ansi-colors@^3.0.0:
version "3.2.1"
resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-3.2.1.tgz#9638047e4213f3428a11944a7d4b31cba0a3ff95"
@ -1889,7 +1898,7 @@ ansi-escapes@^1.0.0:
resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-1.4.0.tgz#d3a8a83b319aa67793662b13e761c7911422306e"
integrity sha1-06ioOzGapneTZisT52HHkRQiMG4=
ansi-escapes@^3.0.0, ansi-escapes@^3.1.0:
ansi-escapes@^3.0.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-3.1.0.tgz#f73207bb81207d75fd6c83f125af26eea378ca30"
integrity sha512-UgAb8H9D41AQnu/PbWlCofQVcnV4Gs2bBJi9eZPxfU/hgglFh3SMDMENRIqdr7H6XFnXdoknctFByVsCOotTVw==
@ -2966,6 +2975,15 @@ chalk@2.4.0:
escape-string-regexp "^1.0.5"
supports-color "^5.3.0"
chalk@2.4.2, chalk@^2.4.2:
version "2.4.2"
resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424"
integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==
dependencies:
ansi-styles "^3.2.1"
escape-string-regexp "^1.0.5"
supports-color "^5.3.0"
chalk@^1.0.0, chalk@^1.1.1, chalk@^1.1.3:
version "1.1.3"
resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98"
@ -2986,15 +3004,6 @@ chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0, chalk@^2.3.1, chalk@^2.4
escape-string-regexp "^1.0.5"
supports-color "^5.3.0"
chalk@^2.4.2:
version "2.4.2"
resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424"
integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==
dependencies:
ansi-styles "^3.2.1"
escape-string-regexp "^1.0.5"
supports-color "^5.3.0"
chardet@^0.4.0:
version "0.4.2"
resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.4.2.tgz#b5473b33dc97c424e5d98dc87d55d4d8a29c8bf2"
@ -3100,7 +3109,7 @@ chromedriver@2.42.0:
mkdirp "^0.5.1"
request "^2.87.0"
ci-info@^1.5.0, ci-info@^1.6.0:
ci-info@^1.5.0:
version "1.6.0"
resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-1.6.0.tgz#2ca20dbb9ceb32d4524a683303313f0304b1e497"
integrity sha512-vsGdkwSCDpWmP80ncATX7iea5DWQemg1UgCW5J8tqjU3lYw4FBYuj89J0CTVomA7BEfvSZd84GmHko+MxFQU2A==
@ -3279,7 +3288,7 @@ color@^3.0.0:
color-convert "^1.9.1"
color-string "^1.5.2"
colors@~1.1.2:
colors@1.1.2, colors@~1.1.2:
version "1.1.2"
resolved "https://registry.yarnpkg.com/colors/-/colors-1.1.2.tgz#168a4701756b6a7f51a12ce0c97bfa28c084ed63"
integrity sha1-FopHAXVran9RoSzgyXv6KMCE7WM=
@ -3299,6 +3308,13 @@ combined-stream@^1.0.6, combined-stream@~1.0.5, combined-stream@~1.0.6:
dependencies:
delayed-stream "~1.0.0"
commander@2.9.0:
version "2.9.0"
resolved "https://registry.yarnpkg.com/commander/-/commander-2.9.0.tgz#9c99094176e12240cb22d6c5146098400fe0f7d4"
integrity sha1-nJkJQXbhIkDLItbFFGCYQA/g99Q=
dependencies:
graceful-readlink ">= 1.0.0"
commander@^2.12.1, commander@^2.18.0, commander@^2.9.0:
version "2.19.0"
resolved "https://registry.yarnpkg.com/commander/-/commander-2.19.0.tgz#f6198aa84e5b83c46054b94ddedbfed5ee9ff12a"
@ -3372,17 +3388,6 @@ configstore@3.1.2:
write-file-atomic "^2.0.0"
xdg-basedir "^3.0.0"
consola@^2.3.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/consola/-/consola-2.3.0.tgz#256b80a927234351d512a4e5693eac9cf8a572b9"
integrity sha512-gsawoQfj4DtnwsaPrabFpFOZBxWpzpT+E9fu6YAdFKO3NvBOOsFcQl/cskDOoIDDLMkLZvm4jjMWvSEelIumIw==
dependencies:
chalk "^2.4.1"
dayjs "^1.7.7"
figures "^2.0.0"
std-env "^2.2.1"
string-width "^2.1.1"
console-browserify@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/console-browserify/-/console-browserify-1.1.0.tgz#f0241c45730a9fc6323b206dbf38edc741d0bb10"
@ -3962,11 +3967,6 @@ dateformat@^3.0.0:
resolved "https://registry.yarnpkg.com/dateformat/-/dateformat-3.0.3.tgz#a6e37499a4d9a9cf85ef5872044d62901c9889ae"
integrity sha512-jyCETtSl3VMZMWeRo7iY1FL19ges1t55hMo5yaam4Jrsm5EPL89UQkoQRyiI+Yf4k8r2ZpdngkV8hr1lIdjb3Q==
dayjs@^1.7.7:
version "1.7.8"
resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.7.8.tgz#05d288f8d4b2140110cc1519cfe317d6f1f11a3c"
integrity sha512-Gp4Y5KWeSri0QOWGzHQz7VrKDkfEpS92dCLK7P8hYowRFbaym1vj3d6CoHio3apSS4KSi/qb5Edemv26IN5Hfg==
debug-log@^1.0.0:
version "1.0.1"
resolved "https://registry.yarnpkg.com/debug-log/-/debug-log-1.0.1.tgz#2307632d4c04382b8df8a32f70b895046d52745f"
@ -4442,13 +4442,6 @@ error-ex@^1.2.0, error-ex@^1.3.1:
dependencies:
is-arrayish "^0.2.1"
error-stack-parser@^2.0.0:
version "2.0.2"
resolved "https://registry.yarnpkg.com/error-stack-parser/-/error-stack-parser-2.0.2.tgz#4ae8dbaa2bf90a8b450707b9149dcabca135520d"
integrity sha512-E1fPutRDdIj/hohG0UpT5mayXNCxXP9d+snxFsPU9X0XgccOumKraa3juDMwTUyi7+Bu5+mCGagjg4IYeNbOdw==
dependencies:
stackframe "^1.0.4"
es-abstract@^1.5.1, es-abstract@^1.6.1, es-abstract@^1.7.0:
version "1.12.0"
resolved "https://registry.yarnpkg.com/es-abstract/-/es-abstract-1.12.0.tgz#9dbbdd27c6856f0001421ca18782d786bf8a6165"
@ -5349,15 +5342,6 @@ fresh@0.5.2:
resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7"
integrity sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=
friendly-errors-webpack-plugin@1.7.0:
version "1.7.0"
resolved "https://registry.yarnpkg.com/friendly-errors-webpack-plugin/-/friendly-errors-webpack-plugin-1.7.0.tgz#efc86cbb816224565861a1be7a9d84d0aafea136"
integrity sha512-K27M3VK30wVoOarP651zDmb93R9zF28usW4ocaK3mfQeIEI5BPht/EzZs5E8QLLwbLRJQMwscAjDxYPb1FuNiw==
dependencies:
chalk "^1.1.3"
error-stack-parser "^2.0.0"
string-width "^2.0.0"
from2@^2.1.0:
version "2.3.0"
resolved "https://registry.yarnpkg.com/from2/-/from2-2.3.0.tgz#8bfb5502bde4a4d36cfdeea007fcca21d7e382af"
@ -5776,6 +5760,11 @@ graceful-fs@^4.1.0, graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.4,
resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.1.15.tgz#ffb703e1066e8a0eeaa4c8b80ba9253eeefbfb00"
integrity sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==
"graceful-readlink@>= 1.0.0":
version "1.0.1"
resolved "https://registry.yarnpkg.com/graceful-readlink/-/graceful-readlink-1.0.1.tgz#4cafad76bc62f02fa039b2f94e9a3dd3a391a725"
integrity sha1-TK+tdrxi8C+gObL5Tpo906ORpyU=
"growl@~> 1.10.0":
version "1.10.5"
resolved "https://registry.yarnpkg.com/growl/-/growl-1.10.5.tgz#f2735dc2283674fa67478b10181059355c369e5e"
@ -9589,11 +9578,6 @@ pretty-format@^23.6.0:
ansi-regex "^3.0.0"
ansi-styles "^3.2.0"
pretty-time@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/pretty-time/-/pretty-time-1.1.0.tgz#ffb7429afabb8535c346a34e41873adf3d74dd0e"
integrity sha512-28iF6xPQrP8Oa6uxE6a1biz+lWeTOAPKggvjB8HAs6nVMKZwf5bG++632Dx614hIWgUPkgivRfG+a8uAXGTIbA==
private@^0.1.6, private@^0.1.8:
version "0.1.8"
resolved "https://registry.yarnpkg.com/private/-/private-0.1.8.tgz#2381edb3689f7a53d653190060fcf822d2f368ff"
@ -9637,6 +9621,13 @@ promise-retry@^1.1.1:
err-code "^1.0.0"
retry "^0.10.0"
promise@7.1.1:
version "7.1.1"
resolved "https://registry.yarnpkg.com/promise/-/promise-7.1.1.tgz#489654c692616b8aa55b0724fa809bb7db49c5bf"
integrity sha1-SJZUxpJha4qlWwck+oCbt9tJxb8=
dependencies:
asap "~2.0.3"
promise@^7.0.1:
version "7.3.1"
resolved "https://registry.yarnpkg.com/promise/-/promise-7.3.1.tgz#064b72602b18f90f29192b8b1bc418ffd1ebd3bf"
@ -9870,15 +9861,15 @@ rc@^1.0.1, rc@^1.1.6, rc@^1.2.7:
minimist "^1.2.0"
strip-json-comments "~2.0.1"
react-dom@16.6.3:
version "16.6.3"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-16.6.3.tgz#8fa7ba6883c85211b8da2d0efeffc9d3825cccc0"
integrity sha512-8ugJWRCWLGXy+7PmNh8WJz3g1TaTUt1XyoIcFN+x0Zbkoz+KKdUyx1AQLYJdbFXjuF41Nmjn5+j//rxvhFjgSQ==
react-dom@16.8.0:
version "16.8.0"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-16.8.0.tgz#18f28d4be3571ed206672a267c66dd083145a9c4"
integrity sha512-dBzoAGYZpW9Yggp+CzBPC7q1HmWSeRc93DWrwbskmG1eHJWznZB/p0l/Sm+69leIGUS91AXPB/qB3WcPnKx8Sw==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"
prop-types "^15.6.2"
scheduler "^0.11.2"
scheduler "^0.13.0"
react-error-overlay@4.0.0:
version "4.0.0"
@ -9890,15 +9881,15 @@ react-is@16.6.3, react-is@^16.3.2:
resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.6.3.tgz#d2d7462fcfcbe6ec0da56ad69047e47e56e7eac0"
integrity sha512-u7FDWtthB4rWibG/+mFbVd5FvdI20yde86qKGx4lVUTWmPlSWQ4QxbBIrrs+HnXGbxOUlUzTAP/VDmvCwaP2yA==
react@16.6.3:
version "16.6.3"
resolved "https://registry.yarnpkg.com/react/-/react-16.6.3.tgz#25d77c91911d6bbdd23db41e70fb094cc1e0871c"
integrity sha512-zCvmH2vbEolgKxtqXL2wmGCUxUyNheYn/C+PD1YAjfxHC54+MhdruyhO7QieQrYsYeTxrn93PM2y0jRH1zEExw==
react@16.8.0:
version "16.8.0"
resolved "https://registry.yarnpkg.com/react/-/react-16.8.0.tgz#8533f0e4af818f448a276eae71681d09e8dd970a"
integrity sha512-g+nikW2D48kqgWSPwNo0NH9tIGG3DsQFlrtrQ1kj6W77z5ahyIHG0w8kPpz4Sdj6gyLnz0lEd/xsjOoGge2MYQ==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"
prop-types "^15.6.2"
scheduler "^0.11.2"
scheduler "^0.13.0"
read-cmd-shim@^1.0.1:
version "1.0.1"
@ -10623,10 +10614,10 @@ sax@^1.2.4, sax@~1.2.4:
resolved "https://registry.yarnpkg.com/sax/-/sax-1.2.4.tgz#2816234e2378bddc4e5354fab5caa895df7100d9"
integrity sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==
scheduler@^0.11.2:
version "0.11.3"
resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.11.3.tgz#b5769b90cf8b1464f3f3cfcafe8e3cd7555a2d6b"
integrity sha512-i9X9VRRVZDd3xZw10NY5Z2cVMbdYg6gqFecfj79USv1CFN+YrJ3gIPRKf1qlY+Sxly4djoKdfx1T+m9dnRB8kQ==
scheduler@^0.13.0:
version "0.13.0"
resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.13.0.tgz#e701f62e1b3e78d2bbb264046d4e7260f12184dd"
integrity sha512-w7aJnV30jc7OsiZQNPVmBc+HooZuvQZIZIShKutC3tnMFMkcwVN9CZRRSSNw03OnSCKmEkK8usmwcw6dqBaLzw==
dependencies:
loose-envify "^1.1.0"
object-assign "^4.1.1"
@ -11100,11 +11091,6 @@ stack-utils@^1.0.1:
resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-1.0.2.tgz#33eba3897788558bebfc2db059dc158ec36cebb8"
integrity sha512-MTX+MeG5U994cazkjd/9KNAapsHnibjMLnfXodlkXw76JEea0UiNzrqidzo1emMwk7w5Qhc9jd4Bn9TBb1MFwA==
stackframe@^1.0.4:
version "1.0.4"
resolved "https://registry.yarnpkg.com/stackframe/-/stackframe-1.0.4.tgz#357b24a992f9427cba6b545d96a14ed2cbca187b"
integrity sha512-to7oADIniaYwS3MhtCa/sQhrxidCCQiF/qp4/m5iN3ipf0Y7Xlri0f6eG29r08aL7JYl8n32AF3Q5GYBZ7K8vw==
staged-git-files@0.0.4:
version "0.0.4"
resolved "https://registry.yarnpkg.com/staged-git-files/-/staged-git-files-0.0.4.tgz#d797e1b551ca7a639dec0237dc6eb4bb9be17d35"
@ -11158,13 +11144,6 @@ statuses@~1.4.0:
resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.4.0.tgz#bb73d446da2796106efcc1b601a253d6c46bd087"
integrity sha512-zhSCtt8v2NDrRlPQpCNtw/heZLtfUDqxBM1udqikb/Hbk52LK4nQSwr10u77iopCW5LsyHpuXS0GnEc48mLeew==
std-env@^2.2.1:
version "2.2.1"
resolved "https://registry.yarnpkg.com/std-env/-/std-env-2.2.1.tgz#2ffa0fdc9e2263e0004c1211966e960948a40f6b"
integrity sha512-IjYQUinA3lg5re/YMlwlfhqNRTzMZMqE+pezevdcTaHceqx8ngEi1alX9nNCk9Sc81fy1fLDeQoaCzeiW1yBOQ==
dependencies:
ci-info "^1.6.0"
stdout-stream@^1.4.0:
version "1.4.1"
resolved "https://registry.yarnpkg.com/stdout-stream/-/stdout-stream-1.4.1.tgz#5ac174cdd5cd726104aa0c0b2bd83815d8d535de"
@ -11951,6 +11930,11 @@ unique-string@^1.0.0:
dependencies:
crypto-random-string "^1.0.0"
unistore@3.2.1:
version "3.2.1"
resolved "https://registry.yarnpkg.com/unistore/-/unistore-3.2.1.tgz#26e316c834e39b83b2a301a65f78138f43975a0b"
integrity sha512-102VTsu5dcoADsz+NdBE55JeFh1YYLvrEzLenwE+nu3lFWSVZj2MpvXLkBqrx/YTk+L3kzMG5UwHkHoj/9VcaQ==
universalify@^0.1.0:
version "0.1.2"
resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66"
@ -12268,20 +12252,6 @@ webpack@4.29.0:
watchpack "^1.5.0"
webpack-sources "^1.3.0"
"webpackbar@3.1.4 ":
version "3.1.4"
resolved "https://registry.yarnpkg.com/webpackbar/-/webpackbar-3.1.4.tgz#7b99fd28bf7c8d4f890b14c042418fc56d0877f0"
integrity sha512-P/ESpzVFl49IL9svoZphf9Kbyh/09vHqo31PP5/fxVrBLCBUHMKbDaWt+Px7zEQZUyFuQCWzRASJHZByQHTdKw==
dependencies:
ansi-escapes "^3.1.0"
chalk "^2.4.1"
consola "^2.3.0"
figures "^2.0.0"
pretty-time "^1.1.0"
std-env "^2.2.1"
text-table "^0.2.0"
wrap-ansi "^4.0.0"
whatwg-encoding@^1.0.1, whatwg-encoding@^1.0.3:
version "1.0.5"
resolved "https://registry.yarnpkg.com/whatwg-encoding/-/whatwg-encoding-1.0.5.tgz#5abacf777c32166a51d085d6b4f3e7d27113ddb0"
@ -12376,15 +12346,6 @@ wrap-ansi@^2.0.0:
string-width "^1.0.1"
strip-ansi "^3.0.1"
wrap-ansi@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-4.0.0.tgz#b3570d7c70156159a2d42be5cc942e957f7b1131"
integrity sha512-uMTsj9rDb0/7kk1PbcbCcwvHUxp60fGDB/NNXpVa0Q+ic/e7y5+BwTxKfQ33VYgDppSwi/FBzpetYzo8s6tfbg==
dependencies:
ansi-styles "^3.2.0"
string-width "^2.1.1"
strip-ansi "^4.0.0"
wrappy@1:
version "1.0.2"
resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f"