cypress 16.2.0 → 16.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/angular/dist/index.js +10 -12
  2. package/angular/package.json +7 -22
  3. package/dist/bin/cypress +8 -8
  4. package/dist/{cli-AgTnS5LO.js → cli-y9Bb9Y77.js} +215 -40
  5. package/dist/cli.js +6 -6
  6. package/dist/{cypress-CdDm9AVa.js → cypress-CvEs5adm.js} +2 -2
  7. package/dist/cypress.js +8 -8
  8. package/dist/exec/spawn.js +4 -4
  9. package/dist/exec/xvfb.js +7 -4
  10. package/dist/index.js +8 -8
  11. package/dist/{spawn-DElwyZHC.js → spawn-Bx99tBTm.js} +529 -69
  12. package/dist/{tap-WHD3nHJC.js → tap-BMFGLoCT.js} +108 -26
  13. package/dist/{xvfb-CbW2_YXR.js → xvfb-DxbcANVl.js} +238 -25
  14. package/mount-utils/dist/index.js +1 -1
  15. package/mount-utils/package.json +15 -14
  16. package/package.json +5 -5
  17. package/react/dist/cypress-react.cjs.js +9 -7
  18. package/react/dist/cypress-react.esm-bundler.js +9 -7
  19. package/react/package.json +26 -46
  20. package/svelte/dist/cypress-svelte.cjs.js +3 -2
  21. package/svelte/dist/cypress-svelte.esm-bundler.js +3 -2
  22. package/svelte/package.json +24 -22
  23. package/types/cy-bluebird.d.ts +1 -0
  24. package/types/cy-chai.d.ts +99 -2
  25. package/types/cypress.d.ts +216 -43
  26. package/types/net-stubbing.d.ts +1 -1
  27. package/vue/dist/cypress-vue.cjs.js +4 -2
  28. package/vue/dist/cypress-vue.esm-bundler.js +4 -2
  29. package/vue/dist/index.d.ts +3 -3
  30. package/vue/package.json +35 -42
  31. package/angular/angular/README.md +0 -18
  32. package/angular/angular/dist/index.d.ts +0 -120
  33. package/angular/angular/dist/index.js +0 -479
  34. package/angular/angular/package.json +0 -82
  35. package/mount-utils/mount-utils/README.md +0 -140
  36. package/mount-utils/mount-utils/dist/index.d.ts +0 -12
  37. package/mount-utils/mount-utils/dist/index.js +0 -41
  38. package/mount-utils/mount-utils/package.json +0 -52
  39. package/react/react/README.md +0 -19
  40. package/react/react/dist/cypress-react.cjs.js +0 -293
  41. package/react/react/dist/cypress-react.esm-bundler.js +0 -268
  42. package/react/react/dist/index.d.ts +0 -95
  43. package/react/react/package.json +0 -113
  44. package/svelte/svelte/README.md +0 -19
  45. package/svelte/svelte/dist/cypress-svelte.cjs.js +0 -122
  46. package/svelte/svelte/dist/cypress-svelte.esm-bundler.js +0 -120
  47. package/svelte/svelte/dist/index.d.ts +0 -31
  48. package/svelte/svelte/package.json +0 -63
  49. package/vue/vue/README.md +0 -14
  50. package/vue/vue/dist/cypress-vue.cjs.js +0 -8692
  51. package/vue/vue/dist/cypress-vue.esm-bundler.js +0 -8671
  52. package/vue/vue/dist/index.d.ts +0 -1413
  53. package/vue/vue/package.json +0 -97
@@ -1,21 +1,287 @@
1
1
  'use strict';
2
2
 
3
- var xvfb = require('./xvfb-CbW2_YXR.js');
3
+ var xvfb = require('./xvfb-DxbcANVl.js');
4
4
  var _ = require('lodash');
5
5
  var os = require('os');
6
6
  var cp = require('child_process');
7
7
  var path = require('path');
8
8
  var Debug = require('debug');
9
+ var require$$1 = require('string_decoder');
10
+ var fs = require('fs-extra');
11
+ var process$1 = require('process');
9
12
  var chalk = require('chalk');
10
13
  var listr2 = require('listr2');
11
14
  var commonTags = require('common-tags');
12
15
  var logSymbols = require('log-symbols');
13
16
  var readline = require('readline');
14
- var process$1 = require('process');
15
17
  var require$$0 = require('stream');
16
- var require$$1 = require('string_decoder');
17
18
  var require$$1$1 = require('node:string_decoder');
18
19
 
20
+ // Must match CYPRESS_OPEN_READY_MESSAGE in packages/server/lib/modes/interactive.ts
21
+ const CYPRESS_OPEN_READY_MESSAGE = 'Cypress is ready';
22
+ const POLL_INTERVAL_MS = 100;
23
+ const MAX_NAME_ATTEMPTS = 5;
24
+ const signalExitCode = (signal) => 128 + os.constants.signals[signal];
25
+ // Files rather than pipes: a pipe breaks once the CLI exits, while the app keeps logging
26
+ function openDetachedOutput() {
27
+ return xvfb.__awaiter(this, void 0, void 0, function* () {
28
+ void pruneStaleDetachedOutput();
29
+ const stem = path.join(os.tmpdir(), `cypress-open-${process.pid}-${Date.now()}`);
30
+ // 'wx' fails on a file that already exists, so a file or link someone left at this
31
+ // predictable name in a shared temp directory is never followed or appended to. Only the
32
+ // person running Cypress needs to read what the app prints. Two runs in the same
33
+ // millisecond take the next numbered name instead of failing.
34
+ for (let attempt = 0;; attempt++) {
35
+ const base = attempt ? `${stem}-${attempt}` : stem;
36
+ const outPath = `${base}.out`;
37
+ const errPath = `${base}.err`;
38
+ let outFd;
39
+ try {
40
+ outFd = yield fs.open(outPath, 'wx', 0o600);
41
+ return { outPath, errPath, outFd, errFd: yield fs.open(errPath, 'wx', 0o600) };
42
+ }
43
+ catch (err) {
44
+ if (outFd !== undefined) {
45
+ yield fs.close(outFd).catch(() => undefined);
46
+ yield fs.remove(outPath).catch(() => undefined);
47
+ }
48
+ if (err instanceof Error && 'code' in err && err.code === 'EEXIST' && attempt < MAX_NAME_ATTEMPTS) {
49
+ continue;
50
+ }
51
+ throw err;
52
+ }
53
+ }
54
+ });
55
+ }
56
+ const STALE_OUTPUT_MS = 7 * 24 * 60 * 60 * 1000;
57
+ const OUTPUT_FILE = /^cypress-open-\d+-\d+(?:-\d+)?(?:-app(\d+))?\.(?:out|err)$/;
58
+ function isRunning(pid) {
59
+ try {
60
+ process.kill(pid, 0);
61
+ return true;
62
+ }
63
+ catch (err) {
64
+ return err instanceof Error && 'code' in err && err.code === 'EPERM';
65
+ }
66
+ }
67
+ // The app keeps writing to these files after the CLI exits, so they cannot be removed
68
+ // on success. Older ones are removed the next time a detached run starts, unless the app
69
+ // they are named for is still running and has only been quiet.
70
+ function pruneStaleDetachedOutput() {
71
+ return xvfb.__awaiter(this, arguments, void 0, function* (now = Date.now()) {
72
+ try {
73
+ const dir = os.tmpdir();
74
+ yield Promise.all((yield fs.readdir(dir)).map((name) => xvfb.__awaiter(this, void 0, void 0, function* () {
75
+ const match = OUTPUT_FILE.exec(name);
76
+ if (!match || (match[1] && isRunning(Number(match[1])))) {
77
+ return;
78
+ }
79
+ const file = path.join(dir, name);
80
+ if (now - (yield fs.stat(file)).mtimeMs > STALE_OUTPUT_MS) {
81
+ yield fs.remove(file);
82
+ }
83
+ })));
84
+ }
85
+ catch (_a) {
86
+ // Best effort: a file that cannot be listed or removed is left for next time
87
+ }
88
+ });
89
+ }
90
+ function closeDetachedOutput(_a) {
91
+ return xvfb.__awaiter(this, arguments, void 0, function* ({ outFd, errFd }) {
92
+ yield Promise.all([outFd, errFd].map((fd) => fs.close(fd).catch(() => undefined)));
93
+ });
94
+ }
95
+ function removeDetachedOutput(_a) {
96
+ return xvfb.__awaiter(this, arguments, void 0, function* ({ outPath, errPath }) {
97
+ yield Promise.all([outPath, errPath].map((file) => fs.remove(file).catch(() => undefined)));
98
+ });
99
+ }
100
+ const withAppPid = (file, pid) => file.replace(/\.(out|err)$/, `-app${pid}.$1`);
101
+ // Puts the app's pid in the names of its output files, so pruning can tell they are still in use.
102
+ // A file that cannot be renamed keeps its name, which only makes it prunable after a week.
103
+ function nameForApp(output, pid) {
104
+ return xvfb.__awaiter(this, void 0, void 0, function* () {
105
+ if (!pid) {
106
+ return output;
107
+ }
108
+ const rename = (file) => xvfb.__awaiter(this, void 0, void 0, function* () {
109
+ const named = withAppPid(file, pid);
110
+ return fs.rename(file, named).then(() => named, () => file);
111
+ });
112
+ const [outPath, errPath] = yield Promise.all([rename(output.outPath), rename(output.errPath)]);
113
+ return Object.assign(Object.assign({}, output), { outPath, errPath });
114
+ });
115
+ }
116
+ // For output that no app was started with
117
+ function discardDetachedOutput(output) {
118
+ return xvfb.__awaiter(this, void 0, void 0, function* () {
119
+ yield closeDetachedOutput(output);
120
+ yield removeDetachedOutput(output);
121
+ });
122
+ }
123
+ // Undefined when the file cannot be opened yet, so the next poll tries again
124
+ const openForReading = (file) => fs.open(file, 'r').catch(() => undefined);
125
+ // Only the bytes after `offset`, so a long-running app's log is not read again from the start on every poll
126
+ function readFrom(fd, offset) {
127
+ return xvfb.__awaiter(this, void 0, void 0, function* () {
128
+ if (fd === undefined) {
129
+ return Buffer.alloc(0);
130
+ }
131
+ try {
132
+ const { size } = yield fs.fstat(fd);
133
+ if (size <= offset) {
134
+ return Buffer.alloc(0);
135
+ }
136
+ const chunk = Buffer.alloc(size - offset);
137
+ const { bytesRead } = yield fs.read(fd, chunk, 0, chunk.length, offset);
138
+ return chunk.subarray(0, bytesRead);
139
+ }
140
+ catch (_a) {
141
+ return Buffer.alloc(0);
142
+ }
143
+ });
144
+ }
145
+ // The CLI's own output closing (a pipe the caller stopped reading) must not crash the wait
146
+ function write(stream, chunk) {
147
+ try {
148
+ stream.write(chunk);
149
+ }
150
+ catch (_a) {
151
+ // nothing to report to
152
+ }
153
+ }
154
+ // The length of the longest suffix of `text` that could still become the start of the sentinel
155
+ function partialSentinelLength(text) {
156
+ const max = Math.min(text.length, CYPRESS_OPEN_READY_MESSAGE.length - 1);
157
+ for (let length = max; length > 0; length--) {
158
+ if (CYPRESS_OPEN_READY_MESSAGE.startsWith(text.slice(-length))) {
159
+ return length;
160
+ }
161
+ }
162
+ return 0;
163
+ }
164
+ /**
165
+ * Polls the files the app writes to, forwarding anything printed before the
166
+ * ready message to the CLI's own output.
167
+ * Resolves with `ready: true` once the ready message is seen and the child is
168
+ * still running one poll interval later. Resolves with `ready: false` and the
169
+ * child's exit code if it exits before then, forwarding what it printed after
170
+ * the ready message, since nothing is handed off.
171
+ */
172
+ function waitForReadyMessage(outPath, errPath, child, onStderr = (chunk) => {
173
+ write(process$1.stderr, chunk);
174
+ }) {
175
+ return new Promise((resolve) => {
176
+ const outDecoder = new require$$1.StringDecoder('utf8');
177
+ let outOffset = 0;
178
+ let errOffset = 0;
179
+ let held = '';
180
+ let readySeen = false;
181
+ // Only shown if the app turns out to be gone, since otherwise it keeps going to the files
182
+ let afterReady = '';
183
+ let exit;
184
+ let outFd;
185
+ let errFd;
186
+ const forwardStderr = () => xvfb.__awaiter(this, void 0, void 0, function* () {
187
+ errFd = errFd !== null && errFd !== void 0 ? errFd : yield openForReading(errPath);
188
+ const chunk = yield readFrom(errFd, errOffset);
189
+ errOffset += chunk.length;
190
+ if (chunk.length)
191
+ onStderr(chunk);
192
+ });
193
+ // Returns true when the ready message was found
194
+ const forwardStdout = () => xvfb.__awaiter(this, void 0, void 0, function* () {
195
+ outFd = outFd !== null && outFd !== void 0 ? outFd : yield openForReading(outPath);
196
+ const chunk = yield readFrom(outFd, outOffset);
197
+ outOffset += chunk.length;
198
+ if (readySeen) {
199
+ afterReady += outDecoder.write(chunk);
200
+ return true;
201
+ }
202
+ const text = held + outDecoder.write(chunk);
203
+ const readyIndex = text.indexOf(CYPRESS_OPEN_READY_MESSAGE);
204
+ if (readyIndex !== -1) {
205
+ readySeen = true;
206
+ held = '';
207
+ afterReady = text.slice(readyIndex + CYPRESS_OPEN_READY_MESSAGE.length);
208
+ if (readyIndex > 0)
209
+ write(process$1.stdout, text.slice(0, readyIndex));
210
+ return true;
211
+ }
212
+ // The ready message may be split across two reads, so hold back anything that could be its start
213
+ const holdLength = exit === undefined ? partialSentinelLength(text) : 0;
214
+ held = text.slice(text.length - holdLength);
215
+ const forward = text.slice(0, text.length - holdLength);
216
+ if (forward)
217
+ write(process$1.stdout, forward);
218
+ return false;
219
+ });
220
+ let wake;
221
+ // An exit that arrived during the reads had no sleep to wake, so it is not waited out
222
+ const sleep = () => {
223
+ return new Promise((done) => {
224
+ if (exit !== undefined) {
225
+ return done();
226
+ }
227
+ const timer = setTimeout(done, POLL_INTERVAL_MS);
228
+ wake = () => {
229
+ clearTimeout(timer);
230
+ done();
231
+ };
232
+ });
233
+ };
234
+ const onExit = (code) => {
235
+ exit = code;
236
+ wake === null || wake === void 0 ? void 0 : wake();
237
+ };
238
+ // 'exit' rather than 'close', which also waits for any stdio pipes to close: the app's output is
239
+ // read from files, and the ready check needs to see the exit as soon as Node reports it
240
+ child.once('exit', (code, signal) => {
241
+ onExit(code !== null && code !== void 0 ? code : (signal ? signalExitCode(signal) : 1));
242
+ });
243
+ child.once('error', () => onExit(1));
244
+ const poll = () => xvfb.__awaiter(this, void 0, void 0, function* () {
245
+ try {
246
+ for (;;) {
247
+ // Reads that start after the child is known to be gone also drain what it wrote just before exiting
248
+ const exitedWith = exit;
249
+ const ready = yield forwardStdout();
250
+ yield forwardStderr();
251
+ if (ready) {
252
+ // An app that crashes just after printing the ready message may not be reported as exited
253
+ // yet, so its exit gets one more interval to arrive before the app is handed off. Timers
254
+ // run before Node handles an exit that is already pending, so `exit` is only read once
255
+ // setImmediate has let that happen.
256
+ yield sleep();
257
+ yield new Promise((resolve) => setImmediate(resolve));
258
+ if (exit === undefined) {
259
+ return { ready: true, code: 0 };
260
+ }
261
+ // An app that printed the ready message and has already exited is not running to be handed off
262
+ if (exitedWith === undefined) {
263
+ yield forwardStdout();
264
+ yield forwardStderr();
265
+ }
266
+ const remaining = afterReady.replace(/^\r?\n/, '');
267
+ if (remaining)
268
+ write(process$1.stdout, remaining);
269
+ return { ready: false, code: exit };
270
+ }
271
+ if (exitedWith !== undefined) {
272
+ return { ready: false, code: exitedWith };
273
+ }
274
+ yield sleep();
275
+ }
276
+ }
277
+ finally {
278
+ yield Promise.all([outFd, errFd].map((fd) => (fd === undefined ? undefined : fs.close(fd).catch(() => undefined))));
279
+ }
280
+ });
281
+ resolve(poll());
282
+ });
283
+ }
284
+
19
285
  const debug$1 = Debug('cypress:cli');
20
286
  const verifyTestRunnerTimeoutMs = () => {
21
287
  const verifyTimeout = +((xvfb.util === null || xvfb.util === void 0 ? void 0 : xvfb.util.getEnv('CYPRESS_VERIFY_TIMEOUT')) || 'NaN');
@@ -47,8 +313,15 @@ const checkExecutable = (binaryDir) => xvfb.__awaiter(void 0, void 0, void 0, fu
47
313
  }
48
314
  });
49
315
  const runSmokeTest = (binaryDir, options) => {
316
+ var _a;
50
317
  let executable = xvfb.stateModule.getPathToExecutable(binaryDir);
51
- const needsXvfb = xvfb.xvfb.isNeeded();
318
+ const env = (_a = options.env) !== null && _a !== void 0 ? _a : process.env;
319
+ // The smoke test is run with the environment as it is when it runs, because starting
320
+ // Xvfb sets DISPLAY after this point, and execa adds that to what it is given. So a
321
+ // variable the caller took out has to be named with no value to stay out.
322
+ const removedFromEnv = _.mapValues(_.pickBy(process.env, (_value, key) => !(key in env)), () => undefined);
323
+ const changedInEnv = _.pickBy(env, (value, key) => process.env[key] !== value);
324
+ const needsXvfb = xvfb.xvfb.isNeeded(env);
52
325
  debug$1('needs Xvfb?', needsXvfb);
53
326
  /**
54
327
  * Spawn Cypress running smoke test to check if all operating system
@@ -76,7 +349,7 @@ const runSmokeTest = (binaryDir, options) => {
76
349
  debug$1('smoke test command:', smokeTestCommand);
77
350
  debug$1('smoke test timeout %d ms', options.smokeTestTimeout);
78
351
  const stdioOptions = _.extend({}, {
79
- env: Object.assign(Object.assign({}, process.env), { FORCE_COLOR: '0' }),
352
+ env: Object.assign(Object.assign(Object.assign({}, removedFromEnv), changedInEnv), { FORCE_COLOR: '0' }),
80
353
  timeout: options.smokeTestTimeout,
81
354
  });
82
355
  try {
@@ -95,7 +368,7 @@ const runSmokeTest = (binaryDir, options) => {
95
368
  }
96
369
  catch (err) {
97
370
  debug$1('Smoke test failed:', err);
98
- let errMessage = err.stderr || err.message;
371
+ const errMessage = err.stderr || err.message;
99
372
  debug$1('error message:', errMessage);
100
373
  if (err.timedOut) {
101
374
  debug$1('error timedOut is true');
@@ -179,7 +452,7 @@ function verifyBinary(installedVersion, binaryDir, options) {
179
452
  });
180
453
  }
181
454
  const start$1 = (...args_1) => xvfb.__awaiter(void 0, [...args_1], void 0, function* (options = {}) {
182
- debug$1('verifying Cypress app with options %j', options);
455
+ debug$1('verifying Cypress app with options %j', _.omit(options, 'env'));
183
456
  _.defaults(options, {
184
457
  dev: false,
185
458
  force: false,
@@ -358,7 +631,7 @@ function requireLineDecoder () {
358
631
  */
359
632
  *[Symbol.iterator]() {
360
633
  debugVerbose('iterating over lines in line decoder');
361
- let nextLine = undefined;
634
+ let nextLine;
362
635
  do {
363
636
  nextLine = this.nextLine();
364
637
  if (nextLine) {
@@ -380,7 +653,7 @@ function requireLineDecoder () {
380
653
  */
381
654
  *end(chunk) {
382
655
  this.buffer = `${this.buffer}${(chunk || '')}`;
383
- let nextLine = undefined;
656
+ let nextLine;
384
657
  do {
385
658
  nextLine = this.nextLine();
386
659
  if (nextLine) {
@@ -1053,8 +1326,6 @@ var distExports = requireDist();
1053
1326
  const debug = Debug('cypress:cli');
1054
1327
  const debugElectron = Debug('cypress:electron');
1055
1328
  const debugStderr = Debug('cypress:internal-stderr');
1056
- // Must match CYPRESS_OPEN_READY_MESSAGE in packages/server/lib/modes/interactive.ts
1057
- const CYPRESS_OPEN_READY_MESSAGE = 'Cypress is ready';
1058
1329
  function isPlatform(platform) {
1059
1330
  return os.platform() === platform;
1060
1331
  }
@@ -1083,14 +1354,89 @@ function getStdioStrategy(needsXvfb) {
1083
1354
  }
1084
1355
  return 'inherit';
1085
1356
  }
1086
- function createSpawnFunction(executable, args, options) {
1087
- return (overrides = {}) => {
1357
+ // Where a child's stderr is written: straight through when logging is on, otherwise
1358
+ // through the filter that drops the noise Xlib and libuv print
1359
+ function pipeToFilteredStderr() {
1360
+ var _a, _b;
1361
+ const sourceStream = new require$$0.PassThrough();
1362
+ if (((_a = process$1.env.ELECTRON_ENABLE_LOGGING) !== null && _a !== void 0 ? _a : '') === '1' ||
1363
+ debugElectron.enabled ||
1364
+ ((_b = process$1.env.CYPRESS_INTERNAL_ENV) !== null && _b !== void 0 ? _b : '') === 'development') {
1365
+ sourceStream.pipe(process$1.stderr, { end: false });
1366
+ }
1367
+ else {
1368
+ sourceStream.pipe(distExports.filter(process$1.stderr, debugStderr, distExports.DEBUG_PREFIX));
1369
+ }
1370
+ return sourceStream;
1371
+ }
1372
+ const INTERRUPT_SIGNALS = ['SIGINT', 'SIGTERM'];
1373
+ // The signal reaches the processes the app started too, as Ctrl-C does for an app that is not
1374
+ // detached. On Windows that takes the process tree; elsewhere the app leads a process group of its own.
1375
+ function killApp(child, signal = 'SIGTERM') {
1376
+ const pid = child.pid;
1377
+ if (pid && isPlatform('win32')) {
1378
+ const killOnlyApp = (err) => {
1379
+ debug('could not kill the process tree of the app, signalling only the app %o', err);
1380
+ child.kill(signal);
1381
+ };
1382
+ void import('tree-kill').then(({ default: kill }) => {
1383
+ kill(pid, signal, (err) => {
1384
+ if (err)
1385
+ killOnlyApp(err);
1386
+ });
1387
+ }).catch(killOnlyApp);
1388
+ return;
1389
+ }
1390
+ if (pid) {
1391
+ try {
1392
+ process$1.kill(-pid, signal);
1393
+ return;
1394
+ }
1395
+ catch (err) {
1396
+ debug('could not signal the process group of the app, signalling only the app %o', err);
1397
+ }
1398
+ }
1399
+ child.kill(signal);
1400
+ }
1401
+ function createSpawnFunction(executable, baseArgs, options) {
1402
+ // `done` is set once a detached app is running on its own, so its Xvfb is not stopped with the
1403
+ // CLI. `signal` is the interrupt that stopped a detached app before it was ready.
1404
+ const handoff = { done: false };
1405
+ // The detached app that has been spawned but is not ready yet
1406
+ let startingChild;
1407
+ // Until a detached app is ready there is nothing to hand off, so an interrupt stops the launch
1408
+ // instead of leaving the app, or a Xvfb started for it in a session of its own, running unseen.
1409
+ // Before the app is spawned that means stopping the Xvfb, which also ends a wait for one that is
1410
+ // slow to start. A second interrupt does not wait for an app that ignored the first.
1411
+ const interruptHandlers = INTERRUPT_SIGNALS.map((signal) => {
1412
+ const handler = () => {
1413
+ var _a;
1414
+ debug('%s received before the app was ready, stopping it', signal);
1415
+ if (startingChild) {
1416
+ killApp(startingChild, handoff.signal ? 'SIGKILL' : signal);
1417
+ }
1418
+ else {
1419
+ void xvfb.xvfb.stop();
1420
+ }
1421
+ handoff.signal = (_a = handoff.signal) !== null && _a !== void 0 ? _a : signal;
1422
+ };
1423
+ return { signal, handler };
1424
+ });
1425
+ const armInterrupts = () => {
1426
+ interruptHandlers.forEach(({ signal, handler }) => process$1.on(signal, handler));
1427
+ };
1428
+ // Safe to call again once disarmed: removing a handler that is not there does nothing
1429
+ const disarmInterrupts = () => {
1430
+ interruptHandlers.forEach(({ signal, handler }) => process$1.off(signal, handler));
1431
+ };
1432
+ const spawnFunction = (overrides = {}) => {
1088
1433
  return new Promise((resolve, reject) => xvfb.__awaiter(this, void 0, void 0, function* () {
1089
- var _a, _b;
1090
1434
  _.defaults(overrides, {
1091
1435
  onStderrData: false,
1092
1436
  });
1093
1437
  const { onStderrData } = overrides;
1438
+ // Copied, so a retry inside Xvfb starts from the same arguments as the first attempt
1439
+ let args = [...baseArgs];
1094
1440
  const envOverrides = xvfb.util.getEnvOverrides(options);
1095
1441
  const electronArgs = [];
1096
1442
  const node11WindowsFix = isPlatform('win32');
@@ -1127,11 +1473,8 @@ function createSpawnFunction(executable, args, options) {
1127
1473
  stdioOptions.env.DISPLAY = process$1.env.DISPLAY;
1128
1474
  }
1129
1475
  if (stdioOptions.detached) {
1130
- // Ask interactive mode to print a ready sentinel on stdout; pipe stdio during
1131
- // startup so errors are visible and we can detect it. Streams are destroyed
1132
- // once it arrives so they don't keep the parent event loop alive.
1476
+ // Ask interactive mode to print a ready sentinel on stdout
1133
1477
  args.push('--emit-when-ready');
1134
- stdioOptions.stdio = ['ignore', 'pipe', 'pipe'];
1135
1478
  }
1136
1479
  if (stdioOptions.env.ELECTRON_RUN_AS_NODE) {
1137
1480
  // Since we are running electron as node, we need to add an entry point file.
@@ -1156,6 +1499,9 @@ function createSpawnFunction(executable, args, options) {
1156
1499
  if (!platform) {
1157
1500
  return;
1158
1501
  }
1502
+ if (handoff.signal) {
1503
+ return resolve(signalExitCode(handoff.signal));
1504
+ }
1159
1505
  function resolveOn(event) {
1160
1506
  return function (code, signal) {
1161
1507
  debug('child event fired %o', { event, code, signal });
@@ -1164,17 +1510,89 @@ function createSpawnFunction(executable, args, options) {
1164
1510
  resolve(0);
1165
1511
  }
1166
1512
  else {
1167
- resolve(128 + os.constants.signals[signal]);
1513
+ resolve(signalExitCode(signal));
1168
1514
  }
1169
1515
  return;
1170
1516
  }
1171
1517
  resolve(code !== null && code !== void 0 ? code : 1);
1172
1518
  };
1173
1519
  }
1174
- const child = cp.spawn(executable, args, stdioOptions);
1175
- child.on('close', resolveOn('close'));
1176
- child.on('exit', resolveOn('exit'));
1520
+ let detachedOutput;
1521
+ if (stdioOptions.detached) {
1522
+ try {
1523
+ detachedOutput = yield openDetachedOutput();
1524
+ }
1525
+ catch (err) {
1526
+ return reject(err);
1527
+ }
1528
+ if (handoff.signal) {
1529
+ yield discardDetachedOutput(detachedOutput);
1530
+ return resolve(signalExitCode(handoff.signal));
1531
+ }
1532
+ stdioOptions.stdio = ['ignore', detachedOutput.outFd, detachedOutput.errFd];
1533
+ }
1534
+ let child;
1535
+ try {
1536
+ child = cp.spawn(executable, args, stdioOptions);
1537
+ }
1538
+ catch (err) {
1539
+ if (detachedOutput) {
1540
+ yield discardDetachedOutput(detachedOutput);
1541
+ }
1542
+ return reject(err);
1543
+ }
1544
+ // A detached app's exit is reported by waiting on its output, so what it printed
1545
+ // just before exiting is not cut off by the CLI exiting first
1546
+ if (!detachedOutput) {
1547
+ child.on('close', resolveOn('close'));
1548
+ child.on('exit', resolveOn('exit'));
1549
+ }
1177
1550
  child.on('error', reject);
1551
+ // A detached app outlives the CLI, so it gets no signal forwarding and nothing that keeps the CLI alive
1552
+ if (detachedOutput) {
1553
+ const output = detachedOutput;
1554
+ const filteredStderr = pipeToFilteredStderr();
1555
+ startingChild = child;
1556
+ let ready;
1557
+ let code;
1558
+ try {
1559
+ ({ ready, code } = yield waitForReadyMessage(output.outPath, output.errPath, child, (chunk) => {
1560
+ if (onStderrData && onStderrData(chunk.toString())) {
1561
+ return;
1562
+ }
1563
+ filteredStderr.write(chunk);
1564
+ }));
1565
+ }
1566
+ catch (err) {
1567
+ killApp(child);
1568
+ yield removeDetachedOutput(output);
1569
+ return reject(err);
1570
+ }
1571
+ finally {
1572
+ filteredStderr.end();
1573
+ yield closeDetachedOutput(output);
1574
+ }
1575
+ // Renamed while an interrupt still stops the app, so no app is handed off under the old names
1576
+ const named = ready && !handoff.signal ? yield nameForApp(output, child.pid) : output;
1577
+ // An app that was told to stop after it printed the ready message is still shutting down.
1578
+ // It stays the starting child until it has exited, so another interrupt still kills it.
1579
+ if (ready && handoff.signal) {
1580
+ yield waitForExit(child);
1581
+ }
1582
+ startingChild = undefined;
1583
+ if (ready && !handoff.signal) {
1584
+ child.unref();
1585
+ handoff.done = true;
1586
+ disarmInterrupts();
1587
+ process$1.stdout.write(`Cypress is running in the background. Its output is written to "${named.outPath}" and "${named.errPath}"\n`);
1588
+ resolve(0);
1589
+ }
1590
+ else {
1591
+ yield removeDetachedOutput(named);
1592
+ resolve(handoff.signal ? signalExitCode(handoff.signal) : code);
1593
+ }
1594
+ return;
1595
+ }
1178
1596
  if (isPlatform('win32')) {
1179
1597
  const rl = readline.createInterface({
1180
1598
  input: process$1.stdin,
@@ -1207,26 +1625,6 @@ function createSpawnFunction(executable, args, options) {
1207
1625
  });
1208
1626
  }
1209
1627
  }
1210
- if (stdioOptions.detached) {
1211
- child.stdout.on('data', (data) => {
1212
- const str = data.toString();
1213
- const readyMessageIndex = str.indexOf(CYPRESS_OPEN_READY_MESSAGE);
1214
- const isReady = readyMessageIndex !== -1;
1215
- if (isReady) {
1216
- const outputBeforeReady = str.slice(0, readyMessageIndex);
1217
- if (outputBeforeReady)
1218
- process$1.stdout.write(outputBeforeReady);
1219
- child.stdout.destroy();
1220
- child.stderr.destroy();
1221
- child.unref();
1222
- resolve(0);
1223
- return;
1224
- }
1225
- process$1.stdout.write(data);
1226
- });
1227
- child.stderr.pipe(process$1.stderr, { end: false });
1228
- return;
1229
- }
1230
1628
  // if stdio options is set to 'pipe', then
1231
1629
  // we should set up pipes:
1232
1630
  // process STDIN (read stream) => child STDIN (writeable)
@@ -1244,7 +1642,7 @@ function createSpawnFunction(executable, args, options) {
1244
1642
  // to filter out the garbage
1245
1643
  if (child.stderr) {
1246
1644
  debug('piping child STDERR to process STDERR');
1247
- const sourceStream = new require$$0.PassThrough();
1645
+ const sourceStream = pipeToFilteredStderr();
1248
1646
  child.on('close', () => {
1249
1647
  sourceStream.end();
1250
1648
  });
@@ -1257,14 +1655,6 @@ function createSpawnFunction(executable, args, options) {
1257
1655
  sourceStream.write(data);
1258
1656
  }
1259
1657
  });
1260
- if (((_a = process$1.env.ELECTRON_ENABLE_LOGGING) !== null && _a !== void 0 ? _a : '') === '1' ||
1261
- debugElectron.enabled ||
1262
- ((_b = process$1.env.CYPRESS_INTERNAL_ENV) !== null && _b !== void 0 ? _b : '') === 'development') {
1263
- sourceStream.pipe(process$1.stderr, { end: false });
1264
- }
1265
- else {
1266
- sourceStream.pipe(distExports.filter(process$1.stderr, debugStderr, distExports.DEBUG_PREFIX));
1267
- }
1268
1658
  }
1269
1659
  // https://github.com/cypress-io/cypress/issues/1841
1270
1660
  // https://github.com/cypress-io/cypress/issues/5241
@@ -1282,17 +1672,62 @@ function createSpawnFunction(executable, args, options) {
1282
1672
  });
1283
1673
  }));
1284
1674
  };
1675
+ return Object.assign(spawnFunction, {
1676
+ handedOff: () => handoff.done,
1677
+ interruptedBy: () => handoff.signal,
1678
+ isDetached: () => Boolean(options.detached),
1679
+ armInterrupts,
1680
+ disarmInterrupts,
1681
+ });
1682
+ }
1683
+ const STOP_GRACE_MS = 5000;
1684
+ // Resolves once the child has exited, killing it if it ignores the signal it was sent
1685
+ function waitForExit(child) {
1686
+ return xvfb.__awaiter(this, void 0, void 0, function* () {
1687
+ var _a;
1688
+ const exited = ((_a = child.exitCode) !== null && _a !== void 0 ? _a : null) !== null || Boolean(child.signalCode);
1689
+ if (exited) {
1690
+ return;
1691
+ }
1692
+ yield new Promise((resolve) => {
1693
+ const timer = setTimeout(() => {
1694
+ killApp(child, 'SIGKILL');
1695
+ resolve();
1696
+ }, STOP_GRACE_MS);
1697
+ child.once('exit', () => {
1698
+ clearTimeout(timer);
1699
+ resolve();
1700
+ });
1701
+ });
1702
+ });
1285
1703
  }
1286
1704
  function spawnInXvfb(spawn) {
1287
1705
  return xvfb.__awaiter(this, void 0, void 0, function* () {
1288
1706
  try {
1289
- yield xvfb.xvfb.start();
1707
+ try {
1708
+ yield xvfb.xvfb.start({ detached: spawn.isDetached() });
1709
+ }
1710
+ catch (err) {
1711
+ const signal = spawn.interruptedBy();
1712
+ // An interrupt stops a Xvfb that is still starting, so this failure is the interrupt working
1713
+ if (signal) {
1714
+ debug('xvfb was stopped by %s while it started', signal);
1715
+ return signalExitCode(signal);
1716
+ }
1717
+ throw err;
1718
+ }
1290
1719
  debug('xvfb started');
1291
1720
  const code = yield userFriendlySpawn(spawn);
1292
1721
  return code;
1293
1722
  }
1294
1723
  finally {
1295
- yield xvfb.xvfb.stop();
1724
+ if (spawn.handedOff()) {
1725
+ debug('app was handed off, leaving xvfb running');
1726
+ xvfb.xvfb.release();
1727
+ }
1728
+ else {
1729
+ yield xvfb.xvfb.stop();
1730
+ }
1296
1731
  }
1297
1732
  });
1298
1733
  }
@@ -1316,7 +1751,8 @@ function userFriendlySpawn(spawn, linuxWithDisplayEnv) {
1316
1751
  try {
1317
1752
  const code = yield spawn(overrides);
1318
1753
  debug('tried spawning without xvfb, code', code, brokenGtkDisplay);
1319
- if (code !== 0 && brokenGtkDisplay) {
1754
+ // An interrupted app is not retried: the person who stopped it does not want a second one
1755
+ if (code !== 0 && brokenGtkDisplay && !spawn.interruptedBy()) {
1320
1756
  xvfb.util.logBrokenGtkDisplayWarning();
1321
1757
  return spawnInXvfb(spawn);
1322
1758
  }
@@ -1337,7 +1773,7 @@ function userFriendlySpawn(spawn, linuxWithDisplayEnv) {
1337
1773
  function start(args_1) {
1338
1774
  return xvfb.__awaiter(this, arguments, void 0, function* (args, options = {}) {
1339
1775
  var _a, _b, _c, _d;
1340
- let executable = xvfb.util.getEnv('CYPRESS_RUN_BINARY') ?
1776
+ const executable = xvfb.util.getEnv('CYPRESS_RUN_BINARY') ?
1341
1777
  path.resolve(xvfb.util.getEnv('CYPRESS_RUN_BINARY')) :
1342
1778
  xvfb.stateModule.getPathToExecutable(xvfb.stateModule.getBinaryDir());
1343
1779
  // Always push cwd into the args
@@ -1349,25 +1785,49 @@ function start(args_1) {
1349
1785
  '--userNodePath', process$1.execPath,
1350
1786
  '--userNodeVersion', process$1.versions.node,
1351
1787
  ]);
1352
- const needsXvfb = xvfb.xvfb.isNeeded();
1788
+ const env = (_a = options.env) !== null && _a !== void 0 ? _a : process$1.env;
1789
+ const needsXvfb = xvfb.xvfb.isNeeded(env);
1353
1790
  debug('needs to start own Xvfb?', needsXvfb);
1354
- const stdio = (_a = options.stdio) !== null && _a !== void 0 ? _a : getStdioStrategy(needsXvfb);
1355
- const dev = (_b = options.dev) !== null && _b !== void 0 ? _b : false;
1356
- const detached = (_c = options.detached) !== null && _c !== void 0 ? _c : false;
1357
- const env = (_d = options.env) !== null && _d !== void 0 ? _d : process$1.env;
1791
+ const stdio = (_b = options.stdio) !== null && _b !== void 0 ? _b : getStdioStrategy(needsXvfb);
1792
+ const dev = (_c = options.dev) !== null && _c !== void 0 ? _c : false;
1793
+ const detached = (_d = options.detached) !== null && _d !== void 0 ? _d : false;
1358
1794
  const spawn = createSpawnFunction(executable, decoratedArgs, { stdio, dev, detached, env });
1359
- if (needsXvfb) {
1360
- debug('starting xvfb');
1361
- return spawnInXvfb(spawn);
1795
+ let code;
1796
+ // Armed before Xvfb starts, and kept until it is stopped, so no interrupt can end the CLI
1797
+ // between the two and leave a Xvfb in a session of its own that no app ever connects to
1798
+ if (detached) {
1799
+ spawn.armInterrupts();
1362
1800
  }
1363
- // if we are on linux and there's already a DISPLAY
1364
- // set, then we may need to rerun cypress after
1365
- // spawning our own Xvfb server
1366
- const linuxWithDisplayEnv = xvfb.util.isPossibleLinuxWithIncorrectDisplay();
1367
- debug('linuxWithDisplayEnv', linuxWithDisplayEnv);
1368
- return userFriendlySpawn(spawn, linuxWithDisplayEnv);
1801
+ try {
1802
+ if (needsXvfb) {
1803
+ debug('starting xvfb');
1804
+ code = yield spawnInXvfb(spawn);
1805
+ }
1806
+ else {
1807
+ // if we are on linux and there's already a DISPLAY
1808
+ // set, then we may need to rerun cypress after
1809
+ // spawning our own Xvfb server
1810
+ const linuxWithDisplayEnv = xvfb.util.isPossibleLinuxWithIncorrectDisplay();
1811
+ debug('linuxWithDisplayEnv', linuxWithDisplayEnv);
1812
+ code = yield userFriendlySpawn(spawn, linuxWithDisplayEnv);
1813
+ }
1814
+ }
1815
+ finally {
1816
+ spawn.disarmInterrupts();
1817
+ reraiseInterrupt(spawn.interruptedBy());
1818
+ }
1819
+ return code;
1369
1820
  });
1370
1821
  }
1822
+ // Listening for the signal while a detached app started took away its default action. A host with
1823
+ // no handler of its own is left to the default once the app and its Xvfb are stopped, so Ctrl-C
1824
+ // ends it as it would have without this CLI.
1825
+ function reraiseInterrupt(signal) {
1826
+ if (signal && process$1.listenerCount(signal) === 0) {
1827
+ debug('re-raising %s now that the app is stopped', signal);
1828
+ process$1.kill(process$1.pid, signal);
1829
+ }
1830
+ }
1371
1831
 
1372
1832
  exports.start = start$1;
1373
1833
  exports.start$1 = start;