File size: 6,281 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import path from 'path'
import fs from 'fs-extra'
import { NextInstance } from './base'
import spawn from 'cross-spawn'
import { Span } from 'next/dist/trace'
import stripAnsi from 'strip-ansi'

export class NextStartInstance extends NextInstance {
  private _buildId: string
  private _cliOutput: string = ''
  private spawnOpts: import('child_process').SpawnOptions

  public get buildId() {
    return this._buildId
  }

  public get cliOutput() {
    return this._cliOutput
  }

  public async setup(parentSpan: Span) {
    super.setup(parentSpan)
    await super.createTestDir({ parentSpan })
  }

  private handleStdio = (childProcess) => {
    childProcess.stdout.on('data', (chunk) => {
      const msg = chunk.toString()
      process.stdout.write(chunk)
      this._cliOutput += msg
      this.emit('stdout', [msg])
    })
    childProcess.stderr.on('data', (chunk) => {
      const msg = chunk.toString()
      process.stderr.write(chunk)
      this._cliOutput += msg
      this.emit('stderr', [msg])
    })
  }

  public async start(options: { skipBuild?: boolean } = {}) {
    if (this.childProcess) {
      throw new Error('next already started')
    }

    this._cliOutput = ''
    this.spawnOpts = {
      cwd: this.testDir,
      stdio: ['ignore', 'pipe', 'pipe'],
      shell: false,
      env: {
        ...process.env,
        ...this.env,
        NODE_ENV: this.env.NODE_ENV || ('' as any),
        ...(this.forcedPort
          ? {
              PORT: this.forcedPort,
            }
          : {
              PORT: '0',
            }),
        __NEXT_TEST_MODE: 'e2e',
      },
    }

    let buildArgs = ['pnpm', 'next', 'build']
    let startArgs = ['pnpm', 'next', 'start']

    if (this.buildCommand) {
      buildArgs = this.buildCommand.split(' ')
    }

    if (this.buildArgs) {
      buildArgs.push(...this.buildArgs)
    }

    if (this.startCommand) {
      startArgs = this.startCommand.split(' ')
    }

    if (this.startArgs) {
      startArgs.push(...this.startArgs)
    }

    if (process.env.NEXT_SKIP_ISOLATE) {
      // without isolation yarn can't be used and pnpm must be used instead
      if (buildArgs[0] === 'yarn') {
        buildArgs[0] = 'pnpm'
      }
      if (startArgs[0] === 'yarn') {
        startArgs[0] = 'pnpm'
      }
    }

    if (!options.skipBuild) {
      console.log('running', buildArgs.join(' '))
      await new Promise<void>((resolve, reject) => {
        try {
          this.childProcess = spawn(
            buildArgs[0],
            buildArgs.slice(1),
            this.spawnOpts
          )
          this.handleStdio(this.childProcess)
          this.childProcess.on('exit', (code, signal) => {
            this.childProcess = undefined
            if (code || signal)
              reject(
                new Error(
                  `next build failed with code/signal ${code || signal}`
                )
              )
            else resolve()
          })
        } catch (err) {
          require('console').error(`Failed to run ${buildArgs.join(' ')}`, err)
          setTimeout(() => process.exit(1), 0)
        }
      })

      this._buildId = (
        await fs
          .readFile(
            path.join(
              this.testDir,
              this.nextConfig?.distDir || '.next',
              'BUILD_ID'
            ),
            'utf8'
          )
          .catch(() => '')
      ).trim()
    }

    console.log('running', startArgs.join(' '))
    await new Promise<void>((resolve, reject) => {
      try {
        this.childProcess = spawn(
          startArgs[0],
          startArgs.slice(1),
          this.spawnOpts
        )
        this.handleStdio(this.childProcess)

        this.childProcess.on('close', (code, signal) => {
          if (this.isStopping) return
          if (code || signal) {
            require('console').error(
              `next start exited unexpectedly with code/signal ${
                code || signal
              }`
            )
          }
        })

        const serverReadyTimeoutId = this.setServerReadyTimeout(
          reject,
          this.startServerTimeout
        )

        const readyCb = (msg) => {
          const colorStrippedMsg = stripAnsi(msg)
          if (colorStrippedMsg.includes('- Local:')) {
            this._url = msg
              .split('\n')
              .find((line) => line.includes('- Local:'))
              .split(/\s*- Local:/)
              .pop()
              .trim()
            this._parsedUrl = new URL(this._url)
          }

          if (this.serverReadyPattern!.test(colorStrippedMsg)) {
            clearTimeout(serverReadyTimeoutId)
            resolve()
            this.off('stdout', readyCb)
          }
        }
        this.on('stdout', readyCb)
      } catch (err) {
        require('console').error(`Failed to run ${startArgs.join(' ')}`, err)
        setTimeout(() => process.exit(1), 0)
      }
    })
  }

  public async build(
    options: { env?: Record<string, string>; args?: string[] } = {}
  ) {
    this.spawnOpts = {
      cwd: this.testDir,
      stdio: ['ignore', 'pipe', 'pipe'],
      shell: false,
      env: {
        ...process.env,
        ...this.env,
        ...options.env,
        NODE_ENV: '' as any,
        PORT: this.forcedPort || '0',
        __NEXT_TEST_MODE: 'e2e',
      },
    }
    return new Promise<{
      exitCode: NodeJS.Signals | number | null
      cliOutput: string
    }>((resolve) => {
      const curOutput = this._cliOutput.length
      const buildArgs = ['pnpm', 'next', 'build']

      if (this.buildArgs) {
        buildArgs.push(...this.buildArgs)
      }

      if (options.args) {
        buildArgs.push(...options.args)
      }

      if (this.childProcess) {
        throw new Error(
          `can not run export while server is running, use next.stop() first`
        )
      }

      console.log('running', buildArgs.join(' '))

      this.childProcess = spawn(
        buildArgs[0],
        buildArgs.slice(1),
        this.spawnOpts
      )
      this.handleStdio(this.childProcess)

      this.childProcess.on('exit', (code, signal) => {
        this.childProcess = undefined
        resolve({
          exitCode: signal || code,
          cliOutput: this.cliOutput.slice(curOutput),
        })
      })
    })
  }
}