Files
cypress/cli/lib/exec/spawn.js
Cacie Prins e463fdbc61 fix: Redirect spammy electron stderr to a debug sink (#32188)
* wip: system test to reproduce

* system test for alsa stderr

* split cypress from 3rd party stderr at parent process to electron child

* rm garbage warning regexes

* fix newline behavior when parsing internal stderr

* migrate left over console errors

* clean up system test name

* fix typed import

* extract stderr splitting to separate pkg so runner can use @packages/error

* rm new err log from packherd-quire

* handle backpressure

* docs

* some unit tests & coverage for stderr-filtering

* unit tests

* no longer test regexp specific output in spawn unit tests

* filter enabled debug namespaces rather than just cypress namespacesc

* revise stream splitting et al

* try to fix v8 snapshot build??

* fix console.log assertion

* add missing eslint config

* rm unused spies

* fix regexp for optional leading wsp and ansi on debug entries

* update unit tests because sinon

* lint

* colon..

* build stderr-filtering before checking if binary exists

* adds TagStream transform stream, fixes stderr from child proc config

* add build-prod script for stderr-filtering

* changelog

* properly handle backpressure in prefixed content transform stream

* use standard tsconfig?

* better tsconfig

* Add pkgStderrFiltering to monorepoPaths

* add \"files\" manifest

* pipe all stderr to stderr when CYPRESS_INTERNAL_DEBUG_ELECTRON is enabled

* rm explicit build of stderr-filtering in check-if-binary-exists step

* ensure all dependencies of scripts/ are built before scripts are executed in the check-if-binary-exists command

* fix dev version ref

* swap logic

* add stdin piping

* fix exec name on the run-on-dependencies command to be more useful

* use correct env

* rm obsolete type refs

* simplify stderr-filtering public iface, pipe cy-in-cy stderr through filtering tx

* bust cache

* fix mocks

* fix v8-snapshot

* move stderrfiltering to dev pkg in cli

* skip integrity check in ci, if they are out of date things should fail anyway

* copypasta over a portion of stderr-filtering to cli, since cli cannot import @packages

* Delete issues.md

* rm special filtering for cy in cy

* rm too narrow rules file

---------

Co-authored-by: Jennifer Shehane <shehane.jennifer@gmail.com>
Co-authored-by: Jennifer Shehane <jennifer@cypress.io>
Co-authored-by: Bill Glesias <bglesias@gmail.com>
2025-08-19 17:05:53 -04:00

290 lines
8.8 KiB
JavaScript

const _ = require('lodash')
const os = require('os')
const cp = require('child_process')
const path = require('path')
const Promise = require('bluebird')
const debug = require('debug')('cypress:cli')
const util = require('../util')
const state = require('../tasks/state')
const xvfb = require('./xvfb')
const verify = require('../tasks/verify')
const errors = require('../errors')
const readline = require('readline')
function isPlatform (platform) {
return os.platform() === platform
}
function needsStderrPiped (needsXvfb) {
return _.some([
isPlatform('darwin'),
(needsXvfb && isPlatform('linux')),
util.isPossibleLinuxWithIncorrectDisplay(),
])
}
function needsEverythingPipedDirectly () {
return isPlatform('win32')
}
function getStdio (needsXvfb) {
if (needsEverythingPipedDirectly()) {
return 'pipe'
}
// https://github.com/cypress-io/cypress/issues/921
// https://github.com/cypress-io/cypress/issues/1143
// https://github.com/cypress-io/cypress/issues/1745
if (needsStderrPiped(needsXvfb)) {
// returning pipe here so we can massage stderr
// and remove garbage from Xlib and libuv
// due to starting the Xvfb process on linux
return ['inherit', 'inherit', 'pipe']
}
return 'inherit'
}
module.exports = {
start (args, options = {}) {
const needsXvfb = xvfb.isNeeded()
let executable = state.getPathToExecutable(state.getBinaryDir())
if (util.getEnv('CYPRESS_RUN_BINARY')) {
executable = path.resolve(util.getEnv('CYPRESS_RUN_BINARY'))
}
debug('needs to start own Xvfb?', needsXvfb)
// Always push cwd into the args
// which additionally acts as a signal to the
// binary that it was invoked through the NPM module
args = args || []
if (typeof args === 'string') {
args = [args]
}
args = [...args, '--cwd', process.cwd(), '--userNodePath', process.execPath, '--userNodeVersion', process.versions.node]
_.defaults(options, {
dev: false,
env: process.env,
detached: false,
stdio: getStdio(needsXvfb),
})
const spawn = (overrides = {}) => {
return new Promise((resolve, reject) => {
_.defaults(overrides, {
onStderrData: false,
})
const { onStderrData } = overrides
const envOverrides = util.getEnvOverrides(options)
const electronArgs = []
const node11WindowsFix = isPlatform('win32')
let startScriptPath
if (options.dev) {
executable = 'node'
// if we're in dev then reset
// the launch cmd to be 'npm run dev'
startScriptPath = path.resolve(__dirname, '..', '..', '..', 'scripts', 'start.js'),
debug('in dev mode the args became %o', args)
}
if (!options.dev && verify.needsSandbox()) {
electronArgs.push('--no-sandbox')
}
// strip dev out of child process options
/**
* @type {import('child_process').ForkOptions}
*/
let stdioOptions = _.pick(options, 'env', 'detached', 'stdio')
// figure out if we're going to be force enabling or disabling colors.
// also figure out whether we should force stdout and stderr into thinking
// it is a tty as opposed to a pipe.
stdioOptions.env = _.extend({}, stdioOptions.env, envOverrides)
if (node11WindowsFix) {
stdioOptions = _.extend({}, stdioOptions, { windowsHide: false })
}
if (util.isPossibleLinuxWithIncorrectDisplay()) {
// make sure we use the latest DISPLAY variable if any
debug('passing DISPLAY', process.env.DISPLAY)
stdioOptions.env.DISPLAY = process.env.DISPLAY
}
if (stdioOptions.env.ELECTRON_RUN_AS_NODE) {
// Since we are running electron as node, we need to add an entry point file.
startScriptPath = path.join(state.getBinaryPkgPath(path.dirname(executable)), '..', 'index.js')
} else {
// Start arguments with "--" so Electron knows these are OUR
// arguments and does not try to sanitize them. Otherwise on Windows
// an url in one of the arguments crashes it :(
// https://github.com/cypress-io/cypress/issues/5466
args = [...electronArgs, '--', ...args]
}
if (startScriptPath) {
args.unshift(startScriptPath)
}
if (process.env.CYPRESS_INTERNAL_DEV_DEBUG) {
args.unshift(process.env.CYPRESS_INTERNAL_DEV_DEBUG)
}
debug('spawn args %o %o', args, _.omit(stdioOptions, 'env'))
debug('spawning Cypress with executable: %s', executable)
const child = cp.spawn(executable, args, stdioOptions)
function resolveOn (event) {
return function (code, signal) {
debug('child event fired %o', { event, code, signal })
if (code === null) {
const errorObject = errors.errors.childProcessKilled(event, signal)
return errors.getError(errorObject).then(reject)
}
resolve(code)
}
}
child.on('close', resolveOn('close'))
child.on('exit', resolveOn('exit'))
child.on('error', reject)
if (isPlatform('win32')) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
})
// on windows, SIGINT does not propagate to the child process when ctrl+c is pressed
// this makes sure all nested processes are closed(ex: firefox inside the server)
rl.on('SIGINT', function () {
let kill = require('tree-kill')
kill(child.pid, 'SIGINT')
})
}
// if stdio options is set to 'pipe', then
// we should set up pipes:
// process STDIN (read stream) => child STDIN (writeable)
// child STDOUT => process STDOUT
// child STDERR => process STDERR with additional filtering
if (child.stdin) {
debug('piping process STDIN into child STDIN')
process.stdin.pipe(child.stdin)
}
if (child.stdout) {
debug('piping child STDOUT to process STDOUT')
child.stdout.pipe(process.stdout)
}
// if this is defined then we are manually piping for linux
// to filter out the garbage
if (child.stderr) {
debug('piping child STDERR to process STDERR')
child.stderr.on('data', (data) => {
const str = data.toString()
// if we have a callback and this explicitly returns
// false then bail
if (onStderrData && onStderrData(str)) {
return
}
// else pass it along!
process.stderr.write(data)
})
}
// https://github.com/cypress-io/cypress/issues/1841
// https://github.com/cypress-io/cypress/issues/5241
// In some versions of node, it will throw on windows
// when you close the parent process after piping
// into the child process. unpiping does not seem
// to have any effect. so we're just catching the
// error here and not doing anything.
process.stdin.on('error', (err) => {
if (['EPIPE', 'ENOTCONN'].includes(err.code)) {
return
}
throw err
})
if (stdioOptions.detached) {
child.unref()
}
})
}
const spawnInXvfb = () => {
return xvfb
.start()
.then(userFriendlySpawn)
.finally(xvfb.stop)
}
const userFriendlySpawn = (linuxWithDisplayEnv) => {
debug('spawning, should retry on display problem?', Boolean(linuxWithDisplayEnv))
let brokenGtkDisplay
const overrides = {}
if (linuxWithDisplayEnv) {
_.extend(overrides, {
electronLogging: true,
onStderrData (str) {
// if we receive a broken pipe anywhere
// then we know that's why cypress exited early
if (util.isBrokenGtkDisplay(str)) {
brokenGtkDisplay = true
}
},
})
}
return spawn(overrides)
.then((code) => {
if (code !== 0 && brokenGtkDisplay) {
util.logBrokenGtkDisplayWarning()
return spawnInXvfb()
}
return code
})
// we can format and handle an error message from the code above
// prevent wrapping error again by using "known: undefined" filter
.catch({ known: undefined }, errors.throwFormErrorText(errors.errors.unexpected))
}
if (needsXvfb) {
return spawnInXvfb()
}
// if we are on linux and there's already a DISPLAY
// set, then we may need to rerun cypress after
// spawning our own Xvfb server
const linuxWithDisplayEnv = util.isPossibleLinuxWithIncorrectDisplay()
return userFriendlySpawn(linuxWithDisplayEnv)
},
}