-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
run_require_async_child.js
307 lines (239 loc) · 10.3 KB
/
run_require_async_child.js
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
require('graceful-fs').gracefulify(require('fs'))
const stripAnsi = require('strip-ansi')
const debug = require('debug')(`cypress:lifecycle:child:run_require_async_child:${process.pid}`)
const { pathToFileURL } = require('url')
const tsNodeUtil = require('./ts_node')
const util = require('../util')
const { RunPlugins } = require('./run_plugins')
let tsRegistered = false
/**
* Executes and returns the passed `file` (usually `configFile`) file in the ipc `loadConfig` event
* @param {*} ipc Inter Process Communication protocol
* @param {*} file the file we are trying to load
* @param {*} projectRoot the root of the typescript project (useful mainly for tsnode)
* @returns
*/
function run (ipc, file, projectRoot) {
debug('configFile:', file)
debug('projectRoot:', projectRoot)
if (!projectRoot) {
throw new Error('Unexpected: projectRoot should be a string')
}
if (!tsRegistered) {
debug('register typescript for required file')
tsNodeUtil.register(projectRoot, file)
// ensure typescript is only registered once
tsRegistered = true
}
process.on('uncaughtException', (err) => {
debug('uncaught exception:', util.serializeError(err))
ipc.send('childProcess:unhandledError', util.serializeError(err))
return false
})
process.on('unhandledRejection', (event) => {
let err = event
debug('unhandled rejection:', event)
// Rejected Bluebird promises will return a reason object.
// OpenSSL error returns a reason as user-friendly string.
if (event && event.reason && typeof event.reason === 'object') {
err = event.reason
}
ipc.send('childProcess:unhandledError', util.serializeError(err))
return false
})
const isValidSetupNodeEvents = (config, testingType) => {
if (config[testingType] && config[testingType].setupNodeEvents && typeof config[testingType].setupNodeEvents !== 'function') {
ipc.send('setupTestingType:error', util.serializeError(
require('@packages/errors').getError('SETUP_NODE_EVENTS_IS_NOT_FUNCTION', file, testingType, config[testingType].setupNodeEvents),
))
return false
}
return true
}
const getValidDevServer = (config) => {
const { devServer } = config
if (devServer && typeof devServer === 'function') {
return { devServer, objApi: false }
}
if (devServer && typeof devServer === 'object') {
if (devServer.bundler === 'webpack') {
return { devServer: require('@cypress/webpack-dev-server').devServer, objApi: true }
}
if (devServer.bundler === 'vite') {
return { devServer: require('@cypress/vite-dev-server').devServer, objApi: true }
}
}
ipc.send('setupTestingType:error', util.serializeError(
require('@packages/errors').getError('CONFIG_FILE_DEV_SERVER_IS_NOT_VALID', file, config),
))
return false
}
// Config file loading of modules is tested within
// system-tests/projects/config-cjs-and-esm/*
const loadFile = async (file) => {
// 1. Try loading the configFile
// 2. Catch the "ERR_REQUIRE_ESM" error
// 3. Check if esbuild is installed
// 3a. Yes: Use bundleRequire
// 3b. No: Continue through to `await import(configFile)`
// 4. Use node's dynamic import to import the configFile
try {
return require(file)
} catch (err) {
if (!err.stack.includes('[ERR_REQUIRE_ESM]') && !err.stack.includes('SyntaxError: Cannot use import statement outside a module')) {
throw err
}
}
debug('User is loading an ESM config file')
try {
debug('Trying to use esbuild to run their config file.')
// We prefer doing this because it supports TypeScript files
require.resolve('esbuild', { paths: [process.cwd()] })
debug(`They have esbuild, so we'll load the configFile via bundleRequire`)
const { bundleRequire } = require('bundle-require')
return (await bundleRequire({ filepath: file })).mod
} catch (err) {
if (err.stack.includes(`Cannot find module 'esbuild'`)) {
debug(`User doesn't have esbuild. Going to use native node imports.`)
// We cannot replace the initial `require` with `await import` because
// Certain modules cannot be dynamically imported.
// pathToFileURL for windows interop: https://github.com/nodejs/node/issues/31710
return await import(pathToFileURL(file).href)
}
throw err
}
}
ipc.on('loadConfig', async () => {
try {
debug('try loading', file)
const configFileExport = await loadFile(file)
debug('loaded config file', file)
const result = configFileExport.default || configFileExport
const replacer = (_key, val) => {
return typeof val === 'function' ? `[Function ${val.name}]` : val
}
ipc.send('loadConfig:reply', { initialConfig: JSON.stringify(result, replacer), requires: util.nonNodeRequires() })
let hasSetup = false
ipc.on('setupTestingType', (testingType, options) => {
if (hasSetup) {
throw new Error('Already Setup')
}
hasSetup = true
debug(`setupTestingType %s %o`, testingType, options)
const runPlugins = new RunPlugins(ipc, projectRoot, file)
if (!isValidSetupNodeEvents(result, testingType)) {
return
}
if (testingType === 'component') {
const devServerInfo = getValidDevServer(result.component || {})
if (!devServerInfo) {
return
}
const { devServer, objApi } = devServerInfo
runPlugins.runSetupNodeEvents(options, (on, config) => {
const setupNodeEvents = result.component && result.component.setupNodeEvents || ((on, config) => {})
const onConfigNotFound = (devServer, root, searchedFor) => {
ipc.send('setupTestingType:error', util.serializeError(
require('@packages/errors').getError('DEV_SERVER_CONFIG_FILE_NOT_FOUND', devServer, root, searchedFor),
))
}
on('dev-server:start', (devServerOpts) => {
if (objApi) {
const { specs, devServerEvents } = devServerOpts
return devServer({
cypressConfig: config,
onConfigNotFound,
...result.component.devServer,
specs,
devServerEvents,
})
}
devServerOpts.cypressConfig = config
return devServer(devServerOpts, result.component && result.component.devServerConfig)
})
return setupNodeEvents(on, config)
})
} else if (testingType === 'e2e') {
const setupNodeEvents = result.e2e && result.e2e.setupNodeEvents || ((on, config) => {})
runPlugins.runSetupNodeEvents(options, setupNodeEvents)
} else {
// Notify the plugins init that there's no plugins to resolve
ipc.send('setupTestingType:reply', {
requires: util.nonNodeRequires(),
})
}
})
debug('loaded config from %s %o', file, result)
} catch (err) {
if (err.name === 'TSError') {
// because of this https://github.com/TypeStrong/ts-node/issues/1418
// we have to do this https://stackoverflow.com/questions/25245716/remove-all-ansi-colors-styles-from-strings/29497680
const cleanMessage = stripAnsi(err.message)
// replace the first line with better text (remove potentially misleading word TypeScript for example)
.replace(/^.*\n/g, 'Error compiling file\n')
// Regex to pull out the error from the message body of a TSError. It displays the relative path to a file
const tsErrorRegex = /\n(.*?)\((\d+),(\d+)\):/g
const failurePath = tsErrorRegex.exec(cleanMessage)
err.compilerErrorLocation = failurePath ? { filePath: failurePath[1], line: Number(failurePath[2]), column: Number(failurePath[3]) } : null
err.originalMessage = err.message
err.message = cleanMessage
} else if (Array.isArray(err.errors)) {
// The stack trace of the esbuild error, do not give to much information related with the user error,
// we have the errors array which includes the users file and information related with the error
const firstError = err.errors.filter((e) => Boolean(e.location))[0]
if (firstError && firstError.location.file) {
err.compilerErrorLocation = { filePath: firstError.location.file, line: Number(firstError.location.line), column: Number(firstError.location.column) }
}
}
ipc.send('loadConfig:error', util.serializeError(
require('@packages/errors').getError('CONFIG_FILE_REQUIRE_ERROR', file, err),
))
}
})
ipc.on('loadLegacyPlugins', async (legacyConfig) => {
try {
let legacyPlugins = await loadFile(file)
if (legacyPlugins && typeof legacyPlugins.default === 'function') {
legacyPlugins = legacyPlugins.default
}
// invalid or empty plugins file
if (typeof legacyPlugins !== 'function') {
ipc.send('loadLegacyPlugins:reply', legacyConfig)
return
}
// we do not want to execute any tasks - the purpose
// of this is to get any modified config returned
// by plugins.
const noop = () => {}
const legacyPluginsConfig = await legacyPlugins(noop, legacyConfig)
// pluginsFile did not return the config - this is allowed, although
// we recommend returning it in our docs.
if (!legacyPluginsConfig) {
ipc.send('loadLegacyPlugins:reply', legacyConfig)
return
}
// match merging strategy from 9.x
const mergedLegacyConfig = {
...legacyConfig,
...legacyPluginsConfig,
}
if (legacyConfig.e2e || legacyPluginsConfig.e2e) {
mergedLegacyConfig.e2e = {
...(legacyConfig.e2e || {}),
...(legacyPluginsConfig.e2e || {}),
}
}
if (legacyConfig.component || legacyPluginsConfig.component) {
mergedLegacyConfig.component = {
...(legacyConfig.component || {}),
...(legacyPluginsConfig.component || {}),
}
}
ipc.send('loadLegacyPlugins:reply', mergedLegacyConfig)
} catch (e) {
ipc.send('loadLegacyPlugins:error', util.serializeError(e))
}
})
ipc.send('ready')
}
module.exports = run