text: /* eslint-env node */
  const next = require('next')
  
  const http = require('http')
  const url = require('url')
  
  const prepare = async (...args) => {
    const options = Object.assign({ dev: true }, ...args)
    const app = next(options)
  
    const handler = app.getRequestHandler()
    await app.prepare()
  
    return http.createServer((req, res) => {
      handler(req, res, url.parse(req.url, true))
    })
  }
  
  const listen = async (server, port) => {
    await new Promise((resolve, reject) => {
      server.once('error', reject)
      server.once('listening', resolve)
      server.listen(port)
    })
  }
  
  const start = async (port, ...args) => {
    const server = await prepare(...args)
    await listen(server, port)
    return server
  }
  
  const main = async (env = process.env) => {
    try {
      const { HTTP_PORT, NODE_ENV = 'development', PORT, SMP_PORT } = env
      const port = SMP_PORT || HTTP_PORT || PORT || '3000'
      const server = await start(port, {
        dev: NODE_ENV !== 'production',
      })
  
      const { port: addr } = server.address()
      console.debug(`ready; try: curl http://localhost:${addr}/health`)
    } catch (err) {
      console.error(err.message)
      process.exit(1)
    }
  }
  
  module.exports = {
    listen,
    prepare,
    start,
  }
  
  if (module === require.main) main()
  