@pkg-nec/jest-core 30.4.2

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.
package/build/index.js ADDED
@@ -0,0 +1,4222 @@
1
+ /*!
2
+ * /**
3
+ * * Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ * *
5
+ * * This source code is licensed under the MIT license found in the
6
+ * * LICENSE file in the root directory of this source tree.
7
+ * * /
8
+ */
9
+ /******/ (() => { // webpackBootstrap
10
+ /******/ "use strict";
11
+ /******/ var __webpack_modules__ = ({
12
+
13
+ /***/ "./src/FailedTestsCache.ts"
14
+ (__unused_webpack_module, exports) {
15
+
16
+
17
+
18
+ Object.defineProperty(exports, "__esModule", ({
19
+ value: true
20
+ }));
21
+ exports["default"] = void 0;
22
+ /**
23
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
24
+ *
25
+ * This source code is licensed under the MIT license found in the
26
+ * LICENSE file in the root directory of this source tree.
27
+ */
28
+
29
+ class FailedTestsCache {
30
+ _enabledTestsMap;
31
+ filterTests(tests) {
32
+ const enabledTestsMap = this._enabledTestsMap;
33
+ if (!enabledTestsMap) {
34
+ return tests;
35
+ }
36
+ return tests.filter(test => enabledTestsMap[test.path]);
37
+ }
38
+ setTestResults(testResults) {
39
+ this._enabledTestsMap = (testResults || []).reduce((suiteMap, testResult) => {
40
+ if (testResult.testExecError) {
41
+ suiteMap[testResult.testFilePath] = {};
42
+ return suiteMap;
43
+ }
44
+ if (!testResult.numFailingTests) {
45
+ return suiteMap;
46
+ }
47
+ suiteMap[testResult.testFilePath] = testResult.testResults.reduce((testMap, test) => {
48
+ if (test.status !== 'failed') {
49
+ return testMap;
50
+ }
51
+ testMap[test.fullName] = true;
52
+ return testMap;
53
+ }, {});
54
+ return suiteMap;
55
+ }, {});
56
+ this._enabledTestsMap = Object.freeze(this._enabledTestsMap);
57
+ }
58
+ }
59
+ exports["default"] = FailedTestsCache;
60
+
61
+ /***/ },
62
+
63
+ /***/ "./src/FailedTestsInteractiveMode.ts"
64
+ (__unused_webpack_module, exports) {
65
+
66
+
67
+
68
+ Object.defineProperty(exports, "__esModule", ({
69
+ value: true
70
+ }));
71
+ exports["default"] = void 0;
72
+ function _ansiEscapes() {
73
+ const data = _interopRequireDefault(require("ansi-escapes"));
74
+ _ansiEscapes = function () {
75
+ return data;
76
+ };
77
+ return data;
78
+ }
79
+ function _chalk() {
80
+ const data = _interopRequireDefault(require("chalk"));
81
+ _chalk = function () {
82
+ return data;
83
+ };
84
+ return data;
85
+ }
86
+ function _jestUtil() {
87
+ const data = require("@pkg-nec/jest-util");
88
+ _jestUtil = function () {
89
+ return data;
90
+ };
91
+ return data;
92
+ }
93
+ function _jestWatcher() {
94
+ const data = require("@pkg-nec/jest-watcher");
95
+ _jestWatcher = function () {
96
+ return data;
97
+ };
98
+ return data;
99
+ }
100
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
101
+ /**
102
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
103
+ *
104
+ * This source code is licensed under the MIT license found in the
105
+ * LICENSE file in the root directory of this source tree.
106
+ */
107
+
108
+ const {
109
+ ARROW,
110
+ CLEAR
111
+ } = _jestUtil().specialChars;
112
+ function describeKey(key, description) {
113
+ return `${_chalk().default.dim(`${ARROW}Press`)} ${key} ${_chalk().default.dim(description)}`;
114
+ }
115
+ const TestProgressLabel = _chalk().default.bold('Interactive Test Progress');
116
+ class FailedTestsInteractiveMode {
117
+ _isActive = false;
118
+ _countPaths = 0;
119
+ _skippedNum = 0;
120
+ _testAssertions = [];
121
+ _updateTestRunnerConfig;
122
+ constructor(_pipe) {
123
+ this._pipe = _pipe;
124
+ }
125
+ isActive() {
126
+ return this._isActive;
127
+ }
128
+ put(key) {
129
+ switch (key) {
130
+ case 's':
131
+ if (this._skippedNum === this._testAssertions.length) {
132
+ break;
133
+ }
134
+ this._skippedNum += 1;
135
+ // move skipped test to the end
136
+ this._testAssertions.push(this._testAssertions.shift());
137
+ if (this._testAssertions.length - this._skippedNum > 0) {
138
+ this._run();
139
+ } else {
140
+ this._drawUIDoneWithSkipped();
141
+ }
142
+ break;
143
+ case 'q':
144
+ case _jestWatcher().KEYS.ESCAPE:
145
+ this.abort();
146
+ break;
147
+ case 'r':
148
+ this.restart();
149
+ break;
150
+ case _jestWatcher().KEYS.ENTER:
151
+ if (this._testAssertions.length === 0) {
152
+ this.abort();
153
+ } else {
154
+ this._run();
155
+ }
156
+ break;
157
+ default:
158
+ }
159
+ }
160
+ run(failedTestAssertions, updateConfig) {
161
+ if (failedTestAssertions.length === 0) return;
162
+ this._testAssertions = [...failedTestAssertions];
163
+ this._countPaths = this._testAssertions.length;
164
+ this._updateTestRunnerConfig = updateConfig;
165
+ this._isActive = true;
166
+ this._run();
167
+ }
168
+ updateWithResults(results) {
169
+ if (!results.snapshot.failure && results.numFailedTests > 0) {
170
+ return this._drawUIOverlay();
171
+ }
172
+ this._testAssertions.shift();
173
+ if (this._testAssertions.length === 0) {
174
+ return this._drawUIOverlay();
175
+ }
176
+
177
+ // Go to the next test
178
+ return this._run();
179
+ }
180
+ _clearTestSummary() {
181
+ this._pipe.write(_ansiEscapes().default.cursorUp(6));
182
+ this._pipe.write(_ansiEscapes().default.eraseDown);
183
+ }
184
+ _drawUIDone() {
185
+ this._pipe.write(CLEAR);
186
+ const messages = [_chalk().default.bold('Watch Usage'), describeKey('Enter', 'to return to watch mode.')];
187
+ this._pipe.write(`${messages.join('\n')}\n`);
188
+ }
189
+ _drawUIDoneWithSkipped() {
190
+ this._pipe.write(CLEAR);
191
+ let stats = `${(0, _jestUtil().pluralize)('test', this._countPaths)} reviewed`;
192
+ if (this._skippedNum > 0) {
193
+ const skippedText = _chalk().default.bold.yellow(`${(0, _jestUtil().pluralize)('test', this._skippedNum)} skipped`);
194
+ stats = `${stats}, ${skippedText}`;
195
+ }
196
+ const message = [TestProgressLabel, `${ARROW}${stats}`, '\n', _chalk().default.bold('Watch Usage'), describeKey('r', 'to restart Interactive Mode.'), describeKey('q', 'to quit Interactive Mode.'), describeKey('Enter', 'to return to watch mode.')];
197
+ this._pipe.write(`\n${message.join('\n')}`);
198
+ }
199
+ _drawUIProgress() {
200
+ this._clearTestSummary();
201
+ const numPass = this._countPaths - this._testAssertions.length;
202
+ const numRemaining = this._countPaths - numPass - this._skippedNum;
203
+ let stats = `${(0, _jestUtil().pluralize)('test', numRemaining)} remaining`;
204
+ if (this._skippedNum > 0) {
205
+ const skippedText = _chalk().default.bold.yellow(`${(0, _jestUtil().pluralize)('test', this._skippedNum)} skipped`);
206
+ stats = `${stats}, ${skippedText}`;
207
+ }
208
+ const message = [TestProgressLabel, `${ARROW}${stats}`, '\n', _chalk().default.bold('Watch Usage'), describeKey('s', 'to skip the current test.'), describeKey('q', 'to quit Interactive Mode.'), describeKey('Enter', 'to return to watch mode.')];
209
+ this._pipe.write(`\n${message.join('\n')}`);
210
+ }
211
+ _drawUIOverlay() {
212
+ if (this._testAssertions.length === 0) return this._drawUIDone();
213
+ return this._drawUIProgress();
214
+ }
215
+ _run() {
216
+ if (this._updateTestRunnerConfig) {
217
+ this._updateTestRunnerConfig(this._testAssertions[0]);
218
+ }
219
+ }
220
+ abort() {
221
+ this._isActive = false;
222
+ this._skippedNum = 0;
223
+ if (this._updateTestRunnerConfig) {
224
+ this._updateTestRunnerConfig();
225
+ }
226
+ }
227
+ restart() {
228
+ this._skippedNum = 0;
229
+ this._countPaths = this._testAssertions.length;
230
+ this._run();
231
+ }
232
+ }
233
+ exports["default"] = FailedTestsInteractiveMode;
234
+
235
+ /***/ },
236
+
237
+ /***/ "./src/ReporterDispatcher.ts"
238
+ (__unused_webpack_module, exports) {
239
+
240
+
241
+
242
+ Object.defineProperty(exports, "__esModule", ({
243
+ value: true
244
+ }));
245
+ exports["default"] = void 0;
246
+ /**
247
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
248
+ *
249
+ * This source code is licensed under the MIT license found in the
250
+ * LICENSE file in the root directory of this source tree.
251
+ */
252
+
253
+ class ReporterDispatcher {
254
+ _reporters;
255
+ constructor() {
256
+ this._reporters = [];
257
+ }
258
+ register(reporter) {
259
+ this._reporters.push(reporter);
260
+ }
261
+ unregister(reporterConstructor) {
262
+ this._reporters = this._reporters.filter(reporter => !(reporter instanceof reporterConstructor));
263
+ }
264
+ async onTestFileResult(test, testResult, results) {
265
+ for (const reporter of this._reporters) {
266
+ if (reporter.onTestFileResult) {
267
+ await reporter.onTestFileResult(test, testResult, results);
268
+ } else if (reporter.onTestResult) {
269
+ await reporter.onTestResult(test, testResult, results);
270
+ }
271
+ }
272
+
273
+ // Release memory if unused later.
274
+ testResult.coverage = undefined;
275
+ testResult.console = undefined;
276
+ }
277
+ async onTestFileStart(test) {
278
+ for (const reporter of this._reporters) {
279
+ if (reporter.onTestFileStart) {
280
+ await reporter.onTestFileStart(test);
281
+ } else if (reporter.onTestStart) {
282
+ await reporter.onTestStart(test);
283
+ }
284
+ }
285
+ }
286
+ async onRunStart(results, options) {
287
+ for (const reporter of this._reporters) {
288
+ if (reporter.onRunStart) {
289
+ await reporter.onRunStart(results, options);
290
+ }
291
+ }
292
+ }
293
+ async onTestCaseStart(test, testCaseStartInfo) {
294
+ for (const reporter of this._reporters) {
295
+ if (reporter.onTestCaseStart) {
296
+ await reporter.onTestCaseStart(test, testCaseStartInfo);
297
+ }
298
+ }
299
+ }
300
+ async onTestCaseResult(test, testCaseResult) {
301
+ for (const reporter of this._reporters) {
302
+ if (reporter.onTestCaseResult) {
303
+ await reporter.onTestCaseResult(test, testCaseResult);
304
+ }
305
+ }
306
+ }
307
+ async onRunComplete(testContexts, results) {
308
+ for (const reporter of this._reporters) {
309
+ if (reporter.onRunComplete) {
310
+ await reporter.onRunComplete(testContexts, results);
311
+ }
312
+ }
313
+ }
314
+
315
+ // Return a list of last errors for every reporter
316
+ getErrors() {
317
+ return this._reporters.reduce((list, reporter) => {
318
+ const error = reporter.getLastError?.();
319
+ return error ? [...list, error] : list;
320
+ }, []);
321
+ }
322
+ hasErrors() {
323
+ return this.getErrors().length > 0;
324
+ }
325
+ }
326
+ exports["default"] = ReporterDispatcher;
327
+
328
+ /***/ },
329
+
330
+ /***/ "./src/SearchSource.ts"
331
+ (__unused_webpack_module, exports) {
332
+
333
+
334
+
335
+ Object.defineProperty(exports, "__esModule", ({
336
+ value: true
337
+ }));
338
+ exports["default"] = void 0;
339
+ function os() {
340
+ const data = _interopRequireWildcard(require("node:os"));
341
+ os = function () {
342
+ return data;
343
+ };
344
+ return data;
345
+ }
346
+ function path() {
347
+ const data = _interopRequireWildcard(require("node:path"));
348
+ path = function () {
349
+ return data;
350
+ };
351
+ return data;
352
+ }
353
+ function _jestConfig() {
354
+ const data = require("@pkg-nec/jest-config");
355
+ _jestConfig = function () {
356
+ return data;
357
+ };
358
+ return data;
359
+ }
360
+ function _jestRegexUtil() {
361
+ const data = require("@pkg-nec/jest-regex-util");
362
+ _jestRegexUtil = function () {
363
+ return data;
364
+ };
365
+ return data;
366
+ }
367
+ function _jestResolveDependencies() {
368
+ const data = require("@pkg-nec/jest-resolve-dependencies");
369
+ _jestResolveDependencies = function () {
370
+ return data;
371
+ };
372
+ return data;
373
+ }
374
+ function _jestSnapshot() {
375
+ const data = require("@pkg-nec/jest-snapshot");
376
+ _jestSnapshot = function () {
377
+ return data;
378
+ };
379
+ return data;
380
+ }
381
+ function _jestUtil() {
382
+ const data = require("@pkg-nec/jest-util");
383
+ _jestUtil = function () {
384
+ return data;
385
+ };
386
+ return data;
387
+ }
388
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
389
+ /**
390
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
391
+ *
392
+ * This source code is licensed under the MIT license found in the
393
+ * LICENSE file in the root directory of this source tree.
394
+ */
395
+
396
+ const regexToMatcher = testRegex => {
397
+ const regexes = testRegex.map(testRegex => new RegExp(testRegex));
398
+ return path => regexes.some(regex => {
399
+ const result = regex.test(path);
400
+
401
+ // prevent stateful regexes from breaking, just in case
402
+ regex.lastIndex = 0;
403
+ return result;
404
+ });
405
+ };
406
+ const toTests = (context, tests) => tests.map(path => ({
407
+ context,
408
+ duration: undefined,
409
+ path
410
+ }));
411
+ const hasSCM = changedFilesInfo => {
412
+ const {
413
+ repos
414
+ } = changedFilesInfo;
415
+ // no SCM (git/hg/...) is found in any of the roots.
416
+ const noSCM = Object.values(repos).every(scm => scm.size === 0);
417
+ return !noSCM;
418
+ };
419
+ function normalizePosix(filePath) {
420
+ return filePath.replaceAll('\\', '/');
421
+ }
422
+ class SearchSource {
423
+ _context;
424
+ _dependencyResolver;
425
+ _testPathCases = [];
426
+ constructor(context) {
427
+ const {
428
+ config
429
+ } = context;
430
+ this._context = context;
431
+ this._dependencyResolver = null;
432
+ const rootPattern = new RegExp(config.roots.map(dir => (0, _jestRegexUtil().escapePathForRegex)(dir + path().sep)).join('|'));
433
+ this._testPathCases.push({
434
+ isMatch: path => rootPattern.test(path),
435
+ stat: 'roots'
436
+ });
437
+ if (config.testMatch.length > 0) {
438
+ this._testPathCases.push({
439
+ isMatch: (0, _jestUtil().globsToMatcher)(config.testMatch),
440
+ stat: 'testMatch'
441
+ });
442
+ }
443
+ if (config.testPathIgnorePatterns.length > 0) {
444
+ const testIgnorePatternsRegex = new RegExp(config.testPathIgnorePatterns.join('|'));
445
+ this._testPathCases.push({
446
+ isMatch: path => !testIgnorePatternsRegex.test(path),
447
+ stat: 'testPathIgnorePatterns'
448
+ });
449
+ }
450
+ if (config.testRegex.length > 0) {
451
+ this._testPathCases.push({
452
+ isMatch: regexToMatcher(config.testRegex),
453
+ stat: 'testRegex'
454
+ });
455
+ }
456
+ }
457
+ async _getOrBuildDependencyResolver() {
458
+ if (!this._dependencyResolver) {
459
+ this._dependencyResolver = new (_jestResolveDependencies().DependencyResolver)(this._context.resolver, this._context.hasteFS, await (0, _jestSnapshot().buildSnapshotResolver)(this._context.config));
460
+ }
461
+ return this._dependencyResolver;
462
+ }
463
+ _filterTestPathsWithStats(allPaths, testPathPatternsExecutor) {
464
+ const data = {
465
+ stats: {
466
+ roots: 0,
467
+ testMatch: 0,
468
+ testPathIgnorePatterns: 0,
469
+ testRegex: 0
470
+ },
471
+ tests: [],
472
+ total: allPaths.length
473
+ };
474
+ const testCases = [...this._testPathCases]; // clone
475
+ if (testPathPatternsExecutor.isSet()) {
476
+ testCases.push({
477
+ isMatch: path => testPathPatternsExecutor.isMatch(path),
478
+ stat: 'testPathPatterns'
479
+ });
480
+ data.stats.testPathPatterns = 0;
481
+ }
482
+ data.tests = allPaths.filter(test => {
483
+ let filterResult = true;
484
+ for (const {
485
+ isMatch,
486
+ stat
487
+ } of testCases) {
488
+ if (isMatch(test.path)) {
489
+ data.stats[stat]++;
490
+ } else {
491
+ filterResult = false;
492
+ }
493
+ }
494
+ return filterResult;
495
+ });
496
+ return data;
497
+ }
498
+ _getAllTestPaths(testPathPatternsExecutor) {
499
+ return this._filterTestPathsWithStats(toTests(this._context, this._context.hasteFS.getAllFiles()), testPathPatternsExecutor);
500
+ }
501
+ isTestFilePath(path) {
502
+ return this._testPathCases.every(testCase => testCase.isMatch(path));
503
+ }
504
+ findMatchingTests(testPathPatternsExecutor) {
505
+ return this._getAllTestPaths(testPathPatternsExecutor);
506
+ }
507
+ async findRelatedTests(allPaths, collectCoverage) {
508
+ const dependencyResolver = await this._getOrBuildDependencyResolver();
509
+ if (!collectCoverage) {
510
+ return {
511
+ tests: toTests(this._context, dependencyResolver.resolveInverse(allPaths, this.isTestFilePath.bind(this), {
512
+ skipNodeResolution: this._context.config.skipNodeResolution
513
+ }))
514
+ };
515
+ }
516
+ const testModulesMap = dependencyResolver.resolveInverseModuleMap(allPaths, this.isTestFilePath.bind(this), {
517
+ skipNodeResolution: this._context.config.skipNodeResolution
518
+ });
519
+ const allPathsAbsolute = new Set([...allPaths].map(p => path().resolve(p)));
520
+ const collectCoverageFrom = new Set();
521
+ for (const testModule of testModulesMap) {
522
+ if (!testModule.dependencies) {
523
+ continue;
524
+ }
525
+ for (const p of testModule.dependencies) {
526
+ if (!allPathsAbsolute.has(p)) {
527
+ continue;
528
+ }
529
+ const filename = (0, _jestConfig().replaceRootDirInPath)(this._context.config.rootDir, p);
530
+ collectCoverageFrom.add(path().isAbsolute(filename) ? path().relative(this._context.config.rootDir, filename) : filename);
531
+ }
532
+ }
533
+ return {
534
+ collectCoverageFrom,
535
+ tests: toTests(this._context, testModulesMap.map(testModule => testModule.file))
536
+ };
537
+ }
538
+ findTestsByPaths(paths) {
539
+ return {
540
+ tests: toTests(this._context, paths.map(p => path().resolve(this._context.config.cwd, p)).filter(this.isTestFilePath.bind(this)))
541
+ };
542
+ }
543
+ async findRelatedTestsFromPattern(paths, collectCoverage) {
544
+ if (Array.isArray(paths) && paths.length > 0) {
545
+ const resolvedPaths = paths.map(p => path().resolve(this._context.config.cwd, p));
546
+ return this.findRelatedTests(new Set(resolvedPaths), collectCoverage);
547
+ }
548
+ return {
549
+ tests: []
550
+ };
551
+ }
552
+ async findTestRelatedToChangedFiles(changedFilesInfo, collectCoverage) {
553
+ if (!hasSCM(changedFilesInfo)) {
554
+ return {
555
+ noSCM: true,
556
+ tests: []
557
+ };
558
+ }
559
+ const {
560
+ changedFiles
561
+ } = changedFilesInfo;
562
+ return this.findRelatedTests(changedFiles, collectCoverage);
563
+ }
564
+ async _getTestPaths(globalConfig, projectConfig, changedFiles) {
565
+ if (globalConfig.onlyChanged) {
566
+ if (!changedFiles) {
567
+ throw new Error('Changed files must be set when running with -o.');
568
+ }
569
+ return this.findTestRelatedToChangedFiles(changedFiles, globalConfig.collectCoverage);
570
+ }
571
+ let paths = globalConfig.nonFlagArgs;
572
+ if (globalConfig.findRelatedTests && 'win32' === os().platform()) {
573
+ paths = this.filterPathsWin32(paths);
574
+ }
575
+ if (globalConfig.runTestsByPath && paths && paths.length > 0) {
576
+ return this.findTestsByPaths(paths);
577
+ } else if (globalConfig.findRelatedTests && paths && paths.length > 0) {
578
+ return this.findRelatedTestsFromPattern(paths, globalConfig.collectCoverage);
579
+ } else {
580
+ return this.findMatchingTests(globalConfig.testPathPatterns.toExecutor({
581
+ rootDir: projectConfig.rootDir
582
+ }));
583
+ }
584
+ }
585
+ filterPathsWin32(paths) {
586
+ const allFiles = this._context.hasteFS.getAllFiles();
587
+ const options = {
588
+ nocase: true,
589
+ windows: false
590
+ };
591
+ paths = paths.map(p => {
592
+ // micromatch works with forward slashes: https://github.com/micromatch/micromatch#backslashes
593
+ const normalizedPath = normalizePosix(path().resolve(this._context.config.cwd, p));
594
+ const matcher = (0, _jestUtil().globsToMatcher)([normalizedPath], options);
595
+ return allFiles.map(normalizePosix).find(matcher);
596
+ }).filter(p => p !== undefined).map(p => path().resolve(p));
597
+ return paths;
598
+ }
599
+ async getTestPaths(globalConfig, projectConfig, changedFiles, filter) {
600
+ const searchResult = await this._getTestPaths(globalConfig, projectConfig, changedFiles);
601
+ const filterPath = globalConfig.filter;
602
+ if (filter) {
603
+ const tests = searchResult.tests;
604
+ const filterResult = await filter(tests.map(test => test.path));
605
+ if (!Array.isArray(filterResult.filtered)) {
606
+ throw new TypeError(`Filter ${filterPath} did not return a valid test list`);
607
+ }
608
+ const filteredSet = new Set(filterResult.filtered);
609
+ return {
610
+ ...searchResult,
611
+ tests: tests.filter(test => filteredSet.has(test.path))
612
+ };
613
+ }
614
+ return searchResult;
615
+ }
616
+ async findRelatedSourcesFromTestsInChangedFiles(changedFilesInfo) {
617
+ if (!hasSCM(changedFilesInfo)) {
618
+ return [];
619
+ }
620
+ const {
621
+ changedFiles
622
+ } = changedFilesInfo;
623
+ const dependencyResolver = await this._getOrBuildDependencyResolver();
624
+ const relatedSourcesSet = new Set();
625
+ for (const filePath of changedFiles) {
626
+ if (this.isTestFilePath(filePath)) {
627
+ const sourcePaths = dependencyResolver.resolve(filePath, {
628
+ skipNodeResolution: this._context.config.skipNodeResolution
629
+ });
630
+ for (const sourcePath of sourcePaths) relatedSourcesSet.add(sourcePath);
631
+ }
632
+ }
633
+ return [...relatedSourcesSet];
634
+ }
635
+ }
636
+ exports["default"] = SearchSource;
637
+
638
+ /***/ },
639
+
640
+ /***/ "./src/SnapshotInteractiveMode.ts"
641
+ (__unused_webpack_module, exports) {
642
+
643
+
644
+
645
+ Object.defineProperty(exports, "__esModule", ({
646
+ value: true
647
+ }));
648
+ exports["default"] = void 0;
649
+ function _ansiEscapes() {
650
+ const data = _interopRequireDefault(require("ansi-escapes"));
651
+ _ansiEscapes = function () {
652
+ return data;
653
+ };
654
+ return data;
655
+ }
656
+ function _chalk() {
657
+ const data = _interopRequireDefault(require("chalk"));
658
+ _chalk = function () {
659
+ return data;
660
+ };
661
+ return data;
662
+ }
663
+ function _jestUtil() {
664
+ const data = require("@pkg-nec/jest-util");
665
+ _jestUtil = function () {
666
+ return data;
667
+ };
668
+ return data;
669
+ }
670
+ function _jestWatcher() {
671
+ const data = require("@pkg-nec/jest-watcher");
672
+ _jestWatcher = function () {
673
+ return data;
674
+ };
675
+ return data;
676
+ }
677
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
678
+ /**
679
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
680
+ *
681
+ * This source code is licensed under the MIT license found in the
682
+ * LICENSE file in the root directory of this source tree.
683
+ */
684
+
685
+ const {
686
+ ARROW,
687
+ CLEAR
688
+ } = _jestUtil().specialChars;
689
+ class SnapshotInteractiveMode {
690
+ _pipe;
691
+ _isActive;
692
+ _updateTestRunnerConfig;
693
+ _testAssertions;
694
+ _countPaths;
695
+ _skippedNum;
696
+ constructor(pipe) {
697
+ this._pipe = pipe;
698
+ this._isActive = false;
699
+ this._skippedNum = 0;
700
+ }
701
+ isActive() {
702
+ return this._isActive;
703
+ }
704
+ getSkippedNum() {
705
+ return this._skippedNum;
706
+ }
707
+ _clearTestSummary() {
708
+ this._pipe.write(_ansiEscapes().default.cursorUp(6));
709
+ this._pipe.write(_ansiEscapes().default.eraseDown);
710
+ }
711
+ _drawUIProgress() {
712
+ this._clearTestSummary();
713
+ const numPass = this._countPaths - this._testAssertions.length;
714
+ const numRemaining = this._countPaths - numPass - this._skippedNum;
715
+ let stats = _chalk().default.bold.dim(`${(0, _jestUtil().pluralize)('snapshot', numRemaining)} remaining`);
716
+ if (numPass) {
717
+ stats += `, ${_chalk().default.bold.green(`${(0, _jestUtil().pluralize)('snapshot', numPass)} updated`)}`;
718
+ }
719
+ if (this._skippedNum) {
720
+ stats += `, ${_chalk().default.bold.yellow(`${(0, _jestUtil().pluralize)('snapshot', this._skippedNum)} skipped`)}`;
721
+ }
722
+ const messages = [`\n${_chalk().default.bold('Interactive Snapshot Progress')}`, ARROW + stats, `\n${_chalk().default.bold('Watch Usage')}`, `${_chalk().default.dim(`${ARROW}Press `)}u${_chalk().default.dim(' to update failing snapshots for this test.')}`, `${_chalk().default.dim(`${ARROW}Press `)}s${_chalk().default.dim(' to skip the current test.')}`, `${_chalk().default.dim(`${ARROW}Press `)}q${_chalk().default.dim(' to quit Interactive Snapshot Mode.')}`, `${_chalk().default.dim(`${ARROW}Press `)}Enter${_chalk().default.dim(' to trigger a test run.')}`];
723
+ this._pipe.write(`${messages.filter(Boolean).join('\n')}\n`);
724
+ }
725
+ _drawUIDoneWithSkipped() {
726
+ this._pipe.write(CLEAR);
727
+ const numPass = this._countPaths - this._testAssertions.length;
728
+ let stats = _chalk().default.bold.dim(`${(0, _jestUtil().pluralize)('snapshot', this._countPaths)} reviewed`);
729
+ if (numPass) {
730
+ stats += `, ${_chalk().default.bold.green(`${(0, _jestUtil().pluralize)('snapshot', numPass)} updated`)}`;
731
+ }
732
+ if (this._skippedNum) {
733
+ stats += `, ${_chalk().default.bold.yellow(`${(0, _jestUtil().pluralize)('snapshot', this._skippedNum)} skipped`)}`;
734
+ }
735
+ const messages = [`\n${_chalk().default.bold('Interactive Snapshot Result')}`, ARROW + stats, `\n${_chalk().default.bold('Watch Usage')}`, `${_chalk().default.dim(`${ARROW}Press `)}r${_chalk().default.dim(' to restart Interactive Snapshot Mode.')}`, `${_chalk().default.dim(`${ARROW}Press `)}q${_chalk().default.dim(' to quit Interactive Snapshot Mode.')}`];
736
+ this._pipe.write(`${messages.filter(Boolean).join('\n')}\n`);
737
+ }
738
+ _drawUIDone() {
739
+ this._pipe.write(CLEAR);
740
+ const numPass = this._countPaths - this._testAssertions.length;
741
+ let stats = _chalk().default.bold.dim(`${(0, _jestUtil().pluralize)('snapshot', this._countPaths)} reviewed`);
742
+ if (numPass) {
743
+ stats += `, ${_chalk().default.bold.green(`${(0, _jestUtil().pluralize)('snapshot', numPass)} updated`)}`;
744
+ }
745
+ const messages = [`\n${_chalk().default.bold('Interactive Snapshot Result')}`, ARROW + stats, `\n${_chalk().default.bold('Watch Usage')}`, `${_chalk().default.dim(`${ARROW}Press `)}Enter${_chalk().default.dim(' to return to watch mode.')}`];
746
+ this._pipe.write(`${messages.filter(Boolean).join('\n')}\n`);
747
+ }
748
+ _drawUIOverlay() {
749
+ if (this._testAssertions.length === 0) {
750
+ return this._drawUIDone();
751
+ }
752
+ if (this._testAssertions.length - this._skippedNum === 0) {
753
+ return this._drawUIDoneWithSkipped();
754
+ }
755
+ return this._drawUIProgress();
756
+ }
757
+ put(key) {
758
+ switch (key) {
759
+ case 's':
760
+ if (this._skippedNum === this._testAssertions.length) break;
761
+ this._skippedNum += 1;
762
+
763
+ // move skipped test to the end
764
+ this._testAssertions.push(this._testAssertions.shift());
765
+ if (this._testAssertions.length - this._skippedNum > 0) {
766
+ this._run(false);
767
+ } else {
768
+ this._drawUIDoneWithSkipped();
769
+ }
770
+ break;
771
+ case 'u':
772
+ this._run(true);
773
+ break;
774
+ case 'q':
775
+ case _jestWatcher().KEYS.ESCAPE:
776
+ this.abort();
777
+ break;
778
+ case 'r':
779
+ this.restart();
780
+ break;
781
+ case _jestWatcher().KEYS.ENTER:
782
+ if (this._testAssertions.length === 0) {
783
+ this.abort();
784
+ } else {
785
+ this._run(false);
786
+ }
787
+ break;
788
+ default:
789
+ break;
790
+ }
791
+ }
792
+ abort() {
793
+ this._isActive = false;
794
+ this._skippedNum = 0;
795
+ this._updateTestRunnerConfig(null, false);
796
+ }
797
+ restart() {
798
+ this._skippedNum = 0;
799
+ this._countPaths = this._testAssertions.length;
800
+ this._run(false);
801
+ }
802
+ updateWithResults(results) {
803
+ const hasSnapshotFailure = !!results.snapshot.failure;
804
+ if (hasSnapshotFailure) {
805
+ this._drawUIOverlay();
806
+ return;
807
+ }
808
+ this._testAssertions.shift();
809
+ if (this._testAssertions.length - this._skippedNum === 0) {
810
+ this._drawUIOverlay();
811
+ return;
812
+ }
813
+
814
+ // Go to the next test
815
+ this._run(false);
816
+ }
817
+ _run(shouldUpdateSnapshot) {
818
+ const testAssertion = this._testAssertions[0];
819
+ this._updateTestRunnerConfig(testAssertion, shouldUpdateSnapshot);
820
+ }
821
+ run(failedSnapshotTestAssertions, onConfigChange) {
822
+ if (failedSnapshotTestAssertions.length === 0) {
823
+ return;
824
+ }
825
+ this._testAssertions = [...failedSnapshotTestAssertions];
826
+ this._countPaths = this._testAssertions.length;
827
+ this._updateTestRunnerConfig = onConfigChange;
828
+ this._isActive = true;
829
+ this._run(false);
830
+ }
831
+ }
832
+ exports["default"] = SnapshotInteractiveMode;
833
+
834
+ /***/ },
835
+
836
+ /***/ "./src/TestNamePatternPrompt.ts"
837
+ (__unused_webpack_module, exports) {
838
+
839
+
840
+
841
+ Object.defineProperty(exports, "__esModule", ({
842
+ value: true
843
+ }));
844
+ exports["default"] = void 0;
845
+ function _jestWatcher() {
846
+ const data = require("@pkg-nec/jest-watcher");
847
+ _jestWatcher = function () {
848
+ return data;
849
+ };
850
+ return data;
851
+ }
852
+ /**
853
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
854
+ *
855
+ * This source code is licensed under the MIT license found in the
856
+ * LICENSE file in the root directory of this source tree.
857
+ */
858
+
859
+ class TestNamePatternPrompt extends _jestWatcher().PatternPrompt {
860
+ constructor(pipe, prompt) {
861
+ super(pipe, prompt, 'tests');
862
+ }
863
+ _onChange(pattern, options) {
864
+ super._onChange(pattern, options);
865
+ this._printPrompt(pattern);
866
+ }
867
+ _printPrompt(pattern) {
868
+ const pipe = this._pipe;
869
+ (0, _jestWatcher().printPatternCaret)(pattern, pipe);
870
+ (0, _jestWatcher().printRestoredPatternCaret)(pattern, this._currentUsageRows, pipe);
871
+ }
872
+ }
873
+ exports["default"] = TestNamePatternPrompt;
874
+
875
+ /***/ },
876
+
877
+ /***/ "./src/TestPathPatternPrompt.ts"
878
+ (__unused_webpack_module, exports) {
879
+
880
+
881
+
882
+ Object.defineProperty(exports, "__esModule", ({
883
+ value: true
884
+ }));
885
+ exports["default"] = void 0;
886
+ function _jestWatcher() {
887
+ const data = require("@pkg-nec/jest-watcher");
888
+ _jestWatcher = function () {
889
+ return data;
890
+ };
891
+ return data;
892
+ }
893
+ /**
894
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
895
+ *
896
+ * This source code is licensed under the MIT license found in the
897
+ * LICENSE file in the root directory of this source tree.
898
+ */
899
+
900
+ class TestPathPatternPrompt extends _jestWatcher().PatternPrompt {
901
+ constructor(pipe, prompt) {
902
+ super(pipe, prompt, 'filenames');
903
+ }
904
+ _onChange(pattern, options) {
905
+ super._onChange(pattern, options);
906
+ this._printPrompt(pattern);
907
+ }
908
+ _printPrompt(pattern) {
909
+ const pipe = this._pipe;
910
+ (0, _jestWatcher().printPatternCaret)(pattern, pipe);
911
+ (0, _jestWatcher().printRestoredPatternCaret)(pattern, this._currentUsageRows, pipe);
912
+ }
913
+ }
914
+ exports["default"] = TestPathPatternPrompt;
915
+
916
+ /***/ },
917
+
918
+ /***/ "./src/TestScheduler.ts"
919
+ (__unused_webpack_module, exports, __webpack_require__) {
920
+
921
+
922
+
923
+ Object.defineProperty(exports, "__esModule", ({
924
+ value: true
925
+ }));
926
+ exports.createTestScheduler = createTestScheduler;
927
+ function _chalk() {
928
+ const data = _interopRequireDefault(require("chalk"));
929
+ _chalk = function () {
930
+ return data;
931
+ };
932
+ return data;
933
+ }
934
+ function _ciInfo() {
935
+ const data = require("ci-info");
936
+ _ciInfo = function () {
937
+ return data;
938
+ };
939
+ return data;
940
+ }
941
+ function _exitX() {
942
+ const data = _interopRequireDefault(require("exit-x"));
943
+ _exitX = function () {
944
+ return data;
945
+ };
946
+ return data;
947
+ }
948
+ function _fastJsonStableStringify() {
949
+ const data = _interopRequireDefault(require("fast-json-stable-stringify"));
950
+ _fastJsonStableStringify = function () {
951
+ return data;
952
+ };
953
+ return data;
954
+ }
955
+ function _jestMessageUtil() {
956
+ const data = require("@pkg-nec/jest-message-util");
957
+ _jestMessageUtil = function () {
958
+ return data;
959
+ };
960
+ return data;
961
+ }
962
+ function _jestReporters() {
963
+ const data = require("@pkg-nec/jest-reporters");
964
+ _jestReporters = function () {
965
+ return data;
966
+ };
967
+ return data;
968
+ }
969
+ function _jestSnapshot() {
970
+ const data = require("@pkg-nec/jest-snapshot");
971
+ _jestSnapshot = function () {
972
+ return data;
973
+ };
974
+ return data;
975
+ }
976
+ function _jestTestResult() {
977
+ const data = require("@pkg-nec/jest-test-result");
978
+ _jestTestResult = function () {
979
+ return data;
980
+ };
981
+ return data;
982
+ }
983
+ function _jestTransform() {
984
+ const data = require("@pkg-nec/jest-transform");
985
+ _jestTransform = function () {
986
+ return data;
987
+ };
988
+ return data;
989
+ }
990
+ function _jestUtil() {
991
+ const data = require("@pkg-nec/jest-util");
992
+ _jestUtil = function () {
993
+ return data;
994
+ };
995
+ return data;
996
+ }
997
+ var _ReporterDispatcher = _interopRequireDefault(__webpack_require__("./src/ReporterDispatcher.ts"));
998
+ var _runGlobalHook = _interopRequireDefault(__webpack_require__("./src/runGlobalHook.ts"));
999
+ var _testSchedulerHelper = __webpack_require__("./src/testSchedulerHelper.ts");
1000
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1001
+ /**
1002
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1003
+ *
1004
+ * This source code is licensed under the MIT license found in the
1005
+ * LICENSE file in the root directory of this source tree.
1006
+ */
1007
+
1008
+ // Env vars that indicate the process is running inside an AI coding agent.
1009
+ // Based on the detection logic from the std-env package.
1010
+ const AGENT_ENV_VARS = ['AI_AGENT', 'AUGMENT_AGENT', 'CLAUDE_CODE', 'CLAUDECODE', 'CODEX_SANDBOX', 'CODEX_THREAD_ID', 'CURSOR_AGENT', 'GEMINI_CLI', 'GOOSE_PROVIDER', 'OPENCODE', 'REPL_ID'];
1011
+ function detectAgent() {
1012
+ return AGENT_ENV_VARS.some(key => key in process.env && process.env[key] !== '');
1013
+ }
1014
+ async function createTestScheduler(globalConfig, context) {
1015
+ return new TestScheduler(globalConfig, context);
1016
+ }
1017
+ class TestScheduler {
1018
+ _context;
1019
+ _dispatcher;
1020
+ _globalConfig;
1021
+ constructor(globalConfig, context) {
1022
+ this._context = context;
1023
+ this._dispatcher = new _ReporterDispatcher.default();
1024
+ this._globalConfig = globalConfig;
1025
+ }
1026
+ addReporter(reporter) {
1027
+ this._dispatcher.register(reporter);
1028
+ }
1029
+ removeReporter(reporterConstructor) {
1030
+ this._dispatcher.unregister(reporterConstructor);
1031
+ }
1032
+ async scheduleTests(tests, watcher) {
1033
+ await this._setupReporters(tests);
1034
+ const onTestFileStart = this._dispatcher.onTestFileStart.bind(this._dispatcher);
1035
+ const timings = [];
1036
+ const testContexts = new Set();
1037
+ for (const test of tests) {
1038
+ testContexts.add(test.context);
1039
+ if (test.duration) {
1040
+ timings.push(test.duration);
1041
+ }
1042
+ }
1043
+ const aggregatedResults = createAggregatedResults(tests.length);
1044
+ const estimatedTime = Math.ceil(getEstimatedTime(timings, this._globalConfig.maxWorkers) / 1000);
1045
+ const runInBand = (0, _testSchedulerHelper.shouldRunInBand)(tests, timings, this._globalConfig);
1046
+ const onResult = async (test, testResult) => {
1047
+ if (watcher.isInterrupted()) {
1048
+ return;
1049
+ }
1050
+ if (testResult.testResults.length === 0) {
1051
+ const message = 'Your test suite must contain at least one test.';
1052
+ return onFailure(test, {
1053
+ message,
1054
+ stack: new Error(message).stack
1055
+ });
1056
+ }
1057
+
1058
+ // Throws when the context is leaked after executing a test.
1059
+ if (testResult.leaks) {
1060
+ const message = `${_chalk().default.red.bold('EXPERIMENTAL FEATURE!\n')}Your test suite is leaking memory. Please ensure all references are cleaned.\n` + '\n' + 'There is a number of things that can leak memory:\n' + ' - Async operations that have not finished (e.g. fs.readFile).\n' + ' - Timers not properly mocked (e.g. setInterval, setTimeout).\n' + ' - Keeping references to the global scope.';
1061
+ return onFailure(test, {
1062
+ message,
1063
+ stack: new Error(message).stack
1064
+ });
1065
+ }
1066
+ (0, _jestTestResult().addResult)(aggregatedResults, testResult);
1067
+ await this._dispatcher.onTestFileResult(test, testResult, aggregatedResults);
1068
+ return this._bailIfNeeded(testContexts, aggregatedResults, watcher, tests);
1069
+ };
1070
+ const onFailure = async (test, error) => {
1071
+ if (watcher.isInterrupted()) {
1072
+ return;
1073
+ }
1074
+ const testResult = (0, _jestTestResult().buildFailureTestResult)(test.path, error);
1075
+ testResult.failureMessage = (0, _jestMessageUtil().formatExecError)(testResult.testExecError, test.context.config, this._globalConfig, test.path);
1076
+ (0, _jestTestResult().addResult)(aggregatedResults, testResult);
1077
+ await this._dispatcher.onTestFileResult(test, testResult, aggregatedResults);
1078
+ };
1079
+ const updateSnapshotState = async () => {
1080
+ const contextsWithSnapshotResolvers = await Promise.all([...testContexts].map(async context => [context, await (0, _jestSnapshot().buildSnapshotResolver)(context.config)]));
1081
+ for (const [context, snapshotResolver] of contextsWithSnapshotResolvers) {
1082
+ const status = (0, _jestSnapshot().cleanup)(context.hasteFS, this._globalConfig.updateSnapshot, snapshotResolver, context.config.testPathIgnorePatterns);
1083
+ aggregatedResults.snapshot.filesRemoved += status.filesRemoved;
1084
+ aggregatedResults.snapshot.filesRemovedList = [...(aggregatedResults.snapshot.filesRemovedList || []), ...status.filesRemovedList];
1085
+ }
1086
+ const updateAll = this._globalConfig.updateSnapshot === 'all';
1087
+ aggregatedResults.snapshot.didUpdate = updateAll;
1088
+ aggregatedResults.snapshot.failure = !!(!updateAll && (aggregatedResults.snapshot.unchecked || aggregatedResults.snapshot.unmatched || aggregatedResults.snapshot.filesRemoved));
1089
+ };
1090
+ await this._dispatcher.onRunStart(aggregatedResults, {
1091
+ estimatedTime,
1092
+ showStatus: !runInBand
1093
+ });
1094
+ const testRunners = Object.create(null);
1095
+ const contextsByTestRunner = new WeakMap();
1096
+ try {
1097
+ await Promise.all([...testContexts].map(async context => {
1098
+ const {
1099
+ config
1100
+ } = context;
1101
+ const runnerKey = `${config.runner}\0${stableRunnerOptionsKey(config.runnerOptions)}`;
1102
+ if (!testRunners[runnerKey]) {
1103
+ const transformer = await (0, _jestTransform().createScriptTransformer)(config);
1104
+ const Runner = await transformer.requireAndTranspileModule(config.runner);
1105
+ const runner = new Runner(this._globalConfig, {
1106
+ changedFiles: this._context.changedFiles,
1107
+ sourcesRelatedToTestsInChangedFiles: this._context.sourcesRelatedToTestsInChangedFiles
1108
+ }, config.runnerOptions);
1109
+ testRunners[runnerKey] = runner;
1110
+ contextsByTestRunner.set(runner, context);
1111
+ }
1112
+ }));
1113
+ const testsByRunner = this._partitionTests(testRunners, tests);
1114
+ if (testsByRunner) {
1115
+ try {
1116
+ for (const runner of Object.keys(testRunners)) {
1117
+ const testRunner = testRunners[runner];
1118
+ const context = contextsByTestRunner.get(testRunner);
1119
+ (0, _jestUtil().invariant)(context);
1120
+ const tests = testsByRunner[runner];
1121
+ const testRunnerOptions = {
1122
+ serial: runInBand || Boolean(testRunner.isSerial)
1123
+ };
1124
+ if (testRunner.supportsEventEmitters) {
1125
+ const unsubscribes = [testRunner.on('test-file-start', ([test]) => onTestFileStart(test)), testRunner.on('test-file-success', ([test, testResult]) => onResult(test, testResult)), testRunner.on('test-file-failure', ([test, error]) => onFailure(test, error)), testRunner.on('test-case-start', ([testPath, testCaseStartInfo]) => {
1126
+ const test = {
1127
+ context,
1128
+ path: testPath
1129
+ };
1130
+ this._dispatcher.onTestCaseStart(test, testCaseStartInfo);
1131
+ }), testRunner.on('test-case-result', ([testPath, testCaseResult]) => {
1132
+ const test = {
1133
+ context,
1134
+ path: testPath
1135
+ };
1136
+ this._dispatcher.onTestCaseResult(test, testCaseResult);
1137
+ })];
1138
+ await testRunner.runTests(tests, watcher, testRunnerOptions);
1139
+ for (const sub of unsubscribes) sub();
1140
+ } else {
1141
+ await testRunner.runTests(tests, watcher, onTestFileStart, onResult, onFailure, testRunnerOptions);
1142
+ }
1143
+ }
1144
+ } catch (error) {
1145
+ if (!watcher.isInterrupted()) {
1146
+ throw error;
1147
+ }
1148
+ }
1149
+ }
1150
+ } catch (error) {
1151
+ aggregatedResults.runExecError = buildExecError(error);
1152
+ await this._dispatcher.onRunComplete(testContexts, aggregatedResults);
1153
+ throw error;
1154
+ }
1155
+ await updateSnapshotState();
1156
+ aggregatedResults.wasInterrupted = watcher.isInterrupted();
1157
+ await this._dispatcher.onRunComplete(testContexts, aggregatedResults);
1158
+ const anyTestFailures = !(aggregatedResults.numFailedTests === 0 && aggregatedResults.numRuntimeErrorTestSuites === 0);
1159
+ const anyReporterErrors = this._dispatcher.hasErrors();
1160
+ aggregatedResults.success = !(anyTestFailures || aggregatedResults.snapshot.failure || anyReporterErrors);
1161
+ return aggregatedResults;
1162
+ }
1163
+ _partitionTests(testRunners, tests) {
1164
+ if (Object.keys(testRunners).length > 1) {
1165
+ return tests.reduce((testRuns, test) => {
1166
+ const {
1167
+ config
1168
+ } = test.context;
1169
+ const runnerKey = `${config.runner}\0${stableRunnerOptionsKey(config.runnerOptions)}`;
1170
+ if (!testRuns[runnerKey]) {
1171
+ testRuns[runnerKey] = [];
1172
+ }
1173
+ testRuns[runnerKey].push(test);
1174
+ return testRuns;
1175
+ }, Object.create(null));
1176
+ } else if (tests.length > 0 && tests[0] != null) {
1177
+ // If there is only one runner, don't partition the tests.
1178
+ const {
1179
+ config
1180
+ } = tests[0].context;
1181
+ const runnerKey = `${config.runner}\0${stableRunnerOptionsKey(config.runnerOptions)}`;
1182
+ return Object.assign(Object.create(null), {
1183
+ [runnerKey]: tests
1184
+ });
1185
+ } else {
1186
+ return null;
1187
+ }
1188
+ }
1189
+ async _setupReporters(tests) {
1190
+ const {
1191
+ collectCoverage: coverage,
1192
+ notify
1193
+ } = this._globalConfig;
1194
+ const verbose = this._globalConfig.verbose || tests.some(t => t.context.config.verbose);
1195
+ const reporters = this._globalConfig.reporters || [[detectAgent() ? 'agent' : 'default', {}]];
1196
+ let summaryOptions = null;
1197
+ for (const [reporter, options] of reporters) {
1198
+ switch (reporter) {
1199
+ case 'agent':
1200
+ summaryOptions = options;
1201
+ this.addReporter(new (_jestReporters().AgentReporter)(this._globalConfig));
1202
+ break;
1203
+ case 'default':
1204
+ summaryOptions = options;
1205
+ this.addReporter(verbose ? new (_jestReporters().VerboseReporter)(this._globalConfig) : new (_jestReporters().DefaultReporter)(this._globalConfig));
1206
+ break;
1207
+ case 'github-actions':
1208
+ if (_ciInfo().GITHUB_ACTIONS) {
1209
+ this.addReporter(new (_jestReporters().GitHubActionsReporter)(this._globalConfig, options));
1210
+ }
1211
+ break;
1212
+ case 'summary':
1213
+ summaryOptions = options;
1214
+ break;
1215
+ default:
1216
+ await this._addCustomReporter(reporter, options);
1217
+ }
1218
+ }
1219
+ if (notify) {
1220
+ this.addReporter(new (_jestReporters().NotifyReporter)(this._globalConfig, this._context));
1221
+ }
1222
+ if (coverage) {
1223
+ this.addReporter(new (_jestReporters().CoverageReporter)(this._globalConfig, this._context));
1224
+ }
1225
+ if (summaryOptions != null) {
1226
+ this.addReporter(new (_jestReporters().SummaryReporter)(this._globalConfig, summaryOptions));
1227
+ }
1228
+ }
1229
+ async _addCustomReporter(reporter, options) {
1230
+ try {
1231
+ const Reporter = await (0, _jestUtil().requireOrImportModule)(reporter);
1232
+ this.addReporter(new Reporter(this._globalConfig, options, this._context));
1233
+ } catch (error) {
1234
+ error.message = `An error occurred while adding the reporter at path "${_chalk().default.bold(reporter)}".\n${error instanceof Error ? error.message : ''}`;
1235
+ throw error;
1236
+ }
1237
+ }
1238
+ async _bailIfNeeded(testContexts, aggregatedResults, watcher, allTests) {
1239
+ if (this._globalConfig.bail !== 0 && aggregatedResults.numFailedTests >= this._globalConfig.bail) {
1240
+ if (watcher.isWatchMode()) {
1241
+ await watcher.setState({
1242
+ interrupted: true
1243
+ });
1244
+ return;
1245
+ }
1246
+ try {
1247
+ await this._dispatcher.onRunComplete(testContexts, aggregatedResults);
1248
+ } finally {
1249
+ // Perform global teardown if client configures `bail`
1250
+ if (allTests.length > 0) {
1251
+ performance.mark('jest/globalTeardown:start');
1252
+ await (0, _runGlobalHook.default)({
1253
+ allTests,
1254
+ globalConfig: this._globalConfig,
1255
+ moduleName: 'globalTeardown'
1256
+ });
1257
+ performance.mark('jest/globalTeardown:end');
1258
+ (0, _exitX().default)(this._globalConfig.testFailureExitCode);
1259
+ }
1260
+ }
1261
+ }
1262
+ }
1263
+ }
1264
+ const createAggregatedResults = numTotalTestSuites => {
1265
+ const result = (0, _jestTestResult().makeEmptyAggregatedTestResult)();
1266
+ result.numTotalTestSuites = numTotalTestSuites;
1267
+ result.startTime = Date.now();
1268
+ result.success = false;
1269
+ return result;
1270
+ };
1271
+ const getEstimatedTime = (timings, workers) => {
1272
+ if (timings.length === 0) {
1273
+ return 0;
1274
+ }
1275
+ const max = Math.max(...timings);
1276
+ return timings.length <= workers ? max : Math.max(timings.reduce((sum, time) => sum + time) / workers, max);
1277
+ };
1278
+ const strToError = errString => {
1279
+ const {
1280
+ message,
1281
+ stack
1282
+ } = (0, _jestMessageUtil().separateMessageFromStack)(errString);
1283
+ if (stack.length > 0) {
1284
+ return {
1285
+ message,
1286
+ stack
1287
+ };
1288
+ }
1289
+ const error = new (_jestUtil().ErrorWithStack)(message, buildExecError);
1290
+ return {
1291
+ message,
1292
+ stack: error.stack || ''
1293
+ };
1294
+ };
1295
+ const buildExecError = err => {
1296
+ if (typeof err === 'string' || err == null) {
1297
+ return strToError(err || 'Error');
1298
+ }
1299
+ const anyErr = err;
1300
+ if (typeof anyErr.message === 'string') {
1301
+ if (typeof anyErr.stack === 'string' && anyErr.stack.length > 0) {
1302
+ return anyErr;
1303
+ }
1304
+ return strToError(anyErr.message);
1305
+ }
1306
+ return strToError(JSON.stringify(err));
1307
+ };
1308
+ function stableRunnerOptionsKey(options) {
1309
+ if (options == null || Object.keys(options).length === 0) return '{}';
1310
+ return (0, _fastJsonStableStringify().default)(options);
1311
+ }
1312
+
1313
+ /***/ },
1314
+
1315
+ /***/ "./src/cli/index.ts"
1316
+ (__unused_webpack_module, exports, __webpack_require__) {
1317
+
1318
+
1319
+
1320
+ Object.defineProperty(exports, "__esModule", ({
1321
+ value: true
1322
+ }));
1323
+ exports.runCLI = runCLI;
1324
+ function _nodePerf_hooks() {
1325
+ const data = require("node:perf_hooks");
1326
+ _nodePerf_hooks = function () {
1327
+ return data;
1328
+ };
1329
+ return data;
1330
+ }
1331
+ function _chalk() {
1332
+ const data = _interopRequireDefault(require("chalk"));
1333
+ _chalk = function () {
1334
+ return data;
1335
+ };
1336
+ return data;
1337
+ }
1338
+ function _exitX() {
1339
+ const data = _interopRequireDefault(require("exit-x"));
1340
+ _exitX = function () {
1341
+ return data;
1342
+ };
1343
+ return data;
1344
+ }
1345
+ function fs() {
1346
+ const data = _interopRequireWildcard(require("graceful-fs"));
1347
+ fs = function () {
1348
+ return data;
1349
+ };
1350
+ return data;
1351
+ }
1352
+ function _jestConfig() {
1353
+ const data = require("@pkg-nec/jest-config");
1354
+ _jestConfig = function () {
1355
+ return data;
1356
+ };
1357
+ return data;
1358
+ }
1359
+ function _jestConsole() {
1360
+ const data = require("@pkg-nec/jest-console");
1361
+ _jestConsole = function () {
1362
+ return data;
1363
+ };
1364
+ return data;
1365
+ }
1366
+ function _jestRuntime() {
1367
+ const data = _interopRequireDefault(require("@pkg-nec/jest-runtime"));
1368
+ _jestRuntime = function () {
1369
+ return data;
1370
+ };
1371
+ return data;
1372
+ }
1373
+ function _jestUtil() {
1374
+ const data = require("@pkg-nec/jest-util");
1375
+ _jestUtil = function () {
1376
+ return data;
1377
+ };
1378
+ return data;
1379
+ }
1380
+ function _jestWatcher() {
1381
+ const data = require("@pkg-nec/jest-watcher");
1382
+ _jestWatcher = function () {
1383
+ return data;
1384
+ };
1385
+ return data;
1386
+ }
1387
+ var _collectHandles = __webpack_require__("./src/collectHandles.ts");
1388
+ var _getChangedFilesPromise = _interopRequireDefault(__webpack_require__("./src/getChangedFilesPromise.ts"));
1389
+ var _getConfigsOfProjectsToRun = _interopRequireDefault(__webpack_require__("./src/getConfigsOfProjectsToRun.ts"));
1390
+ var _getProjectNamesMissingWarning = _interopRequireDefault(__webpack_require__("./src/getProjectNamesMissingWarning.ts"));
1391
+ var _getSelectProjectsMessage = _interopRequireDefault(__webpack_require__("./src/getSelectProjectsMessage.ts"));
1392
+ var _createContext = _interopRequireDefault(__webpack_require__("./src/lib/createContext.ts"));
1393
+ var _handleDeprecationWarnings = _interopRequireDefault(__webpack_require__("./src/lib/handleDeprecationWarnings.ts"));
1394
+ var _logDebugMessages = _interopRequireDefault(__webpack_require__("./src/lib/logDebugMessages.ts"));
1395
+ var _runJest = _interopRequireDefault(__webpack_require__("./src/runJest.ts"));
1396
+ var _watch = _interopRequireDefault(__webpack_require__("./src/watch.ts"));
1397
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
1398
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1399
+ /**
1400
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1401
+ *
1402
+ * This source code is licensed under the MIT license found in the
1403
+ * LICENSE file in the root directory of this source tree.
1404
+ */
1405
+
1406
+ const {
1407
+ print: preRunMessagePrint
1408
+ } = _jestUtil().preRunMessage;
1409
+ async function runCLI(argv, projects) {
1410
+ _nodePerf_hooks().performance.mark('jest/runCLI:start');
1411
+ let results;
1412
+
1413
+ // If we output a JSON object, we can't write anything to stdout, since
1414
+ // it'll break the JSON structure and it won't be valid.
1415
+ const outputStream = argv.json || argv.useStderr ? process.stderr : process.stdout;
1416
+ const {
1417
+ globalConfig,
1418
+ configs,
1419
+ hasDeprecationWarnings
1420
+ } = await (0, _jestConfig().readConfigs)(argv, projects);
1421
+ if (argv.debug) {
1422
+ (0, _logDebugMessages.default)(globalConfig, configs, outputStream);
1423
+ }
1424
+ if (argv.showConfig) {
1425
+ (0, _logDebugMessages.default)(globalConfig, configs, process.stdout);
1426
+ (0, _exitX().default)(0);
1427
+ }
1428
+ if (argv.clearCache) {
1429
+ // stick in a Set to dedupe the deletions
1430
+ const uniqueConfigDirectories = new Set(configs.map(config => config.cacheDirectory));
1431
+ for (const cacheDirectory of uniqueConfigDirectories) {
1432
+ fs().rmSync(cacheDirectory, {
1433
+ force: true,
1434
+ recursive: true
1435
+ });
1436
+ process.stdout.write(`Cleared ${cacheDirectory}\n`);
1437
+ }
1438
+ (0, _exitX().default)(0);
1439
+ }
1440
+ const configsOfProjectsToRun = (0, _getConfigsOfProjectsToRun.default)(configs, {
1441
+ ignoreProjects: argv.ignoreProjects,
1442
+ selectProjects: argv.selectProjects
1443
+ });
1444
+ if (argv.selectProjects || argv.ignoreProjects) {
1445
+ const namesMissingWarning = (0, _getProjectNamesMissingWarning.default)(configs, {
1446
+ ignoreProjects: argv.ignoreProjects,
1447
+ selectProjects: argv.selectProjects
1448
+ });
1449
+ if (namesMissingWarning) {
1450
+ outputStream.write(namesMissingWarning);
1451
+ }
1452
+ outputStream.write((0, _getSelectProjectsMessage.default)(configsOfProjectsToRun, {
1453
+ ignoreProjects: argv.ignoreProjects,
1454
+ selectProjects: argv.selectProjects
1455
+ }));
1456
+ }
1457
+ await _run10000(globalConfig, configsOfProjectsToRun, hasDeprecationWarnings, outputStream, r => {
1458
+ results = r;
1459
+ });
1460
+ if (argv.watch || argv.watchAll) {
1461
+ // If in watch mode, return the promise that will never resolve.
1462
+ // If the watch mode is interrupted, watch should handle the process
1463
+ // shutdown.
1464
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
1465
+ return new Promise(() => {});
1466
+ }
1467
+ if (!results) {
1468
+ throw new Error('AggregatedResult must be present after test run is complete');
1469
+ }
1470
+ const {
1471
+ openHandles
1472
+ } = results;
1473
+ if (openHandles && openHandles.length > 0) {
1474
+ const formatted = (0, _collectHandles.formatHandleErrors)(openHandles, configs[0]);
1475
+ const openHandlesString = (0, _jestUtil().pluralize)('open handle', formatted.length, 's');
1476
+ const message = _chalk().default.red(`\nJest has detected the following ${openHandlesString} potentially keeping Jest from exiting:\n\n`) + formatted.join('\n\n');
1477
+ console.error(message);
1478
+ }
1479
+ _nodePerf_hooks().performance.mark('jest/runCLI:end');
1480
+ return {
1481
+ globalConfig,
1482
+ results
1483
+ };
1484
+ }
1485
+ const buildContextsAndHasteMaps = async (configs, globalConfig, outputStream) => {
1486
+ const hasteMapInstances = Array.from({
1487
+ length: configs.length
1488
+ });
1489
+ const contexts = await Promise.all(configs.map(async (config, index) => {
1490
+ (0, _jestUtil().createDirectory)(config.cacheDirectory);
1491
+ const hasteMapInstance = await _jestRuntime().default.createHasteMap(config, {
1492
+ console: new (_jestConsole().CustomConsole)(outputStream, outputStream),
1493
+ maxWorkers: Math.max(1, Math.floor(globalConfig.maxWorkers / configs.length)),
1494
+ resetCache: !config.cache,
1495
+ watch: globalConfig.watch || globalConfig.watchAll,
1496
+ watchman: globalConfig.watchman,
1497
+ workerThreads: globalConfig.workerThreads
1498
+ });
1499
+ hasteMapInstances[index] = hasteMapInstance;
1500
+ return (0, _createContext.default)(config, await hasteMapInstance.build());
1501
+ }));
1502
+ return {
1503
+ contexts,
1504
+ hasteMapInstances
1505
+ };
1506
+ };
1507
+ const _run10000 = async (globalConfig, configs, hasDeprecationWarnings, outputStream, onComplete) => {
1508
+ // Queries to hg/git can take a while, so we need to start the process
1509
+ // as soon as possible, so by the time we need the result it's already there.
1510
+ const changedFilesPromise = (0, _getChangedFilesPromise.default)(globalConfig, configs);
1511
+ if (changedFilesPromise) {
1512
+ _nodePerf_hooks().performance.mark('jest/getChangedFiles:start');
1513
+ changedFilesPromise.finally(() => {
1514
+ _nodePerf_hooks().performance.mark('jest/getChangedFiles:end');
1515
+ });
1516
+ }
1517
+
1518
+ // Filter may need to do an HTTP call or something similar to setup.
1519
+ // We will wait on an async response from this before using the filter.
1520
+ let filter;
1521
+ if (globalConfig.filter && !globalConfig.skipFilter) {
1522
+ const rawFilter = require(globalConfig.filter);
1523
+ let filterSetupPromise;
1524
+ if (rawFilter.setup) {
1525
+ // Wrap filter setup Promise to avoid "uncaught Promise" error.
1526
+ // If an error is returned, we surface it in the return value.
1527
+ filterSetupPromise = (async () => {
1528
+ try {
1529
+ await rawFilter.setup();
1530
+ } catch (error) {
1531
+ return error;
1532
+ }
1533
+ return undefined;
1534
+ })();
1535
+ }
1536
+ filter = async testPaths => {
1537
+ if (filterSetupPromise) {
1538
+ // Expect an undefined return value unless there was an error.
1539
+ const err = await filterSetupPromise;
1540
+ if (err) {
1541
+ throw err;
1542
+ }
1543
+ }
1544
+ return rawFilter(testPaths);
1545
+ };
1546
+ }
1547
+ _nodePerf_hooks().performance.mark('jest/buildContextsAndHasteMaps:start');
1548
+ const {
1549
+ contexts,
1550
+ hasteMapInstances
1551
+ } = await buildContextsAndHasteMaps(configs, globalConfig, outputStream);
1552
+ _nodePerf_hooks().performance.mark('jest/buildContextsAndHasteMaps:end');
1553
+ if (globalConfig.watch || globalConfig.watchAll) {
1554
+ await runWatch(contexts, configs, hasDeprecationWarnings, globalConfig, outputStream, hasteMapInstances, filter);
1555
+ } else {
1556
+ await runWithoutWatch(globalConfig, contexts, outputStream, onComplete, changedFilesPromise, filter);
1557
+ }
1558
+ };
1559
+ const runWatch = async (contexts, _configs, hasDeprecationWarnings, globalConfig, outputStream, hasteMapInstances, filter) => {
1560
+ if (hasDeprecationWarnings) {
1561
+ try {
1562
+ await (0, _handleDeprecationWarnings.default)(outputStream, process.stdin);
1563
+ return await (0, _watch.default)(globalConfig, contexts, outputStream, hasteMapInstances, undefined, undefined, filter);
1564
+ } catch {
1565
+ (0, _exitX().default)(0);
1566
+ }
1567
+ }
1568
+ return (0, _watch.default)(globalConfig, contexts, outputStream, hasteMapInstances, undefined, undefined, filter);
1569
+ };
1570
+ const runWithoutWatch = async (globalConfig, contexts, outputStream, onComplete, changedFilesPromise, filter) => {
1571
+ const startRun = async () => {
1572
+ if (!globalConfig.listTests) {
1573
+ preRunMessagePrint(outputStream);
1574
+ }
1575
+ return (0, _runJest.default)({
1576
+ changedFilesPromise,
1577
+ contexts,
1578
+ failedTestsCache: undefined,
1579
+ filter,
1580
+ globalConfig,
1581
+ onComplete,
1582
+ outputStream,
1583
+ startRun,
1584
+ testWatcher: new (_jestWatcher().TestWatcher)({
1585
+ isWatchMode: false
1586
+ })
1587
+ });
1588
+ };
1589
+ return startRun();
1590
+ };
1591
+
1592
+ /***/ },
1593
+
1594
+ /***/ "./src/collectHandles.ts"
1595
+ (__unused_webpack_module, exports) {
1596
+
1597
+
1598
+
1599
+ Object.defineProperty(exports, "__esModule", ({
1600
+ value: true
1601
+ }));
1602
+ exports["default"] = collectHandles;
1603
+ exports.formatHandleErrors = formatHandleErrors;
1604
+ function asyncHooks() {
1605
+ const data = _interopRequireWildcard(require("node:async_hooks"));
1606
+ asyncHooks = function () {
1607
+ return data;
1608
+ };
1609
+ return data;
1610
+ }
1611
+ function _nodeUtil() {
1612
+ const data = require("node:util");
1613
+ _nodeUtil = function () {
1614
+ return data;
1615
+ };
1616
+ return data;
1617
+ }
1618
+ function v8() {
1619
+ const data = _interopRequireWildcard(require("node:v8"));
1620
+ v8 = function () {
1621
+ return data;
1622
+ };
1623
+ return data;
1624
+ }
1625
+ function vm() {
1626
+ const data = _interopRequireWildcard(require("node:vm"));
1627
+ vm = function () {
1628
+ return data;
1629
+ };
1630
+ return data;
1631
+ }
1632
+ function _jestMessageUtil() {
1633
+ const data = require("@pkg-nec/jest-message-util");
1634
+ _jestMessageUtil = function () {
1635
+ return data;
1636
+ };
1637
+ return data;
1638
+ }
1639
+ function _jestUtil() {
1640
+ const data = require("@pkg-nec/jest-util");
1641
+ _jestUtil = function () {
1642
+ return data;
1643
+ };
1644
+ return data;
1645
+ }
1646
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
1647
+ /**
1648
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1649
+ *
1650
+ * This source code is licensed under the MIT license found in the
1651
+ * LICENSE file in the root directory of this source tree.
1652
+ */
1653
+
1654
+ function stackIsFromUser(stack) {
1655
+ // Either the test file, or something required by it
1656
+ if (stack.includes('Runtime.requireModule')) {
1657
+ return true;
1658
+ }
1659
+
1660
+ // jest-jasmine it or describe call
1661
+ if (stack.includes('asyncJestTest') || stack.includes('asyncJestLifecycle')) {
1662
+ return true;
1663
+ }
1664
+
1665
+ // An async function call from within circus
1666
+ if (stack.includes('callAsyncCircusFn')) {
1667
+ // jest-circus it or describe call
1668
+ return stack.includes('_callCircusTest') || stack.includes('_callCircusHook');
1669
+ }
1670
+ return false;
1671
+ }
1672
+ const alwaysActive = () => true;
1673
+ const hasWeakRef = typeof WeakRef === 'function';
1674
+ const asyncSleep = (0, _nodeUtil().promisify)(setTimeout);
1675
+ let gcFunc = globalThis.gc;
1676
+ function runGC() {
1677
+ if (!gcFunc) {
1678
+ v8().setFlagsFromString('--expose-gc');
1679
+ gcFunc = vm().runInNewContext('gc');
1680
+ v8().setFlagsFromString('--no-expose-gc');
1681
+ if (!gcFunc) {
1682
+ throw new Error('Cannot find `global.gc` function. Please run node with `--expose-gc` and report this issue in jest repo.');
1683
+ }
1684
+ }
1685
+ gcFunc();
1686
+ }
1687
+
1688
+ // Inspired by https://github.com/mafintosh/why-is-node-running/blob/master/index.js
1689
+ // Extracted as we want to format the result ourselves
1690
+ function collectHandles() {
1691
+ const activeHandles = new Map();
1692
+ const hook = asyncHooks().createHook({
1693
+ destroy(asyncId) {
1694
+ activeHandles.delete(asyncId);
1695
+ },
1696
+ init: function initHook(asyncId, type, triggerAsyncId,
1697
+ // eslint-disable-next-line @typescript-eslint/no-empty-object-type
1698
+ resource) {
1699
+ // Skip resources that should not generally prevent the process from
1700
+ // exiting, not last a meaningfully long time, or otherwise shouldn't be
1701
+ // tracked.
1702
+ if (['PROMISE', 'TIMERWRAP', 'ELDHISTOGRAM', 'PerformanceObserver', 'RANDOMBYTESREQUEST', 'DNSCHANNEL', 'ZLIB', 'SIGNREQUEST', 'TLSWRAP', 'TCPWRAP'].includes(type)) {
1703
+ return;
1704
+ }
1705
+ const error = new (_jestUtil().ErrorWithStack)(type, initHook, 100);
1706
+ let fromUser = stackIsFromUser(error.stack || '');
1707
+
1708
+ // If the async resource was not directly created by user code, but was
1709
+ // triggered by another async resource from user code, track it and use
1710
+ // the original triggering resource's stack.
1711
+ if (!fromUser) {
1712
+ const triggeringHandle = activeHandles.get(triggerAsyncId);
1713
+ if (triggeringHandle) {
1714
+ fromUser = true;
1715
+ error.stack = triggeringHandle.error.stack;
1716
+ }
1717
+ }
1718
+ if (fromUser) {
1719
+ let isActive;
1720
+
1721
+ // Handle that supports hasRef
1722
+ if ('hasRef' in resource) {
1723
+ if (hasWeakRef) {
1724
+ const ref = new WeakRef(resource);
1725
+ isActive = () => {
1726
+ return ref.deref()?.hasRef() ?? false;
1727
+ };
1728
+ } else {
1729
+ isActive = resource.hasRef.bind(resource);
1730
+ }
1731
+ } else {
1732
+ // Handle that doesn't support hasRef
1733
+ isActive = alwaysActive;
1734
+ }
1735
+ activeHandles.set(asyncId, {
1736
+ error,
1737
+ isActive
1738
+ });
1739
+ }
1740
+ }
1741
+ });
1742
+ hook.enable();
1743
+ return async () => {
1744
+ // Wait briefly for any async resources that have been queued for
1745
+ // destruction to actually be destroyed.
1746
+ // For example, Node.js TCP Servers are not destroyed until *after* their
1747
+ // `close` callback runs. If someone finishes a test from the `close`
1748
+ // callback, we will not yet have seen the resource be destroyed here.
1749
+ await asyncSleep(0);
1750
+ if (activeHandles.size > 0) {
1751
+ await asyncSleep(30);
1752
+ if (activeHandles.size > 0) {
1753
+ runGC();
1754
+ await asyncSleep(0);
1755
+ }
1756
+ }
1757
+ hook.disable();
1758
+
1759
+ // Get errors for every async resource still referenced at this moment
1760
+ const result = [...activeHandles.values()].filter(({
1761
+ isActive
1762
+ }) => isActive()).map(({
1763
+ error
1764
+ }) => error);
1765
+ activeHandles.clear();
1766
+ return result;
1767
+ };
1768
+ }
1769
+ function formatHandleErrors(errors, config) {
1770
+ const stacks = new Map();
1771
+ for (const err of errors) {
1772
+ const formatted = (0, _jestMessageUtil().formatExecError)(err, config, {
1773
+ noStackTrace: false
1774
+ }, undefined, true);
1775
+
1776
+ // E.g. timeouts might give multiple traces to the same line of code
1777
+ // This hairy filtering tries to remove entries with duplicate stack traces
1778
+
1779
+ const ansiFree = (0, _nodeUtil().stripVTControlCharacters)(formatted);
1780
+ const match = ansiFree.match(/\s+at(.*)/);
1781
+ if (!match || match.length < 2) {
1782
+ continue;
1783
+ }
1784
+ const stackText = ansiFree.slice(ansiFree.indexOf(match[1])).trim();
1785
+ const name = ansiFree.match(/(?<=● {2}).*$/m);
1786
+ if (name == null || name.length === 0) {
1787
+ continue;
1788
+ }
1789
+ const stack = stacks.get(stackText) || {
1790
+ names: new Set(),
1791
+ stack: formatted.replace(name[0], '%%OBJECT_NAME%%')
1792
+ };
1793
+ stack.names.add(name[0]);
1794
+ stacks.set(stackText, stack);
1795
+ }
1796
+ return [...stacks.values()].map(({
1797
+ stack,
1798
+ names
1799
+ }) => stack.replace('%%OBJECT_NAME%%', [...names].join(',')));
1800
+ }
1801
+
1802
+ /***/ },
1803
+
1804
+ /***/ "./src/getChangedFilesPromise.ts"
1805
+ (__unused_webpack_module, exports) {
1806
+
1807
+
1808
+
1809
+ Object.defineProperty(exports, "__esModule", ({
1810
+ value: true
1811
+ }));
1812
+ exports["default"] = getChangedFilesPromise;
1813
+ function _chalk() {
1814
+ const data = _interopRequireDefault(require("chalk"));
1815
+ _chalk = function () {
1816
+ return data;
1817
+ };
1818
+ return data;
1819
+ }
1820
+ function _jestChangedFiles() {
1821
+ const data = require("@pkg-nec/jest-changed-files");
1822
+ _jestChangedFiles = function () {
1823
+ return data;
1824
+ };
1825
+ return data;
1826
+ }
1827
+ function _jestMessageUtil() {
1828
+ const data = require("@pkg-nec/jest-message-util");
1829
+ _jestMessageUtil = function () {
1830
+ return data;
1831
+ };
1832
+ return data;
1833
+ }
1834
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1835
+ /**
1836
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1837
+ *
1838
+ * This source code is licensed under the MIT license found in the
1839
+ * LICENSE file in the root directory of this source tree.
1840
+ */
1841
+
1842
+ function getChangedFilesPromise(globalConfig, configs) {
1843
+ if (globalConfig.onlyChanged) {
1844
+ const allRootsForAllProjects = new Set(configs.flatMap(config => config.roots || []));
1845
+ return (0, _jestChangedFiles().getChangedFilesForRoots)([...allRootsForAllProjects], {
1846
+ changedSince: globalConfig.changedSince,
1847
+ lastCommit: globalConfig.lastCommit,
1848
+ withAncestor: globalConfig.changedFilesWithAncestor
1849
+ }).catch(error => {
1850
+ const message = (0, _jestMessageUtil().formatExecError)(error, configs[0], {
1851
+ noStackTrace: true
1852
+ }).split('\n').filter(line => !line.includes('Command failed:')).join('\n');
1853
+ console.error(_chalk().default.red(`\n\n${message}`));
1854
+ process.exit(1);
1855
+ });
1856
+ }
1857
+ return undefined;
1858
+ }
1859
+
1860
+ /***/ },
1861
+
1862
+ /***/ "./src/getConfigsOfProjectsToRun.ts"
1863
+ (__unused_webpack_module, exports, __webpack_require__) {
1864
+
1865
+
1866
+
1867
+ Object.defineProperty(exports, "__esModule", ({
1868
+ value: true
1869
+ }));
1870
+ exports["default"] = getConfigsOfProjectsToRun;
1871
+ var _getProjectDisplayName = _interopRequireDefault(__webpack_require__("./src/getProjectDisplayName.ts"));
1872
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1873
+ /**
1874
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1875
+ *
1876
+ * This source code is licensed under the MIT license found in the
1877
+ * LICENSE file in the root directory of this source tree.
1878
+ */
1879
+
1880
+ function getConfigsOfProjectsToRun(projectConfigs, opts) {
1881
+ const projectFilter = createProjectFilter(opts);
1882
+ return projectConfigs.filter(config => {
1883
+ const name = (0, _getProjectDisplayName.default)(config);
1884
+ return projectFilter(name);
1885
+ });
1886
+ }
1887
+ const always = () => true;
1888
+ function createProjectFilter(opts) {
1889
+ const {
1890
+ selectProjects,
1891
+ ignoreProjects
1892
+ } = opts;
1893
+ const selected = selectProjects ? name => name && selectProjects.includes(name) : always;
1894
+ const notIgnore = ignoreProjects ? name => !(name && ignoreProjects.includes(name)) : always;
1895
+ function test(name) {
1896
+ return selected(name) && notIgnore(name);
1897
+ }
1898
+ return test;
1899
+ }
1900
+
1901
+ /***/ },
1902
+
1903
+ /***/ "./src/getNoTestFound.ts"
1904
+ (__unused_webpack_module, exports) {
1905
+
1906
+
1907
+
1908
+ Object.defineProperty(exports, "__esModule", ({
1909
+ value: true
1910
+ }));
1911
+ exports["default"] = getNoTestFound;
1912
+ function _chalk() {
1913
+ const data = _interopRequireDefault(require("chalk"));
1914
+ _chalk = function () {
1915
+ return data;
1916
+ };
1917
+ return data;
1918
+ }
1919
+ function _jestUtil() {
1920
+ const data = require("@pkg-nec/jest-util");
1921
+ _jestUtil = function () {
1922
+ return data;
1923
+ };
1924
+ return data;
1925
+ }
1926
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1927
+ /**
1928
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1929
+ *
1930
+ * This source code is licensed under the MIT license found in the
1931
+ * LICENSE file in the root directory of this source tree.
1932
+ */
1933
+
1934
+ function getNoTestFound(testRunData, globalConfig, willExitWith0) {
1935
+ const testFiles = testRunData.reduce((current, testRun) => current + (testRun.matches.total || 0), 0);
1936
+ let dataMessage;
1937
+ if (globalConfig.runTestsByPath) {
1938
+ dataMessage = `Files: ${globalConfig.nonFlagArgs.map(p => `"${p}"`).join(', ')}`;
1939
+ } else {
1940
+ dataMessage = `Pattern: ${_chalk().default.yellow(globalConfig.testPathPatterns.toPretty())} - 0 matches`;
1941
+ }
1942
+ if (willExitWith0) {
1943
+ return `${_chalk().default.bold('No tests found, exiting with code 0')}\n` + `In ${_chalk().default.bold(globalConfig.rootDir)}` + '\n' + ` ${(0, _jestUtil().pluralize)('file', testFiles, 's')} checked across ${(0, _jestUtil().pluralize)('project', testRunData.length, 's')}. Run with \`--verbose\` for more details.` + `\n${dataMessage}`;
1944
+ }
1945
+ return `${_chalk().default.bold('No tests found, exiting with code 1')}\n` + 'Run with `--passWithNoTests` to exit with code 0' + '\n' + `In ${_chalk().default.bold(globalConfig.rootDir)}` + '\n' + ` ${(0, _jestUtil().pluralize)('file', testFiles, 's')} checked across ${(0, _jestUtil().pluralize)('project', testRunData.length, 's')}. Run with \`--verbose\` for more details.` + `\n${dataMessage}`;
1946
+ }
1947
+
1948
+ /***/ },
1949
+
1950
+ /***/ "./src/getNoTestFoundFailed.ts"
1951
+ (__unused_webpack_module, exports) {
1952
+
1953
+
1954
+
1955
+ Object.defineProperty(exports, "__esModule", ({
1956
+ value: true
1957
+ }));
1958
+ exports["default"] = getNoTestFoundFailed;
1959
+ function _chalk() {
1960
+ const data = _interopRequireDefault(require("chalk"));
1961
+ _chalk = function () {
1962
+ return data;
1963
+ };
1964
+ return data;
1965
+ }
1966
+ function _jestUtil() {
1967
+ const data = require("@pkg-nec/jest-util");
1968
+ _jestUtil = function () {
1969
+ return data;
1970
+ };
1971
+ return data;
1972
+ }
1973
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
1974
+ /**
1975
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
1976
+ *
1977
+ * This source code is licensed under the MIT license found in the
1978
+ * LICENSE file in the root directory of this source tree.
1979
+ */
1980
+
1981
+ function getNoTestFoundFailed(globalConfig) {
1982
+ let msg = _chalk().default.bold('No failed test found.');
1983
+ if (_jestUtil().isInteractive) {
1984
+ msg += _chalk().default.dim(`\n${globalConfig.watch ? 'Press `f` to quit "only failed tests" mode.' : 'Run Jest without `--onlyFailures` or with `--all` to run all tests.'}`);
1985
+ }
1986
+ return msg;
1987
+ }
1988
+
1989
+ /***/ },
1990
+
1991
+ /***/ "./src/getNoTestFoundPassWithNoTests.ts"
1992
+ (__unused_webpack_module, exports) {
1993
+
1994
+
1995
+
1996
+ Object.defineProperty(exports, "__esModule", ({
1997
+ value: true
1998
+ }));
1999
+ exports["default"] = getNoTestFoundPassWithNoTests;
2000
+ function _chalk() {
2001
+ const data = _interopRequireDefault(require("chalk"));
2002
+ _chalk = function () {
2003
+ return data;
2004
+ };
2005
+ return data;
2006
+ }
2007
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2008
+ /**
2009
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2010
+ *
2011
+ * This source code is licensed under the MIT license found in the
2012
+ * LICENSE file in the root directory of this source tree.
2013
+ */
2014
+
2015
+ function getNoTestFoundPassWithNoTests() {
2016
+ return _chalk().default.bold('No tests found, exiting with code 0');
2017
+ }
2018
+
2019
+ /***/ },
2020
+
2021
+ /***/ "./src/getNoTestFoundRelatedToChangedFiles.ts"
2022
+ (__unused_webpack_module, exports) {
2023
+
2024
+
2025
+
2026
+ Object.defineProperty(exports, "__esModule", ({
2027
+ value: true
2028
+ }));
2029
+ exports["default"] = getNoTestFoundRelatedToChangedFiles;
2030
+ function _chalk() {
2031
+ const data = _interopRequireDefault(require("chalk"));
2032
+ _chalk = function () {
2033
+ return data;
2034
+ };
2035
+ return data;
2036
+ }
2037
+ function _jestUtil() {
2038
+ const data = require("@pkg-nec/jest-util");
2039
+ _jestUtil = function () {
2040
+ return data;
2041
+ };
2042
+ return data;
2043
+ }
2044
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2045
+ /**
2046
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2047
+ *
2048
+ * This source code is licensed under the MIT license found in the
2049
+ * LICENSE file in the root directory of this source tree.
2050
+ */
2051
+
2052
+ function getNoTestFoundRelatedToChangedFiles(globalConfig) {
2053
+ const ref = globalConfig.changedSince ? `"${globalConfig.changedSince}"` : 'last commit';
2054
+ let msg = _chalk().default.bold(`No tests found related to files changed since ${ref}.`);
2055
+ if (_jestUtil().isInteractive) {
2056
+ msg += _chalk().default.dim(`\n${globalConfig.watch ? 'Press `a` to run all tests, or run Jest with `--watchAll`.' : 'Run Jest without `-o` or with `--all` to run all tests.'}`);
2057
+ }
2058
+ return msg;
2059
+ }
2060
+
2061
+ /***/ },
2062
+
2063
+ /***/ "./src/getNoTestFoundVerbose.ts"
2064
+ (__unused_webpack_module, exports) {
2065
+
2066
+
2067
+
2068
+ Object.defineProperty(exports, "__esModule", ({
2069
+ value: true
2070
+ }));
2071
+ exports["default"] = getNoTestFoundVerbose;
2072
+ function _chalk() {
2073
+ const data = _interopRequireDefault(require("chalk"));
2074
+ _chalk = function () {
2075
+ return data;
2076
+ };
2077
+ return data;
2078
+ }
2079
+ function _jestUtil() {
2080
+ const data = require("@pkg-nec/jest-util");
2081
+ _jestUtil = function () {
2082
+ return data;
2083
+ };
2084
+ return data;
2085
+ }
2086
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2087
+ /**
2088
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2089
+ *
2090
+ * This source code is licensed under the MIT license found in the
2091
+ * LICENSE file in the root directory of this source tree.
2092
+ */
2093
+
2094
+ function getNoTestFoundVerbose(testRunData, globalConfig, willExitWith0) {
2095
+ const individualResults = testRunData.map(testRun => {
2096
+ const stats = testRun.matches.stats || {};
2097
+ const config = testRun.context.config;
2098
+ const statsMessage = Object.keys(stats).map(key => {
2099
+ if (key === 'roots' && config.roots.length === 1) {
2100
+ return null;
2101
+ }
2102
+ const value = config[key];
2103
+ if (value) {
2104
+ const valueAsString = Array.isArray(value) ? value.join(', ') : String(value);
2105
+ const matches = (0, _jestUtil().pluralize)('match', stats[key] || 0, 'es');
2106
+ return ` ${key}: ${_chalk().default.yellow(valueAsString)} - ${matches}`;
2107
+ }
2108
+ return null;
2109
+ }).filter(Boolean).join('\n');
2110
+ return testRun.matches.total ? `In ${_chalk().default.bold(config.rootDir)}\n` + ` ${(0, _jestUtil().pluralize)('file', testRun.matches.total || 0, 's')} checked.\n${statsMessage}` : `No files found in ${config.rootDir}.\n` + "Make sure Jest's configuration does not exclude this directory." + '\nTo set up Jest, make sure a package.json file exists.\n' + 'Jest Documentation: ' + 'https://jestjs.io/docs/configuration';
2111
+ });
2112
+ let dataMessage;
2113
+ if (globalConfig.runTestsByPath) {
2114
+ dataMessage = `Files: ${globalConfig.nonFlagArgs.map(p => `"${p}"`).join(', ')}`;
2115
+ } else {
2116
+ dataMessage = `Pattern: ${_chalk().default.yellow(globalConfig.testPathPatterns.toPretty())} - 0 matches`;
2117
+ }
2118
+ if (willExitWith0) {
2119
+ return `${_chalk().default.bold('No tests found, exiting with code 0')}\n${individualResults.join('\n')}\n${dataMessage}`;
2120
+ }
2121
+ return `${_chalk().default.bold('No tests found, exiting with code 1')}\n` + 'Run with `--passWithNoTests` to exit with code 0' + `\n${individualResults.join('\n')}\n${dataMessage}`;
2122
+ }
2123
+
2124
+ /***/ },
2125
+
2126
+ /***/ "./src/getNoTestsFoundMessage.ts"
2127
+ (__unused_webpack_module, exports, __webpack_require__) {
2128
+
2129
+
2130
+
2131
+ Object.defineProperty(exports, "__esModule", ({
2132
+ value: true
2133
+ }));
2134
+ exports["default"] = getNoTestsFoundMessage;
2135
+ var _getNoTestFound = _interopRequireDefault(__webpack_require__("./src/getNoTestFound.ts"));
2136
+ var _getNoTestFoundFailed = _interopRequireDefault(__webpack_require__("./src/getNoTestFoundFailed.ts"));
2137
+ var _getNoTestFoundPassWithNoTests = _interopRequireDefault(__webpack_require__("./src/getNoTestFoundPassWithNoTests.ts"));
2138
+ var _getNoTestFoundRelatedToChangedFiles = _interopRequireDefault(__webpack_require__("./src/getNoTestFoundRelatedToChangedFiles.ts"));
2139
+ var _getNoTestFoundVerbose = _interopRequireDefault(__webpack_require__("./src/getNoTestFoundVerbose.ts"));
2140
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2141
+ /**
2142
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2143
+ *
2144
+ * This source code is licensed under the MIT license found in the
2145
+ * LICENSE file in the root directory of this source tree.
2146
+ */
2147
+
2148
+ function getNoTestsFoundMessage(testRunData, globalConfig) {
2149
+ const exitWith0 = globalConfig.passWithNoTests || globalConfig.lastCommit || globalConfig.onlyChanged;
2150
+ if (globalConfig.onlyFailures) {
2151
+ return {
2152
+ exitWith0,
2153
+ message: (0, _getNoTestFoundFailed.default)(globalConfig)
2154
+ };
2155
+ }
2156
+ if (globalConfig.onlyChanged) {
2157
+ return {
2158
+ exitWith0,
2159
+ message: (0, _getNoTestFoundRelatedToChangedFiles.default)(globalConfig)
2160
+ };
2161
+ }
2162
+ if (globalConfig.passWithNoTests) {
2163
+ return {
2164
+ exitWith0,
2165
+ message: (0, _getNoTestFoundPassWithNoTests.default)()
2166
+ };
2167
+ }
2168
+ return {
2169
+ exitWith0,
2170
+ message: testRunData.length === 1 || globalConfig.verbose ? (0, _getNoTestFoundVerbose.default)(testRunData, globalConfig, exitWith0) : (0, _getNoTestFound.default)(testRunData, globalConfig, exitWith0)
2171
+ };
2172
+ }
2173
+
2174
+ /***/ },
2175
+
2176
+ /***/ "./src/getProjectDisplayName.ts"
2177
+ (__unused_webpack_module, exports) {
2178
+
2179
+
2180
+
2181
+ Object.defineProperty(exports, "__esModule", ({
2182
+ value: true
2183
+ }));
2184
+ exports["default"] = getProjectDisplayName;
2185
+ /**
2186
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2187
+ *
2188
+ * This source code is licensed under the MIT license found in the
2189
+ * LICENSE file in the root directory of this source tree.
2190
+ */
2191
+
2192
+ function getProjectDisplayName(projectConfig) {
2193
+ return projectConfig.displayName?.name || undefined;
2194
+ }
2195
+
2196
+ /***/ },
2197
+
2198
+ /***/ "./src/getProjectNamesMissingWarning.ts"
2199
+ (__unused_webpack_module, exports, __webpack_require__) {
2200
+
2201
+
2202
+
2203
+ Object.defineProperty(exports, "__esModule", ({
2204
+ value: true
2205
+ }));
2206
+ exports["default"] = getProjectNamesMissingWarning;
2207
+ function _chalk() {
2208
+ const data = _interopRequireDefault(require("chalk"));
2209
+ _chalk = function () {
2210
+ return data;
2211
+ };
2212
+ return data;
2213
+ }
2214
+ var _getProjectDisplayName = _interopRequireDefault(__webpack_require__("./src/getProjectDisplayName.ts"));
2215
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2216
+ /**
2217
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2218
+ *
2219
+ * This source code is licensed under the MIT license found in the
2220
+ * LICENSE file in the root directory of this source tree.
2221
+ */
2222
+
2223
+ function getProjectNamesMissingWarning(projectConfigs, opts) {
2224
+ const numberOfProjectsWithoutAName = projectConfigs.filter(config => !(0, _getProjectDisplayName.default)(config)).length;
2225
+ if (numberOfProjectsWithoutAName === 0) {
2226
+ return undefined;
2227
+ }
2228
+ const args = [];
2229
+ if (opts.selectProjects) {
2230
+ args.push('--selectProjects');
2231
+ }
2232
+ if (opts.ignoreProjects) {
2233
+ args.push('--ignoreProjects');
2234
+ }
2235
+ return _chalk().default.yellow(`You provided values for ${args.join(' and ')} but ${numberOfProjectsWithoutAName === 1 ? 'a project does not have a name' : `${numberOfProjectsWithoutAName} projects do not have a name`}.\n` + 'Set displayName in the config of all projects in order to disable this warning.\n');
2236
+ }
2237
+
2238
+ /***/ },
2239
+
2240
+ /***/ "./src/getSelectProjectsMessage.ts"
2241
+ (__unused_webpack_module, exports, __webpack_require__) {
2242
+
2243
+
2244
+
2245
+ Object.defineProperty(exports, "__esModule", ({
2246
+ value: true
2247
+ }));
2248
+ exports["default"] = getSelectProjectsMessage;
2249
+ function _chalk() {
2250
+ const data = _interopRequireDefault(require("chalk"));
2251
+ _chalk = function () {
2252
+ return data;
2253
+ };
2254
+ return data;
2255
+ }
2256
+ var _getProjectDisplayName = _interopRequireDefault(__webpack_require__("./src/getProjectDisplayName.ts"));
2257
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2258
+ /**
2259
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2260
+ *
2261
+ * This source code is licensed under the MIT license found in the
2262
+ * LICENSE file in the root directory of this source tree.
2263
+ */
2264
+
2265
+ function getSelectProjectsMessage(projectConfigs, opts) {
2266
+ if (projectConfigs.length === 0) {
2267
+ return getNoSelectionWarning(opts);
2268
+ }
2269
+ return getProjectsRunningMessage(projectConfigs);
2270
+ }
2271
+ function getNoSelectionWarning(opts) {
2272
+ if (opts.ignoreProjects && opts.selectProjects) {
2273
+ return _chalk().default.yellow('You provided values for --selectProjects and --ignoreProjects, but no projects were found matching the selection.\n' + 'Are you ignoring all the selected projects?\n');
2274
+ } else if (opts.ignoreProjects) {
2275
+ return _chalk().default.yellow('You provided values for --ignoreProjects, but no projects were found matching the selection.\n' + 'Are you ignoring all projects?\n');
2276
+ } else if (opts.selectProjects) {
2277
+ return _chalk().default.yellow('You provided values for --selectProjects but no projects were found matching the selection.\n');
2278
+ } else {
2279
+ return _chalk().default.yellow('No projects were found.\n');
2280
+ }
2281
+ }
2282
+ function getProjectsRunningMessage(projectConfigs) {
2283
+ if (projectConfigs.length === 1) {
2284
+ const name = (0, _getProjectDisplayName.default)(projectConfigs[0]) ?? '<unnamed project>';
2285
+ return `Running one project: ${_chalk().default.bold(name)}\n`;
2286
+ }
2287
+ const projectsList = projectConfigs.map(getProjectNameListElement).sort().join('\n');
2288
+ return `Running ${projectConfigs.length} projects:\n${projectsList}\n`;
2289
+ }
2290
+ function getProjectNameListElement(projectConfig) {
2291
+ const name = (0, _getProjectDisplayName.default)(projectConfig);
2292
+ const elementContent = name ? _chalk().default.bold(name) : '<unnamed project>';
2293
+ return `- ${elementContent}`;
2294
+ }
2295
+
2296
+ /***/ },
2297
+
2298
+ /***/ "./src/lib/activeFiltersMessage.ts"
2299
+ (__unused_webpack_module, exports) {
2300
+
2301
+
2302
+
2303
+ Object.defineProperty(exports, "__esModule", ({
2304
+ value: true
2305
+ }));
2306
+ exports["default"] = void 0;
2307
+ function _chalk() {
2308
+ const data = _interopRequireDefault(require("chalk"));
2309
+ _chalk = function () {
2310
+ return data;
2311
+ };
2312
+ return data;
2313
+ }
2314
+ function _jestUtil() {
2315
+ const data = require("@pkg-nec/jest-util");
2316
+ _jestUtil = function () {
2317
+ return data;
2318
+ };
2319
+ return data;
2320
+ }
2321
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2322
+ /**
2323
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2324
+ *
2325
+ * This source code is licensed under the MIT license found in the
2326
+ * LICENSE file in the root directory of this source tree.
2327
+ */
2328
+
2329
+ const activeFilters = globalConfig => {
2330
+ const {
2331
+ testNamePattern
2332
+ } = globalConfig;
2333
+ const testPathPatterns = globalConfig.testPathPatterns;
2334
+ if (testNamePattern || testPathPatterns.isSet()) {
2335
+ const filters = [testPathPatterns.isSet() ? _chalk().default.dim('filename ') + _chalk().default.yellow(testPathPatterns.toPretty()) : null, testNamePattern ? _chalk().default.dim('test name ') + _chalk().default.yellow(`/${testNamePattern}/`) : null].filter(_jestUtil().isNonNullable).join(', ');
2336
+ const messages = `\n${_chalk().default.bold('Active Filters: ')}${filters}`;
2337
+ return messages;
2338
+ }
2339
+ return '';
2340
+ };
2341
+ var _default = exports["default"] = activeFilters;
2342
+
2343
+ /***/ },
2344
+
2345
+ /***/ "./src/lib/createContext.ts"
2346
+ (__unused_webpack_module, exports) {
2347
+
2348
+
2349
+
2350
+ Object.defineProperty(exports, "__esModule", ({
2351
+ value: true
2352
+ }));
2353
+ exports["default"] = createContext;
2354
+ function _jestRuntime() {
2355
+ const data = _interopRequireDefault(require("@pkg-nec/jest-runtime"));
2356
+ _jestRuntime = function () {
2357
+ return data;
2358
+ };
2359
+ return data;
2360
+ }
2361
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2362
+ /**
2363
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2364
+ *
2365
+ * This source code is licensed under the MIT license found in the
2366
+ * LICENSE file in the root directory of this source tree.
2367
+ */
2368
+
2369
+ function createContext(config, {
2370
+ hasteFS,
2371
+ moduleMap
2372
+ }) {
2373
+ return {
2374
+ config,
2375
+ hasteFS,
2376
+ moduleMap,
2377
+ resolver: _jestRuntime().default.createResolver(config, moduleMap)
2378
+ };
2379
+ }
2380
+
2381
+ /***/ },
2382
+
2383
+ /***/ "./src/lib/handleDeprecationWarnings.ts"
2384
+ (__unused_webpack_module, exports) {
2385
+
2386
+
2387
+
2388
+ Object.defineProperty(exports, "__esModule", ({
2389
+ value: true
2390
+ }));
2391
+ exports["default"] = handleDeprecationWarnings;
2392
+ function _chalk() {
2393
+ const data = _interopRequireDefault(require("chalk"));
2394
+ _chalk = function () {
2395
+ return data;
2396
+ };
2397
+ return data;
2398
+ }
2399
+ function _jestWatcher() {
2400
+ const data = require("@pkg-nec/jest-watcher");
2401
+ _jestWatcher = function () {
2402
+ return data;
2403
+ };
2404
+ return data;
2405
+ }
2406
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2407
+ /**
2408
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2409
+ *
2410
+ * This source code is licensed under the MIT license found in the
2411
+ * LICENSE file in the root directory of this source tree.
2412
+ */
2413
+
2414
+ function handleDeprecationWarnings(pipe, stdin = process.stdin) {
2415
+ return new Promise((resolve, reject) => {
2416
+ if (typeof stdin.setRawMode === 'function') {
2417
+ const messages = [_chalk().default.red('There are deprecation warnings.\n'), `${_chalk().default.dim(' \u203A Press ')}Enter${_chalk().default.dim(' to continue.')}`, `${_chalk().default.dim(' \u203A Press ')}Esc${_chalk().default.dim(' to exit.')}`];
2418
+ pipe.write(messages.join('\n'));
2419
+ stdin.setRawMode(true);
2420
+ stdin.resume();
2421
+ stdin.setEncoding('utf8');
2422
+ // this is a string since we set encoding above
2423
+ stdin.on('data', key => {
2424
+ if (key === _jestWatcher().KEYS.ENTER) {
2425
+ resolve();
2426
+ } else if ([_jestWatcher().KEYS.ESCAPE, _jestWatcher().KEYS.CONTROL_C, _jestWatcher().KEYS.CONTROL_D].includes(key)) {
2427
+ reject();
2428
+ }
2429
+ });
2430
+ } else {
2431
+ resolve();
2432
+ }
2433
+ });
2434
+ }
2435
+
2436
+ /***/ },
2437
+
2438
+ /***/ "./src/lib/isValidPath.ts"
2439
+ (__unused_webpack_module, exports) {
2440
+
2441
+
2442
+
2443
+ Object.defineProperty(exports, "__esModule", ({
2444
+ value: true
2445
+ }));
2446
+ exports["default"] = isValidPath;
2447
+ function _jestSnapshot() {
2448
+ const data = require("@pkg-nec/jest-snapshot");
2449
+ _jestSnapshot = function () {
2450
+ return data;
2451
+ };
2452
+ return data;
2453
+ }
2454
+ /**
2455
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2456
+ *
2457
+ * This source code is licensed under the MIT license found in the
2458
+ * LICENSE file in the root directory of this source tree.
2459
+ */
2460
+
2461
+ function isValidPath(globalConfig, filePath) {
2462
+ return !filePath.includes(globalConfig.coverageDirectory) && !(0, _jestSnapshot().isSnapshotPath)(filePath);
2463
+ }
2464
+
2465
+ /***/ },
2466
+
2467
+ /***/ "./src/lib/logDebugMessages.ts"
2468
+ (__unused_webpack_module, exports, __webpack_require__) {
2469
+
2470
+
2471
+
2472
+ Object.defineProperty(exports, "__esModule", ({
2473
+ value: true
2474
+ }));
2475
+ exports["default"] = logDebugMessages;
2476
+ /**
2477
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2478
+ *
2479
+ * This source code is licensed under the MIT license found in the
2480
+ * LICENSE file in the root directory of this source tree.
2481
+ */
2482
+
2483
+ const VERSION = (__webpack_require__("./package.json").version);
2484
+
2485
+ // if the output here changes, update `getConfig` in e2e/runJest.ts
2486
+ function logDebugMessages(globalConfig, configs, outputStream) {
2487
+ const output = {
2488
+ configs,
2489
+ globalConfig: {
2490
+ ...globalConfig,
2491
+ testPathPatterns: globalConfig.testPathPatterns.patterns
2492
+ },
2493
+ version: VERSION
2494
+ };
2495
+ outputStream.write(`${JSON.stringify(output, null, ' ')}\n`);
2496
+ }
2497
+
2498
+ /***/ },
2499
+
2500
+ /***/ "./src/lib/serializeToJSON.ts"
2501
+ (__unused_webpack_module, exports) {
2502
+
2503
+
2504
+
2505
+ Object.defineProperty(exports, "__esModule", ({
2506
+ value: true
2507
+ }));
2508
+ exports["default"] = serializeToJSON;
2509
+ function _jestUtil() {
2510
+ const data = require("@pkg-nec/jest-util");
2511
+ _jestUtil = function () {
2512
+ return data;
2513
+ };
2514
+ return data;
2515
+ }
2516
+ /**
2517
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2518
+ *
2519
+ * This source code is licensed under the MIT license found in the
2520
+ * LICENSE file in the root directory of this source tree.
2521
+ */
2522
+
2523
+ /**
2524
+ * When we're asked to give a JSON output with the --json flag or otherwise,
2525
+ * some data we need to return don't serialize well with a basic
2526
+ * `JSON.stringify`, particularly Errors returned in `.openHandles`.
2527
+ *
2528
+ * This function handles the extended serialization wanted above.
2529
+ */
2530
+ function serializeToJSON(value, space) {
2531
+ return JSON.stringify(value, (_, value) => {
2532
+ // There might be more in Error, but pulling out just the message, name,
2533
+ // and stack should be good enough
2534
+ if ((0, _jestUtil().isError)(value)) {
2535
+ return {
2536
+ message: value.message,
2537
+ name: value.name,
2538
+ stack: value.stack
2539
+ };
2540
+ }
2541
+ return value;
2542
+ }, space);
2543
+ }
2544
+
2545
+ /***/ },
2546
+
2547
+ /***/ "./src/lib/updateGlobalConfig.ts"
2548
+ (__unused_webpack_module, exports) {
2549
+
2550
+
2551
+
2552
+ Object.defineProperty(exports, "__esModule", ({
2553
+ value: true
2554
+ }));
2555
+ exports["default"] = updateGlobalConfig;
2556
+ function _jestPattern() {
2557
+ const data = require("@pkg-nec/jest-pattern");
2558
+ _jestPattern = function () {
2559
+ return data;
2560
+ };
2561
+ return data;
2562
+ }
2563
+ /**
2564
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2565
+ *
2566
+ * This source code is licensed under the MIT license found in the
2567
+ * LICENSE file in the root directory of this source tree.
2568
+ */
2569
+
2570
+ function updateGlobalConfig(globalConfig, options = {}) {
2571
+ const newConfig = {
2572
+ ...globalConfig
2573
+ };
2574
+ if (options.mode === 'watch') {
2575
+ newConfig.watch = true;
2576
+ newConfig.watchAll = false;
2577
+ } else if (options.mode === 'watchAll') {
2578
+ newConfig.watch = false;
2579
+ newConfig.watchAll = true;
2580
+ }
2581
+ if (options.testNamePattern !== undefined) {
2582
+ newConfig.testNamePattern = options.testNamePattern || '';
2583
+ }
2584
+ if (options.testPathPatterns !== undefined) {
2585
+ newConfig.testPathPatterns = new (_jestPattern().TestPathPatterns)(options.testPathPatterns);
2586
+ }
2587
+ newConfig.onlyChanged = !newConfig.watchAll && !newConfig.testNamePattern && !newConfig.testPathPatterns.isSet();
2588
+ if (typeof options.bail === 'boolean') {
2589
+ newConfig.bail = options.bail ? 1 : 0;
2590
+ } else if (options.bail !== undefined) {
2591
+ newConfig.bail = options.bail;
2592
+ }
2593
+ if (options.changedSince !== undefined) {
2594
+ newConfig.changedSince = options.changedSince;
2595
+ }
2596
+ if (options.collectCoverage !== undefined) {
2597
+ newConfig.collectCoverage = options.collectCoverage || false;
2598
+ }
2599
+ if (options.collectCoverageFrom !== undefined) {
2600
+ newConfig.collectCoverageFrom = options.collectCoverageFrom;
2601
+ }
2602
+ if (options.coverageDirectory !== undefined) {
2603
+ newConfig.coverageDirectory = options.coverageDirectory;
2604
+ }
2605
+ if (options.coverageReporters !== undefined) {
2606
+ newConfig.coverageReporters = options.coverageReporters;
2607
+ }
2608
+ if (options.findRelatedTests !== undefined) {
2609
+ newConfig.findRelatedTests = options.findRelatedTests;
2610
+ }
2611
+ if (options.nonFlagArgs !== undefined) {
2612
+ newConfig.nonFlagArgs = options.nonFlagArgs;
2613
+ }
2614
+ if (options.noSCM) {
2615
+ newConfig.noSCM = true;
2616
+ }
2617
+ if (options.notify !== undefined) {
2618
+ newConfig.notify = options.notify || false;
2619
+ }
2620
+ if (options.notifyMode !== undefined) {
2621
+ newConfig.notifyMode = options.notifyMode;
2622
+ }
2623
+ if (options.onlyFailures !== undefined) {
2624
+ newConfig.onlyFailures = options.onlyFailures || false;
2625
+ }
2626
+ if (options.passWithNoTests !== undefined) {
2627
+ newConfig.passWithNoTests = true;
2628
+ }
2629
+ if (options.reporters !== undefined) {
2630
+ newConfig.reporters = options.reporters;
2631
+ }
2632
+ if (options.updateSnapshot !== undefined) {
2633
+ newConfig.updateSnapshot = options.updateSnapshot;
2634
+ }
2635
+ if (options.verbose !== undefined) {
2636
+ newConfig.verbose = options.verbose || false;
2637
+ }
2638
+ return Object.freeze(newConfig);
2639
+ }
2640
+
2641
+ /***/ },
2642
+
2643
+ /***/ "./src/lib/watchPluginsHelpers.ts"
2644
+ (__unused_webpack_module, exports) {
2645
+
2646
+
2647
+
2648
+ Object.defineProperty(exports, "__esModule", ({
2649
+ value: true
2650
+ }));
2651
+ exports.getSortedUsageRows = exports.filterInteractivePlugins = void 0;
2652
+ function _jestUtil() {
2653
+ const data = require("@pkg-nec/jest-util");
2654
+ _jestUtil = function () {
2655
+ return data;
2656
+ };
2657
+ return data;
2658
+ }
2659
+ /**
2660
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2661
+ *
2662
+ * This source code is licensed under the MIT license found in the
2663
+ * LICENSE file in the root directory of this source tree.
2664
+ */
2665
+
2666
+ const filterInteractivePlugins = (watchPlugins, globalConfig) => {
2667
+ const usageInfos = watchPlugins.map(p => p.getUsageInfo && p.getUsageInfo(globalConfig));
2668
+ return watchPlugins.filter((_plugin, i) => {
2669
+ const usageInfo = usageInfos[i];
2670
+ if (usageInfo) {
2671
+ const {
2672
+ key
2673
+ } = usageInfo;
2674
+ return !usageInfos.slice(i + 1).some(u => !!u && key === u.key);
2675
+ }
2676
+ return false;
2677
+ });
2678
+ };
2679
+ exports.filterInteractivePlugins = filterInteractivePlugins;
2680
+ const getSortedUsageRows = (watchPlugins, globalConfig) => filterInteractivePlugins(watchPlugins, globalConfig).sort((a, b) => {
2681
+ if (a.isInternal && b.isInternal) {
2682
+ // internal plugins in the order we specify them
2683
+ return 0;
2684
+ }
2685
+ if (a.isInternal !== b.isInternal) {
2686
+ // external plugins afterwards
2687
+ return a.isInternal ? -1 : 1;
2688
+ }
2689
+ const usageInfoA = a.getUsageInfo && a.getUsageInfo(globalConfig);
2690
+ const usageInfoB = b.getUsageInfo && b.getUsageInfo(globalConfig);
2691
+ if (usageInfoA && usageInfoB) {
2692
+ // external plugins in alphabetical order
2693
+ return usageInfoA.key.localeCompare(usageInfoB.key);
2694
+ }
2695
+ return 0;
2696
+ }).map(p => p.getUsageInfo && p.getUsageInfo(globalConfig)).filter(_jestUtil().isNonNullable);
2697
+ exports.getSortedUsageRows = getSortedUsageRows;
2698
+
2699
+ /***/ },
2700
+
2701
+ /***/ "./src/plugins/FailedTestsInteractive.ts"
2702
+ (__unused_webpack_module, exports, __webpack_require__) {
2703
+
2704
+
2705
+
2706
+ Object.defineProperty(exports, "__esModule", ({
2707
+ value: true
2708
+ }));
2709
+ exports["default"] = void 0;
2710
+ function _jestWatcher() {
2711
+ const data = require("@pkg-nec/jest-watcher");
2712
+ _jestWatcher = function () {
2713
+ return data;
2714
+ };
2715
+ return data;
2716
+ }
2717
+ var _FailedTestsInteractiveMode = _interopRequireDefault(__webpack_require__("./src/FailedTestsInteractiveMode.ts"));
2718
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2719
+ /**
2720
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2721
+ *
2722
+ * This source code is licensed under the MIT license found in the
2723
+ * LICENSE file in the root directory of this source tree.
2724
+ */
2725
+
2726
+ class FailedTestsInteractivePlugin extends _jestWatcher().BaseWatchPlugin {
2727
+ _failedTestAssertions;
2728
+ _manager = new _FailedTestsInteractiveMode.default(this._stdout);
2729
+ apply(hooks) {
2730
+ hooks.onTestRunComplete(results => {
2731
+ this._failedTestAssertions = this.getFailedTestAssertions(results);
2732
+ if (this._manager.isActive()) this._manager.updateWithResults(results);
2733
+ });
2734
+ }
2735
+ getUsageInfo() {
2736
+ if (this._failedTestAssertions?.length) {
2737
+ return {
2738
+ key: 'i',
2739
+ prompt: 'run failing tests interactively'
2740
+ };
2741
+ }
2742
+ return null;
2743
+ }
2744
+ onKey(key) {
2745
+ if (this._manager.isActive()) {
2746
+ this._manager.put(key);
2747
+ }
2748
+ }
2749
+ run(_, updateConfigAndRun) {
2750
+ return new Promise(resolve => {
2751
+ if (!this._failedTestAssertions || this._failedTestAssertions.length === 0) {
2752
+ resolve();
2753
+ return;
2754
+ }
2755
+ this._manager.run(this._failedTestAssertions, failure => {
2756
+ updateConfigAndRun({
2757
+ mode: 'watch',
2758
+ testNamePattern: failure ? `^${failure.fullName}$` : '',
2759
+ testPathPatterns: failure ? [failure.path] : []
2760
+ });
2761
+ if (!this._manager.isActive()) {
2762
+ resolve();
2763
+ }
2764
+ });
2765
+ });
2766
+ }
2767
+ getFailedTestAssertions(results) {
2768
+ const failedTestPaths = [];
2769
+ if (
2770
+ // skip if no failed tests
2771
+ results.numFailedTests === 0 ||
2772
+ // skip if missing test results
2773
+ !results.testResults ||
2774
+ // skip if unmatched snapshots are present
2775
+ results.snapshot.unmatched) {
2776
+ return failedTestPaths;
2777
+ }
2778
+ for (const testResult of results.testResults) {
2779
+ for (const result of testResult.testResults) {
2780
+ if (result.status === 'failed') {
2781
+ failedTestPaths.push({
2782
+ fullName: result.fullName,
2783
+ path: testResult.testFilePath
2784
+ });
2785
+ }
2786
+ }
2787
+ }
2788
+ return failedTestPaths;
2789
+ }
2790
+ }
2791
+ exports["default"] = FailedTestsInteractivePlugin;
2792
+
2793
+ /***/ },
2794
+
2795
+ /***/ "./src/plugins/Quit.ts"
2796
+ (__unused_webpack_module, exports) {
2797
+
2798
+
2799
+
2800
+ Object.defineProperty(exports, "__esModule", ({
2801
+ value: true
2802
+ }));
2803
+ exports["default"] = void 0;
2804
+ function _jestWatcher() {
2805
+ const data = require("@pkg-nec/jest-watcher");
2806
+ _jestWatcher = function () {
2807
+ return data;
2808
+ };
2809
+ return data;
2810
+ }
2811
+ /**
2812
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2813
+ *
2814
+ * This source code is licensed under the MIT license found in the
2815
+ * LICENSE file in the root directory of this source tree.
2816
+ */
2817
+
2818
+ class QuitPlugin extends _jestWatcher().BaseWatchPlugin {
2819
+ isInternal;
2820
+ constructor(options) {
2821
+ super(options);
2822
+ this.isInternal = true;
2823
+ }
2824
+ async run() {
2825
+ if (typeof this._stdin.setRawMode === 'function') {
2826
+ this._stdin.setRawMode(false);
2827
+ }
2828
+ this._stdout.write('\n');
2829
+ process.exit(0);
2830
+ }
2831
+ getUsageInfo() {
2832
+ return {
2833
+ key: 'q',
2834
+ prompt: 'quit watch mode'
2835
+ };
2836
+ }
2837
+ }
2838
+ var _default = exports["default"] = QuitPlugin;
2839
+
2840
+ /***/ },
2841
+
2842
+ /***/ "./src/plugins/TestNamePattern.ts"
2843
+ (__unused_webpack_module, exports, __webpack_require__) {
2844
+
2845
+
2846
+
2847
+ Object.defineProperty(exports, "__esModule", ({
2848
+ value: true
2849
+ }));
2850
+ exports["default"] = void 0;
2851
+ function _jestWatcher() {
2852
+ const data = require("@pkg-nec/jest-watcher");
2853
+ _jestWatcher = function () {
2854
+ return data;
2855
+ };
2856
+ return data;
2857
+ }
2858
+ var _TestNamePatternPrompt = _interopRequireDefault(__webpack_require__("./src/TestNamePatternPrompt.ts"));
2859
+ var _activeFiltersMessage = _interopRequireDefault(__webpack_require__("./src/lib/activeFiltersMessage.ts"));
2860
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2861
+ /**
2862
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2863
+ *
2864
+ * This source code is licensed under the MIT license found in the
2865
+ * LICENSE file in the root directory of this source tree.
2866
+ */
2867
+
2868
+ class TestNamePatternPlugin extends _jestWatcher().BaseWatchPlugin {
2869
+ _prompt;
2870
+ isInternal;
2871
+ constructor(options) {
2872
+ super(options);
2873
+ this._prompt = new (_jestWatcher().Prompt)();
2874
+ this.isInternal = true;
2875
+ }
2876
+ getUsageInfo() {
2877
+ return {
2878
+ key: 't',
2879
+ prompt: 'filter by a test name regex pattern'
2880
+ };
2881
+ }
2882
+ onKey(key) {
2883
+ this._prompt.put(key);
2884
+ }
2885
+ run(globalConfig, updateConfigAndRun) {
2886
+ return new Promise((resolve, reject) => {
2887
+ const testNamePatternPrompt = new _TestNamePatternPrompt.default(this._stdout, this._prompt);
2888
+ testNamePatternPrompt.run(value => {
2889
+ updateConfigAndRun({
2890
+ mode: 'watch',
2891
+ testNamePattern: value
2892
+ });
2893
+ resolve();
2894
+ }, reject, {
2895
+ header: (0, _activeFiltersMessage.default)(globalConfig)
2896
+ });
2897
+ });
2898
+ }
2899
+ }
2900
+ var _default = exports["default"] = TestNamePatternPlugin;
2901
+
2902
+ /***/ },
2903
+
2904
+ /***/ "./src/plugins/TestPathPattern.ts"
2905
+ (__unused_webpack_module, exports, __webpack_require__) {
2906
+
2907
+
2908
+
2909
+ Object.defineProperty(exports, "__esModule", ({
2910
+ value: true
2911
+ }));
2912
+ exports["default"] = void 0;
2913
+ function _jestWatcher() {
2914
+ const data = require("@pkg-nec/jest-watcher");
2915
+ _jestWatcher = function () {
2916
+ return data;
2917
+ };
2918
+ return data;
2919
+ }
2920
+ var _TestPathPatternPrompt = _interopRequireDefault(__webpack_require__("./src/TestPathPatternPrompt.ts"));
2921
+ var _activeFiltersMessage = _interopRequireDefault(__webpack_require__("./src/lib/activeFiltersMessage.ts"));
2922
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
2923
+ /**
2924
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2925
+ *
2926
+ * This source code is licensed under the MIT license found in the
2927
+ * LICENSE file in the root directory of this source tree.
2928
+ */
2929
+
2930
+ class TestPathPatternPlugin extends _jestWatcher().BaseWatchPlugin {
2931
+ _prompt;
2932
+ isInternal;
2933
+ constructor(options) {
2934
+ super(options);
2935
+ this._prompt = new (_jestWatcher().Prompt)();
2936
+ this.isInternal = true;
2937
+ }
2938
+ getUsageInfo() {
2939
+ return {
2940
+ key: 'p',
2941
+ prompt: 'filter by a filename regex pattern'
2942
+ };
2943
+ }
2944
+ onKey(key) {
2945
+ this._prompt.put(key);
2946
+ }
2947
+ run(globalConfig, updateConfigAndRun) {
2948
+ return new Promise((resolve, reject) => {
2949
+ const testPathPatternPrompt = new _TestPathPatternPrompt.default(this._stdout, this._prompt);
2950
+ testPathPatternPrompt.run(value => {
2951
+ updateConfigAndRun({
2952
+ mode: 'watch',
2953
+ testPathPatterns: [value]
2954
+ });
2955
+ resolve();
2956
+ }, reject, {
2957
+ header: (0, _activeFiltersMessage.default)(globalConfig)
2958
+ });
2959
+ });
2960
+ }
2961
+ }
2962
+ var _default = exports["default"] = TestPathPatternPlugin;
2963
+
2964
+ /***/ },
2965
+
2966
+ /***/ "./src/plugins/UpdateSnapshots.ts"
2967
+ (__unused_webpack_module, exports) {
2968
+
2969
+
2970
+
2971
+ Object.defineProperty(exports, "__esModule", ({
2972
+ value: true
2973
+ }));
2974
+ exports["default"] = void 0;
2975
+ function _jestWatcher() {
2976
+ const data = require("@pkg-nec/jest-watcher");
2977
+ _jestWatcher = function () {
2978
+ return data;
2979
+ };
2980
+ return data;
2981
+ }
2982
+ /**
2983
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
2984
+ *
2985
+ * This source code is licensed under the MIT license found in the
2986
+ * LICENSE file in the root directory of this source tree.
2987
+ */
2988
+
2989
+ class UpdateSnapshotsPlugin extends _jestWatcher().BaseWatchPlugin {
2990
+ _hasSnapshotFailure;
2991
+ isInternal;
2992
+ constructor(options) {
2993
+ super(options);
2994
+ this.isInternal = true;
2995
+ this._hasSnapshotFailure = false;
2996
+ }
2997
+ run(_globalConfig, updateConfigAndRun) {
2998
+ updateConfigAndRun({
2999
+ updateSnapshot: 'all'
3000
+ });
3001
+ return Promise.resolve(false);
3002
+ }
3003
+ apply(hooks) {
3004
+ hooks.onTestRunComplete(results => {
3005
+ this._hasSnapshotFailure = results.snapshot.failure;
3006
+ });
3007
+ }
3008
+ getUsageInfo() {
3009
+ if (this._hasSnapshotFailure) {
3010
+ return {
3011
+ key: 'u',
3012
+ prompt: 'update failing snapshots'
3013
+ };
3014
+ }
3015
+ return null;
3016
+ }
3017
+ }
3018
+ var _default = exports["default"] = UpdateSnapshotsPlugin;
3019
+
3020
+ /***/ },
3021
+
3022
+ /***/ "./src/plugins/UpdateSnapshotsInteractive.ts"
3023
+ (__unused_webpack_module, exports, __webpack_require__) {
3024
+
3025
+
3026
+
3027
+ Object.defineProperty(exports, "__esModule", ({
3028
+ value: true
3029
+ }));
3030
+ exports["default"] = void 0;
3031
+ function _jestWatcher() {
3032
+ const data = require("@pkg-nec/jest-watcher");
3033
+ _jestWatcher = function () {
3034
+ return data;
3035
+ };
3036
+ return data;
3037
+ }
3038
+ var _SnapshotInteractiveMode = _interopRequireDefault(__webpack_require__("./src/SnapshotInteractiveMode.ts"));
3039
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
3040
+ /**
3041
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3042
+ *
3043
+ * This source code is licensed under the MIT license found in the
3044
+ * LICENSE file in the root directory of this source tree.
3045
+ */
3046
+
3047
+ class UpdateSnapshotInteractivePlugin extends _jestWatcher().BaseWatchPlugin {
3048
+ _snapshotInteractiveMode = new _SnapshotInteractiveMode.default(this._stdout);
3049
+ _failedSnapshotTestAssertions = [];
3050
+ isInternal = true;
3051
+ getFailedSnapshotTestAssertions(testResults) {
3052
+ const failedTestPaths = [];
3053
+ if (testResults.numFailedTests === 0 || !testResults.testResults) {
3054
+ return failedTestPaths;
3055
+ }
3056
+ for (const testResult of testResults.testResults) {
3057
+ if (testResult.snapshot && testResult.snapshot.unmatched) {
3058
+ for (const result of testResult.testResults) {
3059
+ if (result.status === 'failed') {
3060
+ failedTestPaths.push({
3061
+ fullName: result.fullName,
3062
+ path: testResult.testFilePath
3063
+ });
3064
+ }
3065
+ }
3066
+ }
3067
+ }
3068
+ return failedTestPaths;
3069
+ }
3070
+ apply(hooks) {
3071
+ hooks.onTestRunComplete(results => {
3072
+ this._failedSnapshotTestAssertions = this.getFailedSnapshotTestAssertions(results);
3073
+ if (this._snapshotInteractiveMode.isActive()) {
3074
+ this._snapshotInteractiveMode.updateWithResults(results);
3075
+ }
3076
+ });
3077
+ }
3078
+ onKey(key) {
3079
+ if (this._snapshotInteractiveMode.isActive()) {
3080
+ this._snapshotInteractiveMode.put(key);
3081
+ }
3082
+ }
3083
+ run(_globalConfig, updateConfigAndRun) {
3084
+ if (this._failedSnapshotTestAssertions.length > 0) {
3085
+ return new Promise(resolve => {
3086
+ this._snapshotInteractiveMode.run(this._failedSnapshotTestAssertions, (assertion, shouldUpdateSnapshot) => {
3087
+ updateConfigAndRun({
3088
+ mode: 'watch',
3089
+ testNamePattern: assertion ? `^${assertion.fullName}$` : '',
3090
+ testPathPatterns: assertion ? [assertion.path] : [],
3091
+ updateSnapshot: shouldUpdateSnapshot ? 'all' : 'none'
3092
+ });
3093
+ if (!this._snapshotInteractiveMode.isActive()) {
3094
+ resolve();
3095
+ }
3096
+ });
3097
+ });
3098
+ } else {
3099
+ return Promise.resolve();
3100
+ }
3101
+ }
3102
+ getUsageInfo() {
3103
+ if (this._failedSnapshotTestAssertions?.length > 0) {
3104
+ return {
3105
+ key: 'i',
3106
+ prompt: 'update failing snapshots interactively'
3107
+ };
3108
+ }
3109
+ return null;
3110
+ }
3111
+ }
3112
+ var _default = exports["default"] = UpdateSnapshotInteractivePlugin;
3113
+
3114
+ /***/ },
3115
+
3116
+ /***/ "./src/runGlobalHook.ts"
3117
+ (__unused_webpack_module, exports) {
3118
+
3119
+
3120
+
3121
+ Object.defineProperty(exports, "__esModule", ({
3122
+ value: true
3123
+ }));
3124
+ exports["default"] = runGlobalHook;
3125
+ function _jestTransform() {
3126
+ const data = require("@pkg-nec/jest-transform");
3127
+ _jestTransform = function () {
3128
+ return data;
3129
+ };
3130
+ return data;
3131
+ }
3132
+ function _jestUtil() {
3133
+ const data = require("@pkg-nec/jest-util");
3134
+ _jestUtil = function () {
3135
+ return data;
3136
+ };
3137
+ return data;
3138
+ }
3139
+ function _prettyFormat() {
3140
+ const data = _interopRequireDefault(require("@pkg-nec/pretty-format"));
3141
+ _prettyFormat = function () {
3142
+ return data;
3143
+ };
3144
+ return data;
3145
+ }
3146
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
3147
+ /**
3148
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3149
+ *
3150
+ * This source code is licensed under the MIT license found in the
3151
+ * LICENSE file in the root directory of this source tree.
3152
+ */
3153
+
3154
+ async function runGlobalHook({
3155
+ allTests,
3156
+ globalConfig,
3157
+ moduleName
3158
+ }) {
3159
+ const globalModulePaths = new Set(allTests.map(test => test.context.config[moduleName]));
3160
+ if (globalConfig[moduleName]) {
3161
+ globalModulePaths.add(globalConfig[moduleName]);
3162
+ }
3163
+ if (globalModulePaths.size > 0) {
3164
+ for (const modulePath of globalModulePaths) {
3165
+ if (!modulePath) {
3166
+ continue;
3167
+ }
3168
+ const correctConfig = allTests.find(t => t.context.config[moduleName] === modulePath);
3169
+ const projectConfig = correctConfig ? correctConfig.context.config :
3170
+ // Fallback to first config
3171
+ allTests[0].context.config;
3172
+ const transformer = await (0, _jestTransform().createScriptTransformer)(projectConfig);
3173
+ try {
3174
+ await transformer.requireAndTranspileModule(modulePath, async globalModule => {
3175
+ if (typeof globalModule !== 'function') {
3176
+ throw new TypeError(`${moduleName} file must export a function at ${modulePath}`);
3177
+ }
3178
+ await globalModule(globalConfig, projectConfig);
3179
+ });
3180
+ } catch (error) {
3181
+ if ((0, _jestUtil().isError)(error) && (Object.getOwnPropertyDescriptor(error, 'message')?.writable || Object.getOwnPropertyDescriptor(Object.getPrototypeOf(error), 'message')?.writable)) {
3182
+ error.message = `Jest: Got error running ${moduleName} - ${modulePath}, reason: ${error.message}`;
3183
+ throw error;
3184
+ }
3185
+ throw new Error(`Jest: Got error running ${moduleName} - ${modulePath}, reason: ${(0, _prettyFormat().default)(error, {
3186
+ maxDepth: 3
3187
+ })}`);
3188
+ }
3189
+ }
3190
+ }
3191
+ }
3192
+
3193
+ /***/ },
3194
+
3195
+ /***/ "./src/runJest.ts"
3196
+ (__unused_webpack_module, exports, __webpack_require__) {
3197
+
3198
+
3199
+
3200
+ Object.defineProperty(exports, "__esModule", ({
3201
+ value: true
3202
+ }));
3203
+ exports["default"] = runJest;
3204
+ exports.printCollectedTestTree = void 0;
3205
+ function path() {
3206
+ const data = _interopRequireWildcard(require("node:path"));
3207
+ path = function () {
3208
+ return data;
3209
+ };
3210
+ return data;
3211
+ }
3212
+ function _nodePerf_hooks() {
3213
+ const data = require("node:perf_hooks");
3214
+ _nodePerf_hooks = function () {
3215
+ return data;
3216
+ };
3217
+ return data;
3218
+ }
3219
+ function _chalk() {
3220
+ const data = _interopRequireDefault(require("chalk"));
3221
+ _chalk = function () {
3222
+ return data;
3223
+ };
3224
+ return data;
3225
+ }
3226
+ function _exitX() {
3227
+ const data = _interopRequireDefault(require("exit-x"));
3228
+ _exitX = function () {
3229
+ return data;
3230
+ };
3231
+ return data;
3232
+ }
3233
+ function fs() {
3234
+ const data = _interopRequireWildcard(require("graceful-fs"));
3235
+ fs = function () {
3236
+ return data;
3237
+ };
3238
+ return data;
3239
+ }
3240
+ function _jestConsole() {
3241
+ const data = require("@pkg-nec/jest-console");
3242
+ _jestConsole = function () {
3243
+ return data;
3244
+ };
3245
+ return data;
3246
+ }
3247
+ function _jestReporters() {
3248
+ const data = require("@pkg-nec/jest-reporters");
3249
+ _jestReporters = function () {
3250
+ return data;
3251
+ };
3252
+ return data;
3253
+ }
3254
+ function _jestResolve() {
3255
+ const data = _interopRequireDefault(require("@pkg-nec/jest-resolve"));
3256
+ _jestResolve = function () {
3257
+ return data;
3258
+ };
3259
+ return data;
3260
+ }
3261
+ function _jestTestResult() {
3262
+ const data = require("@pkg-nec/jest-test-result");
3263
+ _jestTestResult = function () {
3264
+ return data;
3265
+ };
3266
+ return data;
3267
+ }
3268
+ function _jestUtil() {
3269
+ const data = require("@pkg-nec/jest-util");
3270
+ _jestUtil = function () {
3271
+ return data;
3272
+ };
3273
+ return data;
3274
+ }
3275
+ function _jestWatcher() {
3276
+ const data = require("@pkg-nec/jest-watcher");
3277
+ _jestWatcher = function () {
3278
+ return data;
3279
+ };
3280
+ return data;
3281
+ }
3282
+ var _SearchSource = _interopRequireDefault(__webpack_require__("./src/SearchSource.ts"));
3283
+ var _TestScheduler = __webpack_require__("./src/TestScheduler.ts");
3284
+ var _collectHandles = _interopRequireDefault(__webpack_require__("./src/collectHandles.ts"));
3285
+ var _getNoTestsFoundMessage = _interopRequireDefault(__webpack_require__("./src/getNoTestsFoundMessage.ts"));
3286
+ var _serializeToJSON = _interopRequireDefault(__webpack_require__("./src/lib/serializeToJSON.ts"));
3287
+ var _runGlobalHook = _interopRequireDefault(__webpack_require__("./src/runGlobalHook.ts"));
3288
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
3289
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
3290
+ /**
3291
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3292
+ *
3293
+ * This source code is licensed under the MIT license found in the
3294
+ * LICENSE file in the root directory of this source tree.
3295
+ */
3296
+
3297
+ const printCollectedTestTree = (testResults, outputStream) => {
3298
+ const printSuite = (suite, indent) => {
3299
+ if (suite.title) {
3300
+ outputStream.write(`${' '.repeat(indent)}${suite.title}\n`);
3301
+ }
3302
+ for (const t of suite.tests) {
3303
+ outputStream.write(`${' '.repeat(indent + 1)}${t.title}\n`);
3304
+ }
3305
+ for (const child of suite.suites) {
3306
+ printSuite(child, indent + 1);
3307
+ }
3308
+ };
3309
+ const root = _jestReporters().VerboseReporter.groupTestsBySuites(testResults);
3310
+ printSuite(root, 0);
3311
+ };
3312
+ exports.printCollectedTestTree = printCollectedTestTree;
3313
+ const getTestPaths = async (globalConfig, projectConfig, source, outputStream, changedFiles, jestHooks, filter) => {
3314
+ const data = await source.getTestPaths(globalConfig, projectConfig, changedFiles, filter);
3315
+ if (data.tests.length === 0 && globalConfig.onlyChanged && data.noSCM) {
3316
+ new (_jestConsole().CustomConsole)(outputStream, outputStream).log('Jest can only find uncommitted changed files in a git or hg ' + 'repository. If you make your project a git or hg ' + 'repository (`git init` or `hg init`), Jest will be able ' + 'to only run tests related to files changed since the last ' + 'commit.');
3317
+ }
3318
+ const shouldTestArray = await Promise.all(data.tests.map(test => jestHooks.shouldRunTestSuite({
3319
+ config: test.context.config,
3320
+ duration: test.duration,
3321
+ testPath: test.path
3322
+ })));
3323
+ const filteredTests = data.tests.filter((_test, i) => shouldTestArray[i]);
3324
+ return {
3325
+ ...data,
3326
+ allTests: filteredTests.length,
3327
+ tests: filteredTests
3328
+ };
3329
+ };
3330
+ const processResults = async (runResults, options) => {
3331
+ const {
3332
+ outputFile,
3333
+ json: isJSON,
3334
+ onComplete,
3335
+ outputStream,
3336
+ testResultsProcessor,
3337
+ collectHandles
3338
+ } = options;
3339
+ if (collectHandles) {
3340
+ runResults.openHandles = await collectHandles();
3341
+ } else {
3342
+ runResults.openHandles = [];
3343
+ }
3344
+ if (testResultsProcessor) {
3345
+ const processor = await (0, _jestUtil().requireOrImportModule)(testResultsProcessor);
3346
+ runResults = await processor(runResults);
3347
+ }
3348
+ if (isJSON) {
3349
+ const jsonString = (0, _serializeToJSON.default)((0, _jestTestResult().formatTestResults)(runResults));
3350
+ if (outputFile) {
3351
+ const cwd = (0, _jestUtil().tryRealpath)(process.cwd());
3352
+ const filePath = path().resolve(cwd, outputFile);
3353
+ fs().writeFileSync(filePath, `${jsonString}\n`);
3354
+ outputStream.write(`Test results written to: ${path().relative(cwd, filePath)}\n`);
3355
+ } else {
3356
+ process.stdout.write(`${jsonString}\n`);
3357
+ }
3358
+ }
3359
+ onComplete?.(runResults);
3360
+ };
3361
+ const testSchedulerContext = {
3362
+ firstRun: true,
3363
+ previousSuccess: true
3364
+ };
3365
+ async function runJest({
3366
+ contexts,
3367
+ globalConfig,
3368
+ outputStream,
3369
+ testWatcher,
3370
+ jestHooks = new (_jestWatcher().JestHook)().getEmitter(),
3371
+ startRun,
3372
+ changedFilesPromise,
3373
+ onComplete,
3374
+ failedTestsCache,
3375
+ filter
3376
+ }) {
3377
+ // Clear cache for required modules - there might be different resolutions
3378
+ // from Jest's config loading to running the tests
3379
+ _jestResolve().default.clearDefaultResolverCache();
3380
+ const Sequencer = await (0, _jestUtil().requireOrImportModule)(globalConfig.testSequencer);
3381
+ const sequencer = new Sequencer({
3382
+ contexts,
3383
+ globalConfig
3384
+ });
3385
+ let allTests = [];
3386
+ if (changedFilesPromise && globalConfig.watch) {
3387
+ const {
3388
+ repos
3389
+ } = await changedFilesPromise;
3390
+ const noSCM = Object.keys(repos).every(scm => repos[scm].size === 0);
3391
+ if (noSCM) {
3392
+ process.stderr.write(`\n${_chalk().default.bold('--watch')} is not supported without git/hg, please use --watchAll\n`);
3393
+ (0, _exitX().default)(1);
3394
+ }
3395
+ }
3396
+ const searchSources = contexts.map(context => new _SearchSource.default(context));
3397
+ _nodePerf_hooks().performance.mark('jest/getTestPaths:start');
3398
+ const testRunData = await Promise.all(contexts.map(async (context, index) => {
3399
+ const searchSource = searchSources[index];
3400
+ const matches = await getTestPaths(globalConfig, context.config, searchSource, outputStream, changedFilesPromise && (await changedFilesPromise), jestHooks, filter);
3401
+ allTests = [...allTests, ...matches.tests];
3402
+ return {
3403
+ context,
3404
+ matches
3405
+ };
3406
+ }));
3407
+ _nodePerf_hooks().performance.mark('jest/getTestPaths:end');
3408
+ if (globalConfig.shard) {
3409
+ if (typeof sequencer.shard !== 'function') {
3410
+ throw new TypeError(`Shard ${globalConfig.shard.shardIndex}/${globalConfig.shard.shardCount} requested, but test sequencer ${Sequencer.name} in ${globalConfig.testSequencer} has no shard method.`);
3411
+ }
3412
+ allTests = await sequencer.shard(allTests, globalConfig.shard);
3413
+ }
3414
+ allTests = await sequencer.sort(allTests);
3415
+ if (globalConfig.onlyFailures) {
3416
+ if (failedTestsCache) {
3417
+ allTests = failedTestsCache.filterTests(allTests);
3418
+ } else {
3419
+ allTests = await sequencer.allFailedTests(allTests);
3420
+ }
3421
+ }
3422
+ if (globalConfig.listTests) {
3423
+ const testsPaths = [...new Set(allTests.map(test => test.path))];
3424
+ let testsListOutput;
3425
+ if (globalConfig.json) {
3426
+ testsListOutput = JSON.stringify(testsPaths);
3427
+ } else {
3428
+ testsListOutput = testsPaths.join('\n');
3429
+ }
3430
+ if (globalConfig.outputFile) {
3431
+ const outputFile = path().resolve(process.cwd(), globalConfig.outputFile);
3432
+ fs().writeFileSync(outputFile, testsListOutput, 'utf8');
3433
+ } else {
3434
+ // eslint-disable-next-line no-console
3435
+ console.log(testsListOutput);
3436
+ }
3437
+ onComplete?.((0, _jestTestResult().makeEmptyAggregatedTestResult)());
3438
+ return;
3439
+ }
3440
+ const hasTests = allTests.length > 0;
3441
+ if (globalConfig.collectTests) {
3442
+ if (!hasTests) {
3443
+ // eslint-disable-next-line no-console
3444
+ console.log('No tests found.');
3445
+ onComplete?.((0, _jestTestResult().makeEmptyAggregatedTestResult)());
3446
+ return;
3447
+ }
3448
+
3449
+ // Suppress reporters; circus collects tests without executing.
3450
+ const collectTestsConfig = Object.freeze({
3451
+ ...globalConfig,
3452
+ collectCoverage: false,
3453
+ reporters: [],
3454
+ silent: true
3455
+ });
3456
+ const scheduler = await (0, _TestScheduler.createTestScheduler)(collectTestsConfig, {
3457
+ startRun,
3458
+ ...testSchedulerContext
3459
+ });
3460
+ const results = await scheduler.scheduleTests(allTests, testWatcher);
3461
+ if (!globalConfig.json) {
3462
+ for (const testResult of results.testResults) {
3463
+ if (testResult.testResults.length > 0) {
3464
+ outputStream.write(`${testResult.testFilePath}\n`);
3465
+ printCollectedTestTree(testResult.testResults, outputStream);
3466
+ }
3467
+ }
3468
+ }
3469
+ await processResults(results, {
3470
+ json: globalConfig.json,
3471
+ onComplete,
3472
+ outputFile: globalConfig.outputFile,
3473
+ outputStream,
3474
+ testResultsProcessor: globalConfig.testResultsProcessor
3475
+ });
3476
+ return;
3477
+ }
3478
+ if (!hasTests) {
3479
+ const {
3480
+ exitWith0,
3481
+ message: noTestsFoundMessage
3482
+ } = (0, _getNoTestsFoundMessage.default)(testRunData, globalConfig);
3483
+ if (exitWith0) {
3484
+ new (_jestConsole().CustomConsole)(outputStream, outputStream).log(noTestsFoundMessage);
3485
+ } else {
3486
+ new (_jestConsole().CustomConsole)(outputStream, outputStream).error(noTestsFoundMessage);
3487
+ (0, _exitX().default)(1);
3488
+ }
3489
+ } else if (allTests.length === 1 && globalConfig.silent !== true && globalConfig.verbose !== false) {
3490
+ const newConfig = {
3491
+ ...globalConfig,
3492
+ verbose: true
3493
+ };
3494
+ globalConfig = Object.freeze(newConfig);
3495
+ }
3496
+ let collectHandles;
3497
+ if (globalConfig.detectOpenHandles) {
3498
+ collectHandles = (0, _collectHandles.default)();
3499
+ }
3500
+ if (hasTests) {
3501
+ _nodePerf_hooks().performance.mark('jest/globalSetup:start');
3502
+ await (0, _runGlobalHook.default)({
3503
+ allTests,
3504
+ globalConfig,
3505
+ moduleName: 'globalSetup'
3506
+ });
3507
+ _nodePerf_hooks().performance.mark('jest/globalSetup:end');
3508
+ }
3509
+ if (changedFilesPromise) {
3510
+ const changedFilesInfo = await changedFilesPromise;
3511
+ if (changedFilesInfo.changedFiles) {
3512
+ testSchedulerContext.changedFiles = changedFilesInfo.changedFiles;
3513
+ const relatedFiles = await Promise.all(contexts.map(async (_, index) => {
3514
+ const searchSource = searchSources[index];
3515
+ return searchSource.findRelatedSourcesFromTestsInChangedFiles(changedFilesInfo);
3516
+ }));
3517
+ const sourcesRelatedToTestsInChangedFilesArray = relatedFiles.flat();
3518
+ testSchedulerContext.sourcesRelatedToTestsInChangedFiles = new Set(sourcesRelatedToTestsInChangedFilesArray);
3519
+ }
3520
+ }
3521
+ const scheduler = await (0, _TestScheduler.createTestScheduler)(globalConfig, {
3522
+ startRun,
3523
+ ...testSchedulerContext
3524
+ });
3525
+ _nodePerf_hooks().performance.mark('jest/scheduleAndRun:start', {
3526
+ detail: {
3527
+ numTests: allTests.length
3528
+ }
3529
+ });
3530
+ const results = await scheduler.scheduleTests(allTests, testWatcher);
3531
+ _nodePerf_hooks().performance.mark('jest/scheduleAndRun:end');
3532
+ _nodePerf_hooks().performance.mark('jest/cacheResults:start');
3533
+ sequencer.cacheResults(allTests, results);
3534
+ _nodePerf_hooks().performance.mark('jest/cacheResults:end');
3535
+ if (hasTests) {
3536
+ _nodePerf_hooks().performance.mark('jest/globalTeardown:start');
3537
+ await (0, _runGlobalHook.default)({
3538
+ allTests,
3539
+ globalConfig,
3540
+ moduleName: 'globalTeardown'
3541
+ });
3542
+ _nodePerf_hooks().performance.mark('jest/globalTeardown:end');
3543
+ }
3544
+ _nodePerf_hooks().performance.mark('jest/processResults:start');
3545
+ await processResults(results, {
3546
+ collectHandles,
3547
+ json: globalConfig.json,
3548
+ onComplete,
3549
+ outputFile: globalConfig.outputFile,
3550
+ outputStream,
3551
+ testResultsProcessor: globalConfig.testResultsProcessor
3552
+ });
3553
+ _nodePerf_hooks().performance.mark('jest/processResults:end');
3554
+ }
3555
+
3556
+ /***/ },
3557
+
3558
+ /***/ "./src/testSchedulerHelper.ts"
3559
+ (__unused_webpack_module, exports) {
3560
+
3561
+
3562
+
3563
+ Object.defineProperty(exports, "__esModule", ({
3564
+ value: true
3565
+ }));
3566
+ exports.shouldRunInBand = shouldRunInBand;
3567
+ /**
3568
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3569
+ *
3570
+ * This source code is licensed under the MIT license found in the
3571
+ * LICENSE file in the root directory of this source tree.
3572
+ */
3573
+
3574
+ const SLOW_TEST_TIME = 1000;
3575
+ function shouldRunInBand(tests, timings, {
3576
+ detectOpenHandles,
3577
+ maxWorkers,
3578
+ runInBand,
3579
+ watch,
3580
+ watchAll,
3581
+ workerIdleMemoryLimit
3582
+ }) {
3583
+ // If user asked for run in band, respect that.
3584
+ // detectOpenHandles makes no sense without runInBand, because it cannot detect leaks in workers
3585
+ if (runInBand || detectOpenHandles) {
3586
+ return true;
3587
+ }
3588
+
3589
+ /*
3590
+ * If we are using watch/watchAll mode, don't schedule anything in the main
3591
+ * thread to keep the TTY responsive and to prevent watch mode crashes caused
3592
+ * by leaks (improper test teardown).
3593
+ */
3594
+ if (watch || watchAll) {
3595
+ return false;
3596
+ }
3597
+
3598
+ /*
3599
+ * Otherwise, run in band if we only have one test or one worker available.
3600
+ * Also, if we are confident from previous runs that the tests will finish
3601
+ * quickly we also run in band to reduce the overhead of spawning workers.
3602
+ */
3603
+ const areFastTests = timings.every(timing => timing < SLOW_TEST_TIME);
3604
+ const oneWorkerOrLess = maxWorkers <= 1;
3605
+ const oneTestOrLess = tests.length <= 1;
3606
+ return (
3607
+ // When specifying a memory limit, workers should be used
3608
+ workerIdleMemoryLimit === undefined && (oneWorkerOrLess || oneTestOrLess || tests.length <= 20 && timings.length > 0 && areFastTests)
3609
+ );
3610
+ }
3611
+
3612
+ /***/ },
3613
+
3614
+ /***/ "./src/version.ts"
3615
+ (__unused_webpack_module, exports, __webpack_require__) {
3616
+
3617
+
3618
+
3619
+ Object.defineProperty(exports, "__esModule", ({
3620
+ value: true
3621
+ }));
3622
+ exports["default"] = getVersion;
3623
+ /**
3624
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3625
+ *
3626
+ * This source code is licensed under the MIT license found in the
3627
+ * LICENSE file in the root directory of this source tree.
3628
+ */
3629
+
3630
+ // Cannot be `import` as it's not under TS root dir
3631
+ const {
3632
+ version: VERSION
3633
+ } = __webpack_require__("./package.json");
3634
+ function getVersion() {
3635
+ return VERSION;
3636
+ }
3637
+
3638
+ /***/ },
3639
+
3640
+ /***/ "./src/watch.ts"
3641
+ (__unused_webpack_module, exports, __webpack_require__) {
3642
+
3643
+
3644
+
3645
+ Object.defineProperty(exports, "__esModule", ({
3646
+ value: true
3647
+ }));
3648
+ exports["default"] = watch;
3649
+ function path() {
3650
+ const data = _interopRequireWildcard(require("node:path"));
3651
+ path = function () {
3652
+ return data;
3653
+ };
3654
+ return data;
3655
+ }
3656
+ function _ansiEscapes() {
3657
+ const data = _interopRequireDefault(require("ansi-escapes"));
3658
+ _ansiEscapes = function () {
3659
+ return data;
3660
+ };
3661
+ return data;
3662
+ }
3663
+ function _chalk() {
3664
+ const data = _interopRequireDefault(require("chalk"));
3665
+ _chalk = function () {
3666
+ return data;
3667
+ };
3668
+ return data;
3669
+ }
3670
+ function _exitX() {
3671
+ const data = _interopRequireDefault(require("exit-x"));
3672
+ _exitX = function () {
3673
+ return data;
3674
+ };
3675
+ return data;
3676
+ }
3677
+ function _slash() {
3678
+ const data = _interopRequireDefault(require("slash"));
3679
+ _slash = function () {
3680
+ return data;
3681
+ };
3682
+ return data;
3683
+ }
3684
+ function _jestMessageUtil() {
3685
+ const data = require("@pkg-nec/jest-message-util");
3686
+ _jestMessageUtil = function () {
3687
+ return data;
3688
+ };
3689
+ return data;
3690
+ }
3691
+ function _jestPattern() {
3692
+ const data = require("@pkg-nec/jest-pattern");
3693
+ _jestPattern = function () {
3694
+ return data;
3695
+ };
3696
+ return data;
3697
+ }
3698
+ function _jestUtil() {
3699
+ const data = require("@pkg-nec/jest-util");
3700
+ _jestUtil = function () {
3701
+ return data;
3702
+ };
3703
+ return data;
3704
+ }
3705
+ function _jestValidate() {
3706
+ const data = require("@pkg-nec/jest-validate");
3707
+ _jestValidate = function () {
3708
+ return data;
3709
+ };
3710
+ return data;
3711
+ }
3712
+ function _jestWatcher() {
3713
+ const data = require("@pkg-nec/jest-watcher");
3714
+ _jestWatcher = function () {
3715
+ return data;
3716
+ };
3717
+ return data;
3718
+ }
3719
+ var _FailedTestsCache = _interopRequireDefault(__webpack_require__("./src/FailedTestsCache.ts"));
3720
+ var _SearchSource = _interopRequireDefault(__webpack_require__("./src/SearchSource.ts"));
3721
+ var _getChangedFilesPromise = _interopRequireDefault(__webpack_require__("./src/getChangedFilesPromise.ts"));
3722
+ var _activeFiltersMessage = _interopRequireDefault(__webpack_require__("./src/lib/activeFiltersMessage.ts"));
3723
+ var _createContext = _interopRequireDefault(__webpack_require__("./src/lib/createContext.ts"));
3724
+ var _isValidPath = _interopRequireDefault(__webpack_require__("./src/lib/isValidPath.ts"));
3725
+ var _updateGlobalConfig = _interopRequireDefault(__webpack_require__("./src/lib/updateGlobalConfig.ts"));
3726
+ var _watchPluginsHelpers = __webpack_require__("./src/lib/watchPluginsHelpers.ts");
3727
+ var _FailedTestsInteractive = _interopRequireDefault(__webpack_require__("./src/plugins/FailedTestsInteractive.ts"));
3728
+ var _Quit = _interopRequireDefault(__webpack_require__("./src/plugins/Quit.ts"));
3729
+ var _TestNamePattern = _interopRequireDefault(__webpack_require__("./src/plugins/TestNamePattern.ts"));
3730
+ var _TestPathPattern = _interopRequireDefault(__webpack_require__("./src/plugins/TestPathPattern.ts"));
3731
+ var _UpdateSnapshots = _interopRequireDefault(__webpack_require__("./src/plugins/UpdateSnapshots.ts"));
3732
+ var _UpdateSnapshotsInteractive = _interopRequireDefault(__webpack_require__("./src/plugins/UpdateSnapshotsInteractive.ts"));
3733
+ var _runJest = _interopRequireDefault(__webpack_require__("./src/runJest.ts"));
3734
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
3735
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
3736
+ /**
3737
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3738
+ *
3739
+ * This source code is licensed under the MIT license found in the
3740
+ * LICENSE file in the root directory of this source tree.
3741
+ */
3742
+
3743
+ const {
3744
+ print: preRunMessagePrint
3745
+ } = _jestUtil().preRunMessage;
3746
+ let hasExitListener = false;
3747
+ const INTERNAL_PLUGINS = [_FailedTestsInteractive.default, _TestPathPattern.default, _TestNamePattern.default, _UpdateSnapshots.default, _UpdateSnapshotsInteractive.default, _Quit.default];
3748
+ const RESERVED_KEY_PLUGINS = new Map([[_UpdateSnapshots.default, {
3749
+ forbiddenOverwriteMessage: 'updating snapshots',
3750
+ key: 'u'
3751
+ }], [_UpdateSnapshotsInteractive.default, {
3752
+ forbiddenOverwriteMessage: 'updating snapshots interactively',
3753
+ key: 'i'
3754
+ }], [_Quit.default, {
3755
+ forbiddenOverwriteMessage: 'quitting watch mode'
3756
+ }]]);
3757
+ async function watch(initialGlobalConfig, contexts, outputStream, hasteMapInstances, stdin = process.stdin, hooks = new (_jestWatcher().JestHook)(), filter) {
3758
+ // `globalConfig` will be constantly updated and reassigned as a result of
3759
+ // watch mode interactions.
3760
+ let globalConfig = initialGlobalConfig;
3761
+ let activePlugin;
3762
+ globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
3763
+ mode: globalConfig.watch ? 'watch' : 'watchAll',
3764
+ passWithNoTests: true
3765
+ });
3766
+ const updateConfigAndRun = async ({
3767
+ bail,
3768
+ changedSince,
3769
+ collectCoverage,
3770
+ collectCoverageFrom,
3771
+ coverageDirectory,
3772
+ coverageReporters,
3773
+ findRelatedTests,
3774
+ mode,
3775
+ nonFlagArgs,
3776
+ notify,
3777
+ notifyMode,
3778
+ onlyFailures,
3779
+ reporters,
3780
+ testNamePattern,
3781
+ testPathPatterns,
3782
+ updateSnapshot,
3783
+ verbose
3784
+ } = {}) => {
3785
+ const previousUpdateSnapshot = globalConfig.updateSnapshot;
3786
+ globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
3787
+ bail,
3788
+ changedSince,
3789
+ collectCoverage,
3790
+ collectCoverageFrom,
3791
+ coverageDirectory,
3792
+ coverageReporters,
3793
+ findRelatedTests,
3794
+ mode,
3795
+ nonFlagArgs,
3796
+ notify,
3797
+ notifyMode,
3798
+ onlyFailures,
3799
+ reporters,
3800
+ testNamePattern,
3801
+ testPathPatterns,
3802
+ updateSnapshot,
3803
+ verbose
3804
+ });
3805
+ startRun(globalConfig);
3806
+ globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
3807
+ // updateSnapshot is not sticky after a run.
3808
+ updateSnapshot: previousUpdateSnapshot === 'all' ? 'none' : previousUpdateSnapshot
3809
+ });
3810
+ };
3811
+ const watchPlugins = INTERNAL_PLUGINS.map(InternalPlugin => new InternalPlugin({
3812
+ stdin,
3813
+ stdout: outputStream
3814
+ }));
3815
+ for (const plugin of watchPlugins) {
3816
+ const hookSubscriber = hooks.getSubscriber();
3817
+ if (plugin.apply) {
3818
+ plugin.apply(hookSubscriber);
3819
+ }
3820
+ }
3821
+ if (globalConfig.watchPlugins != null) {
3822
+ const watchPluginKeys = new Map();
3823
+ for (const plugin of watchPlugins) {
3824
+ const reservedInfo = RESERVED_KEY_PLUGINS.get(plugin.constructor) || {};
3825
+ const key = reservedInfo.key || getPluginKey(plugin, globalConfig);
3826
+ if (!key) {
3827
+ continue;
3828
+ }
3829
+ const {
3830
+ forbiddenOverwriteMessage
3831
+ } = reservedInfo;
3832
+ watchPluginKeys.set(key, {
3833
+ forbiddenOverwriteMessage,
3834
+ overwritable: forbiddenOverwriteMessage == null,
3835
+ plugin
3836
+ });
3837
+ }
3838
+ for (const pluginWithConfig of globalConfig.watchPlugins) {
3839
+ let plugin;
3840
+ try {
3841
+ const ThirdPartyPlugin = await (0, _jestUtil().requireOrImportModule)(pluginWithConfig.path);
3842
+ plugin = new ThirdPartyPlugin({
3843
+ config: pluginWithConfig.config,
3844
+ stdin,
3845
+ stdout: outputStream
3846
+ });
3847
+ } catch (error) {
3848
+ const errorWithContext = new Error(`Failed to initialize watch plugin "${_chalk().default.bold((0, _slash().default)(path().relative(process.cwd(), pluginWithConfig.path)))}":\n\n${(0, _jestMessageUtil().formatExecError)(error, contexts[0].config, {
3849
+ noStackTrace: false
3850
+ })}`);
3851
+ delete errorWithContext.stack;
3852
+ throw errorWithContext;
3853
+ }
3854
+ checkForConflicts(watchPluginKeys, plugin, globalConfig);
3855
+ const hookSubscriber = hooks.getSubscriber();
3856
+ if (plugin.apply) {
3857
+ plugin.apply(hookSubscriber);
3858
+ }
3859
+ watchPlugins.push(plugin);
3860
+ }
3861
+ }
3862
+ const failedTestsCache = new _FailedTestsCache.default();
3863
+ let searchSources = contexts.map(context => ({
3864
+ context,
3865
+ searchSource: new _SearchSource.default(context)
3866
+ }));
3867
+ let isRunning = false;
3868
+ let testWatcher;
3869
+ let shouldDisplayWatchUsage = true;
3870
+ let isWatchUsageDisplayed = false;
3871
+ const emitFileChange = () => {
3872
+ if (hooks.isUsed('onFileChange')) {
3873
+ const projects = searchSources.map(({
3874
+ context,
3875
+ searchSource
3876
+ }) => ({
3877
+ config: context.config,
3878
+ testPaths: searchSource.findMatchingTests(new (_jestPattern().TestPathPatterns)([]).toExecutor({
3879
+ rootDir: context.config.rootDir
3880
+ })).tests.map(t => t.path)
3881
+ }));
3882
+ hooks.getEmitter().onFileChange({
3883
+ projects
3884
+ });
3885
+ }
3886
+ };
3887
+ emitFileChange();
3888
+ for (const [index, hasteMapInstance] of hasteMapInstances.entries()) {
3889
+ hasteMapInstance.on('change', ({
3890
+ eventsQueue,
3891
+ hasteFS,
3892
+ moduleMap
3893
+ }) => {
3894
+ const validPaths = eventsQueue.filter(({
3895
+ filePath
3896
+ }) => (0, _isValidPath.default)(globalConfig, filePath));
3897
+ if (validPaths.length > 0) {
3898
+ const context = contexts[index] = (0, _createContext.default)(contexts[index].config, {
3899
+ hasteFS,
3900
+ moduleMap
3901
+ });
3902
+ activePlugin = null;
3903
+ searchSources = [...searchSources];
3904
+ searchSources[index] = {
3905
+ context,
3906
+ searchSource: new _SearchSource.default(context)
3907
+ };
3908
+ emitFileChange();
3909
+ startRun(globalConfig);
3910
+ }
3911
+ });
3912
+ }
3913
+ if (!hasExitListener) {
3914
+ hasExitListener = true;
3915
+ process.on('exit', () => {
3916
+ if (activePlugin) {
3917
+ outputStream.write(_ansiEscapes().default.cursorDown());
3918
+ outputStream.write(_ansiEscapes().default.eraseDown);
3919
+ }
3920
+ });
3921
+ }
3922
+ const startRun = async globalConfig => {
3923
+ if (isRunning) {
3924
+ return;
3925
+ }
3926
+ testWatcher = new (_jestWatcher().TestWatcher)({
3927
+ isWatchMode: true
3928
+ });
3929
+ if (_jestUtil().isInteractive) {
3930
+ outputStream.write(_jestUtil().specialChars.CLEAR);
3931
+ }
3932
+ preRunMessagePrint(outputStream);
3933
+ isRunning = true;
3934
+ const configs = contexts.map(context => context.config);
3935
+ const changedFilesPromise = (0, _getChangedFilesPromise.default)(globalConfig, configs);
3936
+ try {
3937
+ await (0, _runJest.default)({
3938
+ changedFilesPromise,
3939
+ contexts,
3940
+ failedTestsCache,
3941
+ filter,
3942
+ globalConfig,
3943
+ jestHooks: hooks.getEmitter(),
3944
+ onComplete: results => {
3945
+ isRunning = false;
3946
+ hooks.getEmitter().onTestRunComplete(results);
3947
+
3948
+ // Create a new testWatcher instance so that re-runs won't be blocked.
3949
+ // The old instance that was passed to Jest will still be interrupted
3950
+ // and prevent test runs from the previous run.
3951
+ testWatcher = new (_jestWatcher().TestWatcher)({
3952
+ isWatchMode: true
3953
+ });
3954
+
3955
+ // Do not show any Watch Usage related stuff when running in a
3956
+ // non-interactive environment
3957
+ if (_jestUtil().isInteractive) {
3958
+ if (shouldDisplayWatchUsage) {
3959
+ outputStream.write(usage(globalConfig, watchPlugins));
3960
+ shouldDisplayWatchUsage = false; // hide Watch Usage after first run
3961
+ isWatchUsageDisplayed = true;
3962
+ } else {
3963
+ outputStream.write(showToggleUsagePrompt());
3964
+ shouldDisplayWatchUsage = false;
3965
+ isWatchUsageDisplayed = false;
3966
+ }
3967
+ } else {
3968
+ outputStream.write('\n');
3969
+ }
3970
+ failedTestsCache.setTestResults(results.testResults);
3971
+ },
3972
+ outputStream,
3973
+ startRun,
3974
+ testWatcher
3975
+ });
3976
+ } catch (error) {
3977
+ // Errors thrown inside `runJest`, e.g. by resolvers, are caught here for
3978
+ // continuous watch mode execution. We need to reprint them to the
3979
+ // terminal and give just a little bit of extra space so they fit below
3980
+ // `preRunMessagePrint` message nicely.
3981
+ console.error(`\n\n${(0, _jestMessageUtil().formatExecError)(error, contexts[0].config, {
3982
+ noStackTrace: false
3983
+ })}`);
3984
+ }
3985
+ };
3986
+ const onKeypress = key => {
3987
+ if (key === _jestWatcher().KEYS.CONTROL_C || key === _jestWatcher().KEYS.CONTROL_D) {
3988
+ if (typeof stdin.setRawMode === 'function') {
3989
+ stdin.setRawMode(false);
3990
+ }
3991
+ outputStream.write('\n');
3992
+ (0, _exitX().default)(0);
3993
+ return;
3994
+ }
3995
+ if (activePlugin != null && activePlugin.onKey) {
3996
+ // if a plugin is activate, Jest should let it handle keystrokes, so ignore
3997
+ // them here
3998
+ activePlugin.onKey(key);
3999
+ return;
4000
+ }
4001
+
4002
+ // Abort test run
4003
+ const pluginKeys = (0, _watchPluginsHelpers.getSortedUsageRows)(watchPlugins, globalConfig).map(usage => Number(usage.key).toString(16));
4004
+ if (isRunning && testWatcher && ['q', _jestWatcher().KEYS.ENTER, 'a', 'o', 'f', ...pluginKeys].includes(key)) {
4005
+ testWatcher.setState({
4006
+ interrupted: true
4007
+ });
4008
+ return;
4009
+ }
4010
+ const matchingWatchPlugin = (0, _watchPluginsHelpers.filterInteractivePlugins)(watchPlugins, globalConfig).find(plugin => getPluginKey(plugin, globalConfig) === key);
4011
+ if (matchingWatchPlugin != null) {
4012
+ if (isRunning) {
4013
+ testWatcher.setState({
4014
+ interrupted: true
4015
+ });
4016
+ return;
4017
+ }
4018
+ // "activate" the plugin, which has jest ignore keystrokes so the plugin
4019
+ // can handle them
4020
+ activePlugin = matchingWatchPlugin;
4021
+ if (activePlugin.run) {
4022
+ activePlugin.run(globalConfig, updateConfigAndRun).then(async shouldRerun => {
4023
+ activePlugin = null;
4024
+ if (shouldRerun) {
4025
+ await updateConfigAndRun();
4026
+ }
4027
+ }, () => {
4028
+ activePlugin = null;
4029
+ onCancelPatternPrompt();
4030
+ });
4031
+ } else {
4032
+ activePlugin = null;
4033
+ }
4034
+ }
4035
+ switch (key) {
4036
+ case _jestWatcher().KEYS.ENTER:
4037
+ startRun(globalConfig);
4038
+ break;
4039
+ case 'a':
4040
+ globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
4041
+ mode: 'watchAll',
4042
+ testNamePattern: '',
4043
+ testPathPatterns: []
4044
+ });
4045
+ startRun(globalConfig);
4046
+ break;
4047
+ case 'c':
4048
+ updateConfigAndRun({
4049
+ mode: 'watch',
4050
+ testNamePattern: '',
4051
+ testPathPatterns: []
4052
+ });
4053
+ break;
4054
+ case 'f':
4055
+ globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
4056
+ onlyFailures: !globalConfig.onlyFailures
4057
+ });
4058
+ startRun(globalConfig);
4059
+ break;
4060
+ case 'o':
4061
+ globalConfig = (0, _updateGlobalConfig.default)(globalConfig, {
4062
+ mode: 'watch',
4063
+ testNamePattern: '',
4064
+ testPathPatterns: []
4065
+ });
4066
+ startRun(globalConfig);
4067
+ break;
4068
+ case '?':
4069
+ break;
4070
+ case 'w':
4071
+ if (!shouldDisplayWatchUsage && !isWatchUsageDisplayed) {
4072
+ outputStream.write(_ansiEscapes().default.cursorUp());
4073
+ outputStream.write(_ansiEscapes().default.eraseDown);
4074
+ outputStream.write(usage(globalConfig, watchPlugins));
4075
+ isWatchUsageDisplayed = true;
4076
+ shouldDisplayWatchUsage = false;
4077
+ }
4078
+ break;
4079
+ }
4080
+ };
4081
+ const onCancelPatternPrompt = () => {
4082
+ outputStream.write(_ansiEscapes().default.cursorHide);
4083
+ outputStream.write(_jestUtil().specialChars.CLEAR);
4084
+ outputStream.write(usage(globalConfig, watchPlugins));
4085
+ outputStream.write(_ansiEscapes().default.cursorShow);
4086
+ };
4087
+ if (typeof stdin.setRawMode === 'function') {
4088
+ stdin.setRawMode(true);
4089
+ stdin.resume();
4090
+ stdin.setEncoding('utf8');
4091
+ stdin.on('data', onKeypress);
4092
+ }
4093
+ startRun(globalConfig);
4094
+ }
4095
+ const checkForConflicts = (watchPluginKeys, plugin, globalConfig) => {
4096
+ const key = getPluginKey(plugin, globalConfig);
4097
+ if (!key) {
4098
+ return;
4099
+ }
4100
+ const conflictor = watchPluginKeys.get(key);
4101
+ if (!conflictor || conflictor.overwritable) {
4102
+ watchPluginKeys.set(key, {
4103
+ overwritable: false,
4104
+ plugin
4105
+ });
4106
+ return;
4107
+ }
4108
+ let error;
4109
+ if (conflictor.forbiddenOverwriteMessage) {
4110
+ error = `
4111
+ Watch plugin ${_chalk().default.bold.red(getPluginIdentifier(plugin))} attempted to register key ${_chalk().default.bold.red(`<${key}>`)},
4112
+ that is reserved internally for ${_chalk().default.bold.red(conflictor.forbiddenOverwriteMessage)}.
4113
+ Please change the configuration key for this plugin.`.trim();
4114
+ } else {
4115
+ const plugins = [conflictor.plugin, plugin].map(p => _chalk().default.bold.red(getPluginIdentifier(p))).join(' and ');
4116
+ error = `
4117
+ Watch plugins ${plugins} both attempted to register key ${_chalk().default.bold.red(`<${key}>`)}.
4118
+ Please change the key configuration for one of the conflicting plugins to avoid overlap.`.trim();
4119
+ }
4120
+ throw new (_jestValidate().ValidationError)('Watch plugin configuration error', error);
4121
+ };
4122
+ const getPluginIdentifier = plugin =>
4123
+ // This breaks as `displayName` is not defined as a static, but since
4124
+ // WatchPlugin is an interface, and it is my understanding interface
4125
+ // static fields are not definable anymore, no idea how to circumvent
4126
+ // this :-(
4127
+ // @ts-expect-error: leave `displayName` be.
4128
+ plugin.constructor.displayName || plugin.constructor.name;
4129
+ const getPluginKey = (plugin, globalConfig) => {
4130
+ if (typeof plugin.getUsageInfo === 'function') {
4131
+ return (plugin.getUsageInfo(globalConfig) || {
4132
+ key: null
4133
+ }).key;
4134
+ }
4135
+ return null;
4136
+ };
4137
+ const usage = (globalConfig, watchPlugins, delimiter = '\n') => {
4138
+ const testPathPatterns = globalConfig.testPathPatterns;
4139
+ const messages = [(0, _activeFiltersMessage.default)(globalConfig), testPathPatterns.isSet() || globalConfig.testNamePattern ? `${_chalk().default.dim(' \u203A Press ')}c${_chalk().default.dim(' to clear filters.')}` : null, `\n${_chalk().default.bold('Watch Usage')}`, globalConfig.watch ? `${_chalk().default.dim(' \u203A Press ')}a${_chalk().default.dim(' to run all tests.')}` : null, globalConfig.onlyFailures ? `${_chalk().default.dim(' \u203A Press ')}f${_chalk().default.dim(' to quit "only failed tests" mode.')}` : `${_chalk().default.dim(' \u203A Press ')}f${_chalk().default.dim(' to run only failed tests.')}`, (globalConfig.watchAll || testPathPatterns.isSet() || globalConfig.testNamePattern) && !globalConfig.noSCM ? `${_chalk().default.dim(' \u203A Press ')}o${_chalk().default.dim(' to only run tests related to changed files.')}` : null, ...(0, _watchPluginsHelpers.getSortedUsageRows)(watchPlugins, globalConfig).map(plugin => `${_chalk().default.dim(' \u203A Press')} ${plugin.key} ${_chalk().default.dim(`to ${plugin.prompt}.`)}`), `${_chalk().default.dim(' \u203A Press ')}Enter${_chalk().default.dim(' to trigger a test run.')}`];
4140
+ return `${messages.filter(message => !!message).join(delimiter)}\n`;
4141
+ };
4142
+ const showToggleUsagePrompt = () => '\n' + `${_chalk().default.bold('Watch Usage: ')}${_chalk().default.dim('Press ')}w${_chalk().default.dim(' to show more.')}`;
4143
+
4144
+ /***/ },
4145
+
4146
+ /***/ "./package.json"
4147
+ (module) {
4148
+
4149
+ module.exports = {"version":"30.4.2"};
4150
+
4151
+ /***/ }
4152
+
4153
+ /******/ });
4154
+ /************************************************************************/
4155
+ /******/ // The module cache
4156
+ /******/ var __webpack_module_cache__ = {};
4157
+ /******/
4158
+ /******/ // The require function
4159
+ /******/ function __webpack_require__(moduleId) {
4160
+ /******/ // Check if module is in cache
4161
+ /******/ var cachedModule = __webpack_module_cache__[moduleId];
4162
+ /******/ if (cachedModule !== undefined) {
4163
+ /******/ return cachedModule.exports;
4164
+ /******/ }
4165
+ /******/ // Create a new module (and put it into the cache)
4166
+ /******/ var module = __webpack_module_cache__[moduleId] = {
4167
+ /******/ // no module.id needed
4168
+ /******/ // no module.loaded needed
4169
+ /******/ exports: {}
4170
+ /******/ };
4171
+ /******/
4172
+ /******/ // Execute the module function
4173
+ /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
4174
+ /******/
4175
+ /******/ // Return the exports of the module
4176
+ /******/ return module.exports;
4177
+ /******/ }
4178
+ /******/
4179
+ /************************************************************************/
4180
+ var __webpack_exports__ = {};
4181
+ // This entry needs to be wrapped in an IIFE because it uses a non-standard name for the exports (exports).
4182
+ (() => {
4183
+ var exports = __webpack_exports__;
4184
+
4185
+
4186
+ Object.defineProperty(exports, "__esModule", ({
4187
+ value: true
4188
+ }));
4189
+ Object.defineProperty(exports, "SearchSource", ({
4190
+ enumerable: true,
4191
+ get: function () {
4192
+ return _SearchSource.default;
4193
+ }
4194
+ }));
4195
+ Object.defineProperty(exports, "createTestScheduler", ({
4196
+ enumerable: true,
4197
+ get: function () {
4198
+ return _TestScheduler.createTestScheduler;
4199
+ }
4200
+ }));
4201
+ Object.defineProperty(exports, "getVersion", ({
4202
+ enumerable: true,
4203
+ get: function () {
4204
+ return _version.default;
4205
+ }
4206
+ }));
4207
+ Object.defineProperty(exports, "runCLI", ({
4208
+ enumerable: true,
4209
+ get: function () {
4210
+ return _cli.runCLI;
4211
+ }
4212
+ }));
4213
+ var _SearchSource = _interopRequireDefault(__webpack_require__("./src/SearchSource.ts"));
4214
+ var _TestScheduler = __webpack_require__("./src/TestScheduler.ts");
4215
+ var _cli = __webpack_require__("./src/cli/index.ts");
4216
+ var _version = _interopRequireDefault(__webpack_require__("./src/version.ts"));
4217
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
4218
+ })();
4219
+
4220
+ module.exports = __webpack_exports__;
4221
+ /******/ })()
4222
+ ;