Add node modules and new code for release

This commit is contained in:
tbarnes94 2022-01-05 16:22:49 +00:00 committed by GitHub
parent a10d84bc2e
commit 90f63cb10d
7655 changed files with 1763577 additions and 14 deletions

21
node_modules/@jest/reporters/LICENSE generated vendored Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Facebook, Inc. and its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

42
node_modules/@jest/reporters/build/Status.d.ts generated vendored Normal file
View file

@ -0,0 +1,42 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { AggregatedResult, TestCaseResult, TestResult } from '@jest/test-result';
import type { ReporterOnStartOptions, Test } from './types';
declare type Cache = {
content: string;
clear: string;
};
/**
* A class that generates the CLI status of currently running tests
* and also provides an ANSI escape sequence to remove status lines
* from the terminal.
*/
export default class Status {
private _cache;
private _callback?;
private _currentTests;
private _currentTestCases;
private _done;
private _emitScheduled;
private _estimatedTime;
private _interval?;
private _aggregatedResults?;
private _showStatus;
constructor();
onChange(callback: () => void): void;
runStarted(aggregatedResults: AggregatedResult, options: ReporterOnStartOptions): void;
runFinished(): void;
addTestCaseResult(test: Test, testCaseResult: TestCaseResult): void;
testStarted(testPath: Config.Path, config: Config.ProjectConfig): void;
testFinished(_config: Config.ProjectConfig, testResult: TestResult, aggregatedResults: AggregatedResult): void;
get(): Cache;
private _emit;
private _debouncedEmit;
private _tick;
}
export {};

272
node_modules/@jest/reporters/build/Status.js generated vendored Normal file
View file

@ -0,0 +1,272 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _stringLength() {
const data = _interopRequireDefault(require('string-length'));
_stringLength = function () {
return data;
};
return data;
}
var _utils = require('./utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const RUNNING_TEXT = ' RUNS ';
const RUNNING = _chalk().default.reset.inverse.yellow.bold(RUNNING_TEXT) + ' ';
/**
* This class is a perf optimization for sorting the list of currently
* running tests. It tries to keep tests in the same positions without
* shifting the whole list.
*/
class CurrentTestList {
constructor() {
_defineProperty(this, '_array', void 0);
this._array = [];
}
add(testPath, config) {
const index = this._array.indexOf(null);
const record = {
config,
testPath
};
if (index !== -1) {
this._array[index] = record;
} else {
this._array.push(record);
}
}
delete(testPath) {
const record = this._array.find(
record => record !== null && record.testPath === testPath
);
this._array[this._array.indexOf(record || null)] = null;
}
get() {
return this._array;
}
}
/**
* A class that generates the CLI status of currently running tests
* and also provides an ANSI escape sequence to remove status lines
* from the terminal.
*/
class Status {
constructor() {
_defineProperty(this, '_cache', void 0);
_defineProperty(this, '_callback', void 0);
_defineProperty(this, '_currentTests', void 0);
_defineProperty(this, '_currentTestCases', void 0);
_defineProperty(this, '_done', void 0);
_defineProperty(this, '_emitScheduled', void 0);
_defineProperty(this, '_estimatedTime', void 0);
_defineProperty(this, '_interval', void 0);
_defineProperty(this, '_aggregatedResults', void 0);
_defineProperty(this, '_showStatus', void 0);
this._cache = null;
this._currentTests = new CurrentTestList();
this._currentTestCases = [];
this._done = false;
this._emitScheduled = false;
this._estimatedTime = 0;
this._showStatus = false;
}
onChange(callback) {
this._callback = callback;
}
runStarted(aggregatedResults, options) {
this._estimatedTime = (options && options.estimatedTime) || 0;
this._showStatus = options && options.showStatus;
this._interval = setInterval(() => this._tick(), 1000);
this._aggregatedResults = aggregatedResults;
this._debouncedEmit();
}
runFinished() {
this._done = true;
if (this._interval) clearInterval(this._interval);
this._emit();
}
addTestCaseResult(test, testCaseResult) {
this._currentTestCases.push({
test,
testCaseResult
});
if (!this._showStatus) {
this._emit();
} else {
this._debouncedEmit();
}
}
testStarted(testPath, config) {
this._currentTests.add(testPath, config);
if (!this._showStatus) {
this._emit();
} else {
this._debouncedEmit();
}
}
testFinished(_config, testResult, aggregatedResults) {
const {testFilePath} = testResult;
this._aggregatedResults = aggregatedResults;
this._currentTests.delete(testFilePath);
this._currentTestCases = this._currentTestCases.filter(({test}) => {
if (_config !== test.context.config) {
return true;
}
return test.path !== testFilePath;
});
this._debouncedEmit();
}
get() {
if (this._cache) {
return this._cache;
}
if (this._done) {
return {
clear: '',
content: ''
};
}
const width = process.stdout.columns;
let content = '\n';
this._currentTests.get().forEach(record => {
if (record) {
const {config, testPath} = record;
const projectDisplayName = config.displayName
? (0, _utils.printDisplayName)(config) + ' '
: '';
const prefix = RUNNING + projectDisplayName;
content +=
(0, _utils.wrapAnsiString)(
prefix +
(0, _utils.trimAndFormatPath)(
(0, _stringLength().default)(prefix),
config,
testPath,
width
),
width
) + '\n';
}
});
if (this._showStatus && this._aggregatedResults) {
content +=
'\n' +
(0, _utils.getSummary)(this._aggregatedResults, {
currentTestCases: this._currentTestCases,
estimatedTime: this._estimatedTime,
roundTime: true,
width
});
}
let height = 0;
for (let i = 0; i < content.length; i++) {
if (content[i] === '\n') {
height++;
}
}
const clear = '\r\x1B[K\r\x1B[1A'.repeat(height);
return (this._cache = {
clear,
content
});
}
_emit() {
this._cache = null;
if (this._callback) this._callback();
}
_debouncedEmit() {
if (!this._emitScheduled) {
// Perf optimization to avoid two separate renders When
// one test finishes and another test starts executing.
this._emitScheduled = true;
setTimeout(() => {
this._emit();
this._emitScheduled = false;
}, 100);
}
}
_tick() {
this._debouncedEmit();
}
}
exports.default = Status;

19
node_modules/@jest/reporters/build/base_reporter.d.ts generated vendored Normal file
View file

@ -0,0 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { AggregatedResult, TestCaseResult, TestResult } from '@jest/test-result';
import type { Context, Reporter, ReporterOnStartOptions, Test } from './types';
export default class BaseReporter implements Reporter {
private _error?;
log(message: string): void;
onRunStart(_results?: AggregatedResult, _options?: ReporterOnStartOptions): void;
onTestCaseResult(_test: Test, _testCaseResult: TestCaseResult): void;
onTestResult(_test?: Test, _testResult?: TestResult, _results?: AggregatedResult): void;
onTestStart(_test?: Test): void;
onRunComplete(_contexts?: Set<Context>, _aggregatedResults?: AggregatedResult): Promise<void> | void;
protected _setError(error: Error): void;
getLastError(): Error | undefined;
}

65
node_modules/@jest/reporters/build/base_reporter.js generated vendored Normal file
View file

@ -0,0 +1,65 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const {remove: preRunMessageRemove} = _jestUtil().preRunMessage;
class BaseReporter {
constructor() {
_defineProperty(this, '_error', void 0);
}
log(message) {
process.stderr.write(message + '\n');
}
onRunStart(_results, _options) {
preRunMessageRemove(process.stderr);
}
onTestCaseResult(_test, _testCaseResult) {}
onTestResult(_test, _testResult, _results) {}
onTestStart(_test) {}
onRunComplete(_contexts, _aggregatedResults) {}
_setError(error) {
this._error = error;
} // Return an error that occurred during reporting. This error will
// define whether the test run was successful or failed.
getLastError() {
return this._error;
}
}
exports.default = BaseReporter;

View file

@ -0,0 +1,23 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { AggregatedResult, TestResult } from '@jest/test-result';
import BaseReporter from './base_reporter';
import type { Context, CoverageReporterOptions, Test } from './types';
export default class CoverageReporter extends BaseReporter {
private _coverageMap;
private _globalConfig;
private _sourceMapStore;
private _options;
private _v8CoverageResults;
constructor(globalConfig: Config.GlobalConfig, options?: CoverageReporterOptions);
onTestResult(_test: Test, testResult: TestResult): void;
onRunComplete(contexts: Set<Context>, aggregatedResults: AggregatedResult): Promise<void>;
private _addUntestedFiles;
private _checkThreshold;
private _getCoverageResult;
}

654
node_modules/@jest/reporters/build/coverage_reporter.js generated vendored Normal file
View file

@ -0,0 +1,654 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _istanbulLibReport() {
const data = _interopRequireDefault(require('istanbul-lib-report'));
_istanbulLibReport = function () {
return data;
};
return data;
}
function _istanbulReports() {
const data = _interopRequireDefault(require('istanbul-reports'));
_istanbulReports = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _istanbulLibCoverage() {
const data = _interopRequireDefault(require('istanbul-lib-coverage'));
_istanbulLibCoverage = function () {
return data;
};
return data;
}
function _istanbulLibSourceMaps() {
const data = _interopRequireDefault(require('istanbul-lib-source-maps'));
_istanbulLibSourceMaps = function () {
return data;
};
return data;
}
function _v8Coverage() {
const data = require('@bcoe/v8-coverage');
_v8Coverage = function () {
return data;
};
return data;
}
function _jestWorker() {
const data = _interopRequireDefault(require('jest-worker'));
_jestWorker = function () {
return data;
};
return data;
}
function _glob() {
const data = _interopRequireDefault(require('glob'));
_glob = function () {
return data;
};
return data;
}
function _v8ToIstanbul() {
const data = _interopRequireDefault(require('v8-to-istanbul'));
_v8ToIstanbul = function () {
return data;
};
return data;
}
var _base_reporter = _interopRequireDefault(require('./base_reporter'));
var _get_watermarks = _interopRequireDefault(require('./get_watermarks'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const FAIL_COLOR = _chalk().default.bold.red;
const RUNNING_TEST_COLOR = _chalk().default.bold.dim;
class CoverageReporter extends _base_reporter.default {
constructor(globalConfig, options) {
super();
_defineProperty(this, '_coverageMap', void 0);
_defineProperty(this, '_globalConfig', void 0);
_defineProperty(this, '_sourceMapStore', void 0);
_defineProperty(this, '_options', void 0);
_defineProperty(this, '_v8CoverageResults', void 0);
this._coverageMap = _istanbulLibCoverage().default.createCoverageMap({});
this._globalConfig = globalConfig;
this._sourceMapStore = _istanbulLibSourceMaps().default.createSourceMapStore();
this._v8CoverageResults = [];
this._options = options || {};
}
onTestResult(_test, testResult) {
if (testResult.v8Coverage) {
this._v8CoverageResults.push(testResult.v8Coverage);
return;
}
if (testResult.coverage) {
this._coverageMap.merge(testResult.coverage);
}
}
async onRunComplete(contexts, aggregatedResults) {
await this._addUntestedFiles(contexts);
const {map, reportContext} = await this._getCoverageResult();
try {
const coverageReporters = this._globalConfig.coverageReporters || [];
if (!this._globalConfig.useStderr && coverageReporters.length < 1) {
coverageReporters.push('text-summary');
}
coverageReporters.forEach(reporter => {
let additionalOptions = {};
if (Array.isArray(reporter)) {
[reporter, additionalOptions] = reporter;
}
_istanbulReports()
.default.create(reporter, {
maxCols: process.stdout.columns || Infinity,
...additionalOptions
}) // @ts-expect-error
.execute(reportContext);
});
aggregatedResults.coverageMap = map;
} catch (e) {
console.error(
_chalk().default.red(`
Failed to write coverage reports:
ERROR: ${e.toString()}
STACK: ${e.stack}
`)
);
}
this._checkThreshold(map);
}
async _addUntestedFiles(contexts) {
const files = [];
contexts.forEach(context => {
const config = context.config;
if (
this._globalConfig.collectCoverageFrom &&
this._globalConfig.collectCoverageFrom.length
) {
context.hasteFS
.matchFilesWithGlob(
this._globalConfig.collectCoverageFrom,
config.rootDir
)
.forEach(filePath =>
files.push({
config,
path: filePath
})
);
}
});
if (!files.length) {
return;
}
if (_jestUtil().isInteractive) {
process.stderr.write(
RUNNING_TEST_COLOR('Running coverage on untested files...')
);
}
let worker;
if (this._globalConfig.maxWorkers <= 1) {
worker = require('./coverage_worker');
} else {
worker = new (_jestWorker().default)(
require.resolve('./coverage_worker'),
{
exposedMethods: ['worker'],
maxRetries: 2,
numWorkers: this._globalConfig.maxWorkers
}
);
}
const instrumentation = files.map(async fileObj => {
const filename = fileObj.path;
const config = fileObj.config;
const hasCoverageData = this._v8CoverageResults.some(v8Res =>
v8Res.some(innerRes => innerRes.result.url === filename)
);
if (
!hasCoverageData &&
!this._coverageMap.data[filename] &&
'worker' in worker
) {
try {
const result = await worker.worker({
config,
globalConfig: this._globalConfig,
options: {
...this._options,
changedFiles:
this._options.changedFiles &&
Array.from(this._options.changedFiles),
sourcesRelatedToTestsInChangedFiles:
this._options.sourcesRelatedToTestsInChangedFiles &&
Array.from(this._options.sourcesRelatedToTestsInChangedFiles)
},
path: filename
});
if (result) {
if (result.kind === 'V8Coverage') {
this._v8CoverageResults.push([
{
codeTransformResult: undefined,
result: result.result
}
]);
} else {
this._coverageMap.addFileCoverage(result.coverage);
}
}
} catch (error) {
console.error(
_chalk().default.red(
[
`Failed to collect coverage from ${filename}`,
`ERROR: ${error.message}`,
`STACK: ${error.stack}`
].join('\n')
)
);
}
}
});
try {
await Promise.all(instrumentation);
} catch {
// Do nothing; errors were reported earlier to the console.
}
if (_jestUtil().isInteractive) {
(0, _jestUtil().clearLine)(process.stderr);
}
if (worker && 'end' in worker && typeof worker.end === 'function') {
await worker.end();
}
}
_checkThreshold(map) {
const {coverageThreshold} = this._globalConfig;
if (coverageThreshold) {
function check(name, thresholds, actuals) {
return ['statements', 'branches', 'lines', 'functions'].reduce(
(errors, key) => {
const actual = actuals[key].pct;
const actualUncovered = actuals[key].total - actuals[key].covered;
const threshold = thresholds[key];
if (threshold !== undefined) {
if (threshold < 0) {
if (threshold * -1 < actualUncovered) {
errors.push(
`Jest: Uncovered count for ${key} (${actualUncovered}) ` +
`exceeds ${name} threshold (${-1 * threshold})`
);
}
} else if (actual < threshold) {
errors.push(
`Jest: "${name}" coverage threshold for ${key} (${threshold}%) not met: ${actual}%`
);
}
}
return errors;
},
[]
);
}
const THRESHOLD_GROUP_TYPES = {
GLOB: 'glob',
GLOBAL: 'global',
PATH: 'path'
};
const coveredFiles = map.files();
const thresholdGroups = Object.keys(coverageThreshold);
const groupTypeByThresholdGroup = {};
const filesByGlob = {};
const coveredFilesSortedIntoThresholdGroup = coveredFiles.reduce(
(files, file) => {
const pathOrGlobMatches = thresholdGroups.reduce(
(agg, thresholdGroup) => {
const absoluteThresholdGroup = path().resolve(thresholdGroup); // The threshold group might be a path:
if (file.indexOf(absoluteThresholdGroup) === 0) {
groupTypeByThresholdGroup[thresholdGroup] =
THRESHOLD_GROUP_TYPES.PATH;
return agg.concat([[file, thresholdGroup]]);
} // If the threshold group is not a path it might be a glob:
// Note: glob.sync is slow. By memoizing the files matching each glob
// (rather than recalculating it for each covered file) we save a tonne
// of execution time.
if (filesByGlob[absoluteThresholdGroup] === undefined) {
filesByGlob[absoluteThresholdGroup] = _glob()
.default.sync(absoluteThresholdGroup)
.map(filePath => path().resolve(filePath));
}
if (filesByGlob[absoluteThresholdGroup].indexOf(file) > -1) {
groupTypeByThresholdGroup[thresholdGroup] =
THRESHOLD_GROUP_TYPES.GLOB;
return agg.concat([[file, thresholdGroup]]);
}
return agg;
},
[]
);
if (pathOrGlobMatches.length > 0) {
return files.concat(pathOrGlobMatches);
} // Neither a glob or a path? Toss it in global if there's a global threshold:
if (thresholdGroups.indexOf(THRESHOLD_GROUP_TYPES.GLOBAL) > -1) {
groupTypeByThresholdGroup[THRESHOLD_GROUP_TYPES.GLOBAL] =
THRESHOLD_GROUP_TYPES.GLOBAL;
return files.concat([[file, THRESHOLD_GROUP_TYPES.GLOBAL]]);
} // A covered file that doesn't have a threshold:
return files.concat([[file, undefined]]);
},
[]
);
const getFilesInThresholdGroup = thresholdGroup =>
coveredFilesSortedIntoThresholdGroup
.filter(fileAndGroup => fileAndGroup[1] === thresholdGroup)
.map(fileAndGroup => fileAndGroup[0]);
function combineCoverage(filePaths) {
return filePaths
.map(filePath => map.fileCoverageFor(filePath))
.reduce((combinedCoverage, nextFileCoverage) => {
if (combinedCoverage === undefined || combinedCoverage === null) {
return nextFileCoverage.toSummary();
}
return combinedCoverage.merge(nextFileCoverage.toSummary());
}, undefined);
}
let errors = [];
thresholdGroups.forEach(thresholdGroup => {
switch (groupTypeByThresholdGroup[thresholdGroup]) {
case THRESHOLD_GROUP_TYPES.GLOBAL: {
const coverage = combineCoverage(
getFilesInThresholdGroup(THRESHOLD_GROUP_TYPES.GLOBAL)
);
if (coverage) {
errors = errors.concat(
check(
thresholdGroup,
coverageThreshold[thresholdGroup],
coverage
)
);
}
break;
}
case THRESHOLD_GROUP_TYPES.PATH: {
const coverage = combineCoverage(
getFilesInThresholdGroup(thresholdGroup)
);
if (coverage) {
errors = errors.concat(
check(
thresholdGroup,
coverageThreshold[thresholdGroup],
coverage
)
);
}
break;
}
case THRESHOLD_GROUP_TYPES.GLOB:
getFilesInThresholdGroup(thresholdGroup).forEach(
fileMatchingGlob => {
errors = errors.concat(
check(
fileMatchingGlob,
coverageThreshold[thresholdGroup],
map.fileCoverageFor(fileMatchingGlob).toSummary()
)
);
}
);
break;
default:
// If the file specified by path is not found, error is returned.
if (thresholdGroup !== THRESHOLD_GROUP_TYPES.GLOBAL) {
errors = errors.concat(
`Jest: Coverage data for ${thresholdGroup} was not found.`
);
}
// Sometimes all files in the coverage data are matched by
// PATH and GLOB threshold groups in which case, don't error when
// the global threshold group doesn't match any files.
}
});
errors = errors.filter(
err => err !== undefined && err !== null && err.length > 0
);
if (errors.length > 0) {
this.log(`${FAIL_COLOR(errors.join('\n'))}`);
this._setError(new Error(errors.join('\n')));
}
}
}
async _getCoverageResult() {
if (this._globalConfig.coverageProvider === 'v8') {
const mergedCoverages = (0, _v8Coverage().mergeProcessCovs)(
this._v8CoverageResults.map(cov => ({
result: cov.map(r => r.result)
}))
);
const fileTransforms = new Map();
this._v8CoverageResults.forEach(res =>
res.forEach(r => {
if (r.codeTransformResult && !fileTransforms.has(r.result.url)) {
fileTransforms.set(r.result.url, r.codeTransformResult);
}
})
);
const transformedCoverage = await Promise.all(
mergedCoverages.result.map(async res => {
const fileTransform = fileTransforms.get(res.url);
let sourcemapContent = undefined;
if (
fileTransform &&
fileTransform.sourceMapPath &&
fs().existsSync(fileTransform.sourceMapPath)
) {
sourcemapContent = JSON.parse(
fs().readFileSync(fileTransform.sourceMapPath, 'utf8')
);
}
const converter = (0, _v8ToIstanbul().default)(
res.url,
0,
fileTransform && sourcemapContent
? {
originalSource: fileTransform.originalCode,
source: fileTransform.code,
sourceMap: {
sourcemap: sourcemapContent
}
}
: {
source: fs().readFileSync(res.url, 'utf8')
}
);
await converter.load();
converter.applyCoverage(res.functions);
return converter.toIstanbul();
})
);
const map = _istanbulLibCoverage().default.createCoverageMap({});
transformedCoverage.forEach(res => map.merge(res));
const reportContext = _istanbulLibReport().default.createContext({
coverageMap: map,
dir: this._globalConfig.coverageDirectory,
watermarks: (0, _get_watermarks.default)(this._globalConfig)
});
return {
map,
reportContext
};
}
const map = await this._sourceMapStore.transformCoverage(this._coverageMap);
const reportContext = _istanbulLibReport().default.createContext({
coverageMap: map,
dir: this._globalConfig.coverageDirectory,
sourceFinder: this._sourceMapStore.sourceFinder,
watermarks: (0, _get_watermarks.default)(this._globalConfig)
});
return {
map,
reportContext
};
}
}
exports.default = CoverageReporter;

View file

@ -0,0 +1,17 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { CoverageReporterSerializedOptions } from './types';
import { CoverageWorkerResult } from './generateEmptyCoverage';
export declare type CoverageWorkerData = {
globalConfig: Config.GlobalConfig;
config: Config.ProjectConfig;
path: Config.Path;
options?: CoverageReporterSerializedOptions;
};
export type { CoverageWorkerResult };
export declare function worker({ config, globalConfig, path, options, }: CoverageWorkerData): CoverageWorkerResult | null;

103
node_modules/@jest/reporters/build/coverage_worker.js generated vendored Normal file
View file

@ -0,0 +1,103 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.worker = worker;
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
function _exit() {
const data = _interopRequireDefault(require('exit'));
_exit = function () {
return data;
};
return data;
}
var _generateEmptyCoverage = _interopRequireWildcard(
require('./generateEmptyCoverage')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
// Make sure uncaught errors are logged before we exit.
process.on('uncaughtException', err => {
console.error(err.stack);
(0, _exit().default)(1);
});
function worker({config, globalConfig, path, options}) {
return (0, _generateEmptyCoverage.default)(
fs().readFileSync(path, 'utf8'),
path,
globalConfig,
config,
(options === null || options === void 0 ? void 0 : options.changedFiles) &&
new Set(options.changedFiles),
(options === null || options === void 0
? void 0
: options.sourcesRelatedToTestsInChangedFiles) &&
new Set(options.sourcesRelatedToTestsInChangedFiles)
);
}

View file

@ -0,0 +1,31 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { AggregatedResult, TestCaseResult, TestResult } from '@jest/test-result';
import type { ReporterOnStartOptions, Test } from './types';
import BaseReporter from './base_reporter';
export default class DefaultReporter extends BaseReporter {
private _clear;
private _err;
protected _globalConfig: Config.GlobalConfig;
private _out;
private _status;
private _bufferedOutput;
constructor(globalConfig: Config.GlobalConfig);
private _wrapStdio;
forceFlushBufferedOutput(): void;
private _clearStatus;
private _printStatus;
onRunStart(aggregatedResults: AggregatedResult, options: ReporterOnStartOptions): void;
onTestStart(test: Test): void;
onTestCaseResult(test: Test, testCaseResult: TestCaseResult): void;
onRunComplete(): void;
onTestResult(test: Test, testResult: TestResult, aggregatedResults: AggregatedResult): void;
testFinished(config: Config.ProjectConfig, testResult: TestResult, aggregatedResults: AggregatedResult): void;
printTestFileHeader(_testPath: Config.Path, config: Config.ProjectConfig, result: TestResult): void;
printTestFileFailureMessage(_testPath: Config.Path, _config: Config.ProjectConfig, result: TestResult): void;
}

258
node_modules/@jest/reporters/build/default_reporter.js generated vendored Normal file
View file

@ -0,0 +1,258 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _console() {
const data = require('@jest/console');
_console = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
var _base_reporter = _interopRequireDefault(require('./base_reporter'));
var _Status = _interopRequireDefault(require('./Status'));
var _get_result_header = _interopRequireDefault(require('./get_result_header'));
var _get_snapshot_status = _interopRequireDefault(
require('./get_snapshot_status')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const TITLE_BULLET = _chalk().default.bold('\u25cf ');
class DefaultReporter extends _base_reporter.default {
// ANSI clear sequence for the last printed status
constructor(globalConfig) {
super();
_defineProperty(this, '_clear', void 0);
_defineProperty(this, '_err', void 0);
_defineProperty(this, '_globalConfig', void 0);
_defineProperty(this, '_out', void 0);
_defineProperty(this, '_status', void 0);
_defineProperty(this, '_bufferedOutput', void 0);
this._globalConfig = globalConfig;
this._clear = '';
this._out = process.stdout.write.bind(process.stdout);
this._err = process.stderr.write.bind(process.stderr);
this._status = new _Status.default();
this._bufferedOutput = new Set();
this._wrapStdio(process.stdout);
this._wrapStdio(process.stderr);
this._status.onChange(() => {
this._clearStatus();
this._printStatus();
});
}
_wrapStdio(stream) {
const originalWrite = stream.write;
let buffer = [];
let timeout = null;
const flushBufferedOutput = () => {
const string = buffer.join('');
buffer = []; // This is to avoid conflicts between random output and status text
this._clearStatus();
if (string) {
originalWrite.call(stream, string);
}
this._printStatus();
this._bufferedOutput.delete(flushBufferedOutput);
};
this._bufferedOutput.add(flushBufferedOutput);
const debouncedFlush = () => {
// If the process blows up no errors would be printed.
// There should be a smart way to buffer stderr, but for now
// we just won't buffer it.
if (stream === process.stderr) {
flushBufferedOutput();
} else {
if (!timeout) {
timeout = setTimeout(() => {
flushBufferedOutput();
timeout = null;
}, 100);
}
}
};
stream.write = chunk => {
buffer.push(chunk);
debouncedFlush();
return true;
};
} // Don't wait for the debounced call and flush all output immediately.
forceFlushBufferedOutput() {
for (const flushBufferedOutput of this._bufferedOutput) {
flushBufferedOutput();
}
}
_clearStatus() {
if (_jestUtil().isInteractive) {
if (this._globalConfig.useStderr) {
this._err(this._clear);
} else {
this._out(this._clear);
}
}
}
_printStatus() {
const {content, clear} = this._status.get();
this._clear = clear;
if (_jestUtil().isInteractive) {
if (this._globalConfig.useStderr) {
this._err(content);
} else {
this._out(content);
}
}
}
onRunStart(aggregatedResults, options) {
this._status.runStarted(aggregatedResults, options);
}
onTestStart(test) {
this._status.testStarted(test.path, test.context.config);
}
onTestCaseResult(test, testCaseResult) {
this._status.addTestCaseResult(test, testCaseResult);
}
onRunComplete() {
this.forceFlushBufferedOutput();
this._status.runFinished();
process.stdout.write = this._out;
process.stderr.write = this._err;
(0, _jestUtil().clearLine)(process.stderr);
}
onTestResult(test, testResult, aggregatedResults) {
this.testFinished(test.context.config, testResult, aggregatedResults);
if (!testResult.skipped) {
this.printTestFileHeader(
testResult.testFilePath,
test.context.config,
testResult
);
this.printTestFileFailureMessage(
testResult.testFilePath,
test.context.config,
testResult
);
}
this.forceFlushBufferedOutput();
}
testFinished(config, testResult, aggregatedResults) {
this._status.testFinished(config, testResult, aggregatedResults);
}
printTestFileHeader(_testPath, config, result) {
this.log(
(0, _get_result_header.default)(result, this._globalConfig, config)
);
if (result.console) {
this.log(
' ' +
TITLE_BULLET +
'Console\n\n' +
(0, _console().getConsoleOutput)(
config.cwd,
!!this._globalConfig.verbose,
result.console,
config,
this._globalConfig
)
);
}
}
printTestFileFailureMessage(_testPath, _config, result) {
if (result.failureMessage) {
this.log(result.failureMessage);
}
const didUpdate = this._globalConfig.updateSnapshot === 'all';
const snapshotStatuses = (0, _get_snapshot_status.default)(
result.snapshot,
didUpdate
);
snapshotStatuses.forEach(this.log);
}
}
exports.default = DefaultReporter;

View file

@ -0,0 +1,19 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import { FileCoverage } from 'istanbul-lib-coverage';
import type { V8Coverage } from 'collect-v8-coverage';
declare type SingleV8Coverage = V8Coverage[number];
export declare type CoverageWorkerResult = {
kind: 'BabelCoverage';
coverage: FileCoverage;
} | {
kind: 'V8Coverage';
result: SingleV8Coverage;
};
export default function (source: string, filename: Config.Path, globalConfig: Config.GlobalConfig, config: Config.ProjectConfig, changedFiles?: Set<Config.Path>, sourcesRelatedToTestsInChangedFiles?: Set<Config.Path>): CoverageWorkerResult | null;
export {};

View file

@ -0,0 +1,158 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = _default;
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
function _istanbulLibInstrument() {
const data = require('istanbul-lib-instrument');
_istanbulLibInstrument = function () {
return data;
};
return data;
}
function _istanbulLibCoverage() {
const data = require('istanbul-lib-coverage');
_istanbulLibCoverage = function () {
return data;
};
return data;
}
function _transform() {
const data = require('@jest/transform');
_transform = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function _default(
source,
filename,
globalConfig,
config,
changedFiles,
sourcesRelatedToTestsInChangedFiles
) {
const coverageOptions = {
changedFiles,
collectCoverage: globalConfig.collectCoverage,
collectCoverageFrom: globalConfig.collectCoverageFrom,
collectCoverageOnlyFrom: globalConfig.collectCoverageOnlyFrom,
coverageProvider: globalConfig.coverageProvider,
sourcesRelatedToTestsInChangedFiles
};
let coverageWorkerResult = null;
if ((0, _transform().shouldInstrument)(filename, coverageOptions, config)) {
if (coverageOptions.coverageProvider === 'v8') {
const stat = fs().statSync(filename);
return {
kind: 'V8Coverage',
result: {
functions: [
{
functionName: '(empty-report)',
isBlockCoverage: true,
ranges: [
{
count: 0,
endOffset: stat.size,
startOffset: 0
}
]
}
],
scriptId: '0',
url: filename
}
};
} // Transform file with instrumentation to make sure initial coverage data is well mapped to original code.
const {code} = new (_transform().ScriptTransformer)(config).transformSource(
filename,
source,
true
); // TODO: consider passing AST
const extracted = (0, _istanbulLibInstrument().readInitialCoverage)(code); // Check extracted initial coverage is not null, this can happen when using /* istanbul ignore file */
if (extracted) {
coverageWorkerResult = {
coverage: (0, _istanbulLibCoverage().createFileCoverage)(
extracted.coverageData
),
kind: 'BabelCoverage'
};
}
}
return coverageWorkerResult;
}

View file

@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { TestResult } from '@jest/test-result';
declare const _default: (result: TestResult, globalConfig: Config.GlobalConfig, projectConfig?: Config.ProjectConfig | undefined) => string;
export default _default;

107
node_modules/@jest/reporters/build/get_result_header.js generated vendored Normal file
View file

@ -0,0 +1,107 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _terminalLink() {
const data = _interopRequireDefault(require('terminal-link'));
_terminalLink = function () {
return data;
};
return data;
}
var _utils = require('./utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const LONG_TEST_COLOR = _chalk().default.reset.bold.bgRed; // Explicitly reset for these messages since they can get written out in the
// middle of error logging
const FAIL_TEXT = 'FAIL';
const PASS_TEXT = 'PASS';
const FAIL = _chalk().default.supportsColor
? _chalk().default.reset.inverse.bold.red(` ${FAIL_TEXT} `)
: FAIL_TEXT;
const PASS = _chalk().default.supportsColor
? _chalk().default.reset.inverse.bold.green(` ${PASS_TEXT} `)
: PASS_TEXT;
var _default = (result, globalConfig, projectConfig) => {
var _result$perfStats;
const testPath = result.testFilePath;
const formattedTestPath = (0, _utils.formatTestPath)(
projectConfig ? projectConfig : globalConfig,
testPath
);
const fileLink = (0, _terminalLink().default)(
formattedTestPath,
`file://${testPath}`,
{
fallback: () => formattedTestPath
}
);
const status =
result.numFailingTests > 0 || result.testExecError ? FAIL : PASS;
const testDetail = [];
if (
(_result$perfStats = result.perfStats) === null ||
_result$perfStats === void 0
? void 0
: _result$perfStats.slow
) {
const runTime = result.perfStats.runtime / 1000;
testDetail.push(LONG_TEST_COLOR((0, _jestUtil().formatTime)(runTime, 0)));
}
if (result.memoryUsage) {
const toMB = bytes => Math.floor(bytes / 1024 / 1024);
testDetail.push(`${toMB(result.memoryUsage)} MB heap size`);
}
const projectDisplayName =
projectConfig && projectConfig.displayName
? (0, _utils.printDisplayName)(projectConfig) + ' '
: '';
return (
`${status} ${projectDisplayName}${fileLink}` +
(testDetail.length ? ` (${testDetail.join(', ')})` : '')
);
};
exports.default = _default;

View file

@ -0,0 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { TestResult } from '@jest/test-result';
declare const _default: (snapshot: TestResult['snapshot'], afterUpdate: boolean) => Array<string>;
export default _default;

View file

@ -0,0 +1,113 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const ARROW = ' \u203A ';
const DOT = ' \u2022 ';
const FAIL_COLOR = _chalk().default.bold.red;
const SNAPSHOT_ADDED = _chalk().default.bold.green;
const SNAPSHOT_UPDATED = _chalk().default.bold.green;
const SNAPSHOT_OUTDATED = _chalk().default.bold.yellow;
var _default = (snapshot, afterUpdate) => {
const statuses = [];
if (snapshot.added) {
statuses.push(
SNAPSHOT_ADDED(
ARROW +
(0, _jestUtil().pluralize)('snapshot', snapshot.added) +
' written.'
)
);
}
if (snapshot.updated) {
statuses.push(
SNAPSHOT_UPDATED(
ARROW +
(0, _jestUtil().pluralize)('snapshot', snapshot.updated) +
' updated.'
)
);
}
if (snapshot.unmatched) {
statuses.push(
FAIL_COLOR(
ARROW +
(0, _jestUtil().pluralize)('snapshot', snapshot.unmatched) +
' failed.'
)
);
}
if (snapshot.unchecked) {
if (afterUpdate) {
statuses.push(
SNAPSHOT_UPDATED(
ARROW +
(0, _jestUtil().pluralize)('snapshot', snapshot.unchecked) +
' removed.'
)
);
} else {
statuses.push(
SNAPSHOT_OUTDATED(
ARROW +
(0, _jestUtil().pluralize)('snapshot', snapshot.unchecked) +
' obsolete'
) + '.'
);
}
snapshot.uncheckedKeys.forEach(key => {
statuses.push(` ${DOT}${key}`);
});
}
if (snapshot.fileDeleted) {
statuses.push(SNAPSHOT_UPDATED(ARROW + 'snapshot file removed.'));
}
return statuses;
};
exports.default = _default;

View file

@ -0,0 +1,10 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { SnapshotSummary } from '@jest/test-result';
declare const _default: (snapshots: SnapshotSummary, globalConfig: Config.GlobalConfig, updateCommand: string) => Array<string>;
export default _default;

View file

@ -0,0 +1,205 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
var _utils = require('./utils');
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const ARROW = ' \u203A ';
const DOWN_ARROW = ' \u21B3 ';
const DOT = ' \u2022 ';
const FAIL_COLOR = _chalk().default.bold.red;
const OBSOLETE_COLOR = _chalk().default.bold.yellow;
const SNAPSHOT_ADDED = _chalk().default.bold.green;
const SNAPSHOT_NOTE = _chalk().default.dim;
const SNAPSHOT_REMOVED = _chalk().default.bold.green;
const SNAPSHOT_SUMMARY = _chalk().default.bold;
const SNAPSHOT_UPDATED = _chalk().default.bold.green;
var _default = (snapshots, globalConfig, updateCommand) => {
const summary = [];
summary.push(SNAPSHOT_SUMMARY('Snapshot Summary'));
if (snapshots.added) {
summary.push(
SNAPSHOT_ADDED(
ARROW +
(0, _jestUtil().pluralize)('snapshot', snapshots.added) +
' written '
) +
`from ${(0, _jestUtil().pluralize)(
'test suite',
snapshots.filesAdded
)}.`
);
}
if (snapshots.unmatched) {
summary.push(
FAIL_COLOR(
`${ARROW}${(0, _jestUtil().pluralize)(
'snapshot',
snapshots.unmatched
)} failed`
) +
` from ${(0, _jestUtil().pluralize)(
'test suite',
snapshots.filesUnmatched
)}. ` +
SNAPSHOT_NOTE(
'Inspect your code changes or ' + updateCommand + ' to update them.'
)
);
}
if (snapshots.updated) {
summary.push(
SNAPSHOT_UPDATED(
ARROW +
(0, _jestUtil().pluralize)('snapshot', snapshots.updated) +
' updated '
) +
`from ${(0, _jestUtil().pluralize)(
'test suite',
snapshots.filesUpdated
)}.`
);
}
if (snapshots.filesRemoved) {
if (snapshots.didUpdate) {
summary.push(
SNAPSHOT_REMOVED(
`${ARROW}${(0, _jestUtil().pluralize)(
'snapshot file',
snapshots.filesRemoved
)} removed `
) +
`from ${(0, _jestUtil().pluralize)(
'test suite',
snapshots.filesRemoved
)}.`
);
} else {
summary.push(
OBSOLETE_COLOR(
`${ARROW}${(0, _jestUtil().pluralize)(
'snapshot file',
snapshots.filesRemoved
)} obsolete `
) +
`from ${(0, _jestUtil().pluralize)(
'test suite',
snapshots.filesRemoved
)}. ` +
SNAPSHOT_NOTE(
`To remove ${
snapshots.filesRemoved === 1 ? 'it' : 'them all'
}, ${updateCommand}.`
)
);
}
}
if (snapshots.filesRemovedList && snapshots.filesRemovedList.length) {
const [head, ...tail] = snapshots.filesRemovedList;
summary.push(
` ${DOWN_ARROW} ${DOT}${(0, _utils.formatTestPath)(globalConfig, head)}`
);
tail.forEach(key => {
summary.push(
` ${DOT}${(0, _utils.formatTestPath)(globalConfig, key)}`
);
});
}
if (snapshots.unchecked) {
if (snapshots.didUpdate) {
summary.push(
SNAPSHOT_REMOVED(
`${ARROW}${(0, _jestUtil().pluralize)(
'snapshot',
snapshots.unchecked
)} removed `
) +
`from ${(0, _jestUtil().pluralize)(
'test suite',
snapshots.uncheckedKeysByFile.length
)}.`
);
} else {
summary.push(
OBSOLETE_COLOR(
`${ARROW}${(0, _jestUtil().pluralize)(
'snapshot',
snapshots.unchecked
)} obsolete `
) +
`from ${(0, _jestUtil().pluralize)(
'test suite',
snapshots.uncheckedKeysByFile.length
)}. ` +
SNAPSHOT_NOTE(
`To remove ${
snapshots.unchecked === 1 ? 'it' : 'them all'
}, ${updateCommand}.`
)
);
}
snapshots.uncheckedKeysByFile.forEach(uncheckedFile => {
summary.push(
` ${DOWN_ARROW}${(0, _utils.formatTestPath)(
globalConfig,
uncheckedFile.filePath
)}`
);
uncheckedFile.keys.forEach(key => {
summary.push(` ${DOT}${key}`);
});
});
}
return summary;
};
exports.default = _default;

View file

@ -0,0 +1,9 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import istanbulReport = require('istanbul-lib-report');
export default function getWatermarks(config: Config.GlobalConfig): istanbulReport.Watermarks;

47
node_modules/@jest/reporters/build/get_watermarks.js generated vendored Normal file
View file

@ -0,0 +1,47 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getWatermarks;
function _istanbulLibReport() {
const data = _interopRequireDefault(require('istanbul-lib-report'));
_istanbulLibReport = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
function getWatermarks(config) {
const defaultWatermarks = _istanbulLibReport().default.getDefaultWatermarks();
const {coverageThreshold} = config;
if (!coverageThreshold || !coverageThreshold.global) {
return defaultWatermarks;
}
const keys = ['branches', 'functions', 'lines', 'statements'];
return keys.reduce((watermarks, key) => {
const value = coverageThreshold.global[key];
if (value !== undefined) {
watermarks[key][1] = value;
}
return watermarks;
}, defaultWatermarks);
}

24
node_modules/@jest/reporters/build/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,24 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export type { Config } from '@jest/types';
export type { AggregatedResult, SnapshotSummary, TestResult, } from '@jest/test-result';
export { default as BaseReporter } from './base_reporter';
export { default as CoverageReporter } from './coverage_reporter';
export { default as DefaultReporter } from './default_reporter';
export { default as NotifyReporter } from './notify_reporter';
export { default as SummaryReporter } from './summary_reporter';
export { default as VerboseReporter } from './verbose_reporter';
export type { Context, Reporter, ReporterOnStartOptions, SummaryOptions, Test, } from './types';
export declare const utils: {
formatTestPath: (config: import("@jest/types/build/Config").GlobalConfig | import("@jest/types/build/Config").ProjectConfig, testPath: string) => string;
printDisplayName: (config: import("@jest/types/build/Config").ProjectConfig) => string;
relativePath: (config: import("@jest/types/build/Config").GlobalConfig | import("@jest/types/build/Config").ProjectConfig, testPath: string) => {
basename: string;
dirname: string;
};
trimAndFormatPath: (pad: number, config: import("@jest/types/build/Config").GlobalConfig | import("@jest/types/build/Config").ProjectConfig, testPath: string, columns: number) => string;
};

74
node_modules/@jest/reporters/build/index.js generated vendored Normal file
View file

@ -0,0 +1,74 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
Object.defineProperty(exports, 'BaseReporter', {
enumerable: true,
get: function () {
return _base_reporter.default;
}
});
Object.defineProperty(exports, 'CoverageReporter', {
enumerable: true,
get: function () {
return _coverage_reporter.default;
}
});
Object.defineProperty(exports, 'DefaultReporter', {
enumerable: true,
get: function () {
return _default_reporter.default;
}
});
Object.defineProperty(exports, 'NotifyReporter', {
enumerable: true,
get: function () {
return _notify_reporter.default;
}
});
Object.defineProperty(exports, 'SummaryReporter', {
enumerable: true,
get: function () {
return _summary_reporter.default;
}
});
Object.defineProperty(exports, 'VerboseReporter', {
enumerable: true,
get: function () {
return _verbose_reporter.default;
}
});
exports.utils = void 0;
var _utils = require('./utils');
var _base_reporter = _interopRequireDefault(require('./base_reporter'));
var _coverage_reporter = _interopRequireDefault(require('./coverage_reporter'));
var _default_reporter = _interopRequireDefault(require('./default_reporter'));
var _notify_reporter = _interopRequireDefault(require('./notify_reporter'));
var _summary_reporter = _interopRequireDefault(require('./summary_reporter'));
var _verbose_reporter = _interopRequireDefault(require('./verbose_reporter'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const utils = {
formatTestPath: _utils.formatTestPath,
printDisplayName: _utils.printDisplayName,
relativePath: _utils.relativePath,
trimAndFormatPath: _utils.trimAndFormatPath
};
exports.utils = utils;

View file

@ -0,0 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { AggregatedResult } from '@jest/test-result';
import type { Context, TestSchedulerContext } from './types';
import BaseReporter from './base_reporter';
export default class NotifyReporter extends BaseReporter {
private _notifier;
private _startRun;
private _globalConfig;
private _context;
constructor(globalConfig: Config.GlobalConfig, startRun: (globalConfig: Config.GlobalConfig) => any, context: TestSchedulerContext);
onRunComplete(contexts: Set<Context>, result: AggregatedResult): void;
}

254
node_modules/@jest/reporters/build/notify_reporter.js generated vendored Normal file
View file

@ -0,0 +1,254 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function util() {
const data = _interopRequireWildcard(require('util'));
util = function () {
return data;
};
return data;
}
function _exit() {
const data = _interopRequireDefault(require('exit'));
_exit = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
var _base_reporter = _interopRequireDefault(require('./base_reporter'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const isDarwin = process.platform === 'darwin';
const icon = path().resolve(__dirname, '../assets/jest_logo.png');
class NotifyReporter extends _base_reporter.default {
constructor(globalConfig, startRun, context) {
super();
_defineProperty(this, '_notifier', loadNotifier());
_defineProperty(this, '_startRun', void 0);
_defineProperty(this, '_globalConfig', void 0);
_defineProperty(this, '_context', void 0);
this._globalConfig = globalConfig;
this._startRun = startRun;
this._context = context;
}
onRunComplete(contexts, result) {
const success =
result.numFailedTests === 0 && result.numRuntimeErrorTestSuites === 0;
const firstContext = contexts.values().next();
const hasteFS =
firstContext && firstContext.value && firstContext.value.hasteFS;
let packageName;
if (hasteFS != null) {
// assuming root package.json is the first one
const [filePath] = hasteFS.matchFiles('package.json');
packageName =
filePath != null
? hasteFS.getModuleName(filePath)
: this._globalConfig.rootDir;
} else {
packageName = this._globalConfig.rootDir;
}
packageName = packageName != null ? `${packageName} - ` : '';
const notifyMode = this._globalConfig.notifyMode;
const statusChanged =
this._context.previousSuccess !== success || this._context.firstRun;
const testsHaveRun = result.numTotalTests !== 0;
if (
testsHaveRun &&
success &&
(notifyMode === 'always' ||
notifyMode === 'success' ||
notifyMode === 'success-change' ||
(notifyMode === 'change' && statusChanged) ||
(notifyMode === 'failure-change' && statusChanged))
) {
const title = util().format('%s%d%% Passed', packageName, 100);
const message = `${isDarwin ? '\u2705 ' : ''}${(0, _jestUtil().pluralize)(
'test',
result.numPassedTests
)} passed`;
this._notifier.notify({
icon,
message,
timeout: false,
title
});
} else if (
testsHaveRun &&
!success &&
(notifyMode === 'always' ||
notifyMode === 'failure' ||
notifyMode === 'failure-change' ||
(notifyMode === 'change' && statusChanged) ||
(notifyMode === 'success-change' && statusChanged))
) {
const failed = result.numFailedTests / result.numTotalTests;
const title = util().format(
'%s%d%% Failed',
packageName,
Math.ceil(Number.isNaN(failed) ? 0 : failed * 100)
);
const message = util().format(
(isDarwin ? '\u26D4\uFE0F ' : '') + '%d of %d tests failed',
result.numFailedTests,
result.numTotalTests
);
const watchMode = this._globalConfig.watch || this._globalConfig.watchAll;
const restartAnswer = 'Run again';
const quitAnswer = 'Exit tests';
if (!watchMode) {
this._notifier.notify({
icon,
message,
timeout: false,
title
});
} else {
this._notifier.notify(
{
actions: [restartAnswer, quitAnswer],
closeLabel: 'Close',
icon,
message,
timeout: false,
title // https://github.com/DefinitelyTyped/DefinitelyTyped/pull/42303
},
(err, _, metadata) => {
if (err || !metadata) {
return;
}
if (metadata.activationValue === quitAnswer) {
(0, _exit().default)(0);
return;
}
if (metadata.activationValue === restartAnswer) {
this._startRun(this._globalConfig);
}
}
);
}
}
this._context.previousSuccess = success;
this._context.firstRun = false;
}
}
exports.default = NotifyReporter;
function loadNotifier() {
try {
return require('node-notifier');
} catch (err) {
if (err.code !== 'MODULE_NOT_FOUND') {
throw err;
} else {
throw Error(
'notify reporter requires optional dependeny node-notifier but it was not found'
);
}
}
}

View file

@ -0,0 +1,21 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { AggregatedResult } from '@jest/test-result';
import type { Context, ReporterOnStartOptions } from './types';
import BaseReporter from './base_reporter';
export default class SummaryReporter extends BaseReporter {
private _estimatedTime;
private _globalConfig;
constructor(globalConfig: Config.GlobalConfig);
private _write;
onRunStart(aggregatedResults: AggregatedResult, options: ReporterOnStartOptions): void;
onRunComplete(contexts: Set<Context>, aggregatedResults: AggregatedResult): void;
private _printSnapshotSummary;
private _printSummary;
private _getTestSummary;
}

272
node_modules/@jest/reporters/build/summary_reporter.js generated vendored Normal file
View file

@ -0,0 +1,272 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
var _base_reporter = _interopRequireDefault(require('./base_reporter'));
var _utils = require('./utils');
var _get_result_header = _interopRequireDefault(require('./get_result_header'));
var _get_snapshot_summary = _interopRequireDefault(
require('./get_snapshot_summary')
);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const TEST_SUMMARY_THRESHOLD = 20;
const NPM_EVENTS = new Set([
'prepublish',
'publish',
'postpublish',
'preinstall',
'install',
'postinstall',
'preuninstall',
'uninstall',
'postuninstall',
'preversion',
'version',
'postversion',
'pretest',
'test',
'posttest',
'prestop',
'stop',
'poststop',
'prestart',
'start',
'poststart',
'prerestart',
'restart',
'postrestart'
]);
const {
npm_config_user_agent,
npm_lifecycle_event,
npm_lifecycle_script
} = process.env;
class SummaryReporter extends _base_reporter.default {
constructor(globalConfig) {
super();
_defineProperty(this, '_estimatedTime', void 0);
_defineProperty(this, '_globalConfig', void 0);
this._globalConfig = globalConfig;
this._estimatedTime = 0;
} // If we write more than one character at a time it is possible that
// Node.js exits in the middle of printing the result. This was first observed
// in Node.js 0.10 and still persists in Node.js 6.7+.
// Let's print the test failure summary character by character which is safer
// when hundreds of tests are failing.
_write(string) {
for (let i = 0; i < string.length; i++) {
process.stderr.write(string.charAt(i));
}
}
onRunStart(aggregatedResults, options) {
super.onRunStart(aggregatedResults, options);
this._estimatedTime = options.estimatedTime;
}
onRunComplete(contexts, aggregatedResults) {
const {numTotalTestSuites, testResults, wasInterrupted} = aggregatedResults;
if (numTotalTestSuites) {
const lastResult = testResults[testResults.length - 1]; // Print a newline if the last test did not fail to line up newlines
// similar to when an error would have been thrown in the test.
if (
!this._globalConfig.verbose &&
lastResult &&
!lastResult.numFailingTests &&
!lastResult.testExecError
) {
this.log('');
}
this._printSummary(aggregatedResults, this._globalConfig);
this._printSnapshotSummary(
aggregatedResults.snapshot,
this._globalConfig
);
if (numTotalTestSuites) {
let message = (0, _utils.getSummary)(aggregatedResults, {
estimatedTime: this._estimatedTime
});
if (!this._globalConfig.silent) {
message +=
'\n' +
(wasInterrupted
? _chalk().default.bold.red('Test run was interrupted.')
: this._getTestSummary(contexts, this._globalConfig));
}
this.log(message);
}
}
}
_printSnapshotSummary(snapshots, globalConfig) {
if (
snapshots.added ||
snapshots.filesRemoved ||
snapshots.unchecked ||
snapshots.unmatched ||
snapshots.updated
) {
let updateCommand;
const event = npm_lifecycle_event || '';
const prefix = NPM_EVENTS.has(event) ? '' : 'run ';
const isYarn =
typeof npm_config_user_agent === 'string' &&
npm_config_user_agent.includes('yarn');
const client = isYarn ? 'yarn' : 'npm';
const scriptUsesJest =
typeof npm_lifecycle_script === 'string' &&
npm_lifecycle_script.includes('jest');
if (globalConfig.watch || globalConfig.watchAll) {
updateCommand = 'press `u`';
} else if (event && scriptUsesJest) {
updateCommand = `run \`${
client + ' ' + prefix + event + (isYarn ? '' : ' --')
} -u\``;
} else {
updateCommand = 're-run jest with `-u`';
}
const snapshotSummary = (0, _get_snapshot_summary.default)(
snapshots,
globalConfig,
updateCommand
);
snapshotSummary.forEach(this.log);
this.log(''); // print empty line
}
}
_printSummary(aggregatedResults, globalConfig) {
// If there were any failing tests and there was a large number of tests
// executed, re-print the failing results at the end of execution output.
const failedTests = aggregatedResults.numFailedTests;
const runtimeErrors = aggregatedResults.numRuntimeErrorTestSuites;
if (
failedTests + runtimeErrors > 0 &&
aggregatedResults.numTotalTestSuites > TEST_SUMMARY_THRESHOLD
) {
this.log(_chalk().default.bold('Summary of all failing tests'));
aggregatedResults.testResults.forEach(testResult => {
const {failureMessage} = testResult;
if (failureMessage) {
this._write(
(0, _get_result_header.default)(testResult, globalConfig) +
'\n' +
failureMessage +
'\n'
);
}
});
this.log(''); // print empty line
}
}
_getTestSummary(contexts, globalConfig) {
const getMatchingTestsInfo = () => {
const prefix = globalConfig.findRelatedTests
? ' related to files matching '
: ' matching ';
return (
_chalk().default.dim(prefix) +
(0, _jestUtil().testPathPatternToRegExp)(
globalConfig.testPathPattern
).toString()
);
};
let testInfo = '';
if (globalConfig.runTestsByPath) {
testInfo = _chalk().default.dim(' within paths');
} else if (globalConfig.onlyChanged) {
testInfo = _chalk().default.dim(' related to changed files');
} else if (globalConfig.testPathPattern) {
testInfo = getMatchingTestsInfo();
}
let nameInfo = '';
if (globalConfig.runTestsByPath) {
nameInfo = ' ' + globalConfig.nonFlagArgs.map(p => `"${p}"`).join(', ');
} else if (globalConfig.testNamePattern) {
nameInfo =
_chalk().default.dim(' with tests matching ') +
`"${globalConfig.testNamePattern}"`;
}
const contextInfo =
contexts.size > 1
? _chalk().default.dim(' in ') +
contexts.size +
_chalk().default.dim(' projects')
: '';
return (
_chalk().default.dim('Ran all test suites') +
testInfo +
nameInfo +
contextInfo +
_chalk().default.dim('.')
);
}
}
exports.default = SummaryReporter;

75
node_modules/@jest/reporters/build/types.d.ts generated vendored Normal file
View file

@ -0,0 +1,75 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { AggregatedResult, SerializableError, TestCaseResult, TestResult } from '@jest/test-result';
import type { FS as HasteFS, ModuleMap } from 'jest-haste-map';
import type { ResolverType } from 'jest-resolve';
import type { worker } from './coverage_worker';
export declare type ReporterOnStartOptions = {
estimatedTime: number;
showStatus: boolean;
};
export declare type Context = {
config: Config.ProjectConfig;
hasteFS: HasteFS;
moduleMap: ModuleMap;
resolver: ResolverType;
};
export declare type Test = {
context: Context;
duration?: number;
path: Config.Path;
};
export declare type CoverageWorker = {
worker: typeof worker;
};
export declare type CoverageReporterOptions = {
changedFiles?: Set<Config.Path>;
sourcesRelatedToTestsInChangedFiles?: Set<Config.Path>;
};
export declare type CoverageReporterSerializedOptions = {
changedFiles?: Array<Config.Path>;
sourcesRelatedToTestsInChangedFiles?: Array<Config.Path>;
};
export declare type OnTestStart = (test: Test) => Promise<void>;
export declare type OnTestFailure = (test: Test, error: SerializableError) => Promise<any>;
export declare type OnTestSuccess = (test: Test, result: TestResult) => Promise<any>;
export interface Reporter {
readonly onTestResult?: (test: Test, testResult: TestResult, aggregatedResult: AggregatedResult) => Promise<void> | void;
readonly onTestFileResult?: (test: Test, testResult: TestResult, aggregatedResult: AggregatedResult) => Promise<void> | void;
readonly onTestCaseResult?: (test: Test, testCaseResult: TestCaseResult) => Promise<void> | void;
readonly onRunStart: (results: AggregatedResult, options: ReporterOnStartOptions) => Promise<void> | void;
readonly onTestStart?: (test: Test) => Promise<void> | void;
readonly onTestFileStart?: (test: Test) => Promise<void> | void;
readonly onRunComplete: (contexts: Set<Context>, results: AggregatedResult) => Promise<void> | void;
readonly getLastError: () => Error | void;
}
export declare type SummaryOptions = {
currentTestCases?: Array<{
test: Test;
testCaseResult: TestCaseResult;
}>;
estimatedTime?: number;
roundTime?: boolean;
width?: number;
};
export declare type TestRunnerOptions = {
serial: boolean;
};
export declare type TestRunData = Array<{
context: Context;
matches: {
allTests: number;
tests: Array<Test>;
total: number;
};
}>;
export declare type TestSchedulerContext = {
firstRun: boolean;
previousSuccess: boolean;
changedFiles?: Set<Config.Path>;
};

1
node_modules/@jest/reporters/build/types.js generated vendored Normal file
View file

@ -0,0 +1 @@
'use strict';

18
node_modules/@jest/reporters/build/utils.d.ts generated vendored Normal file
View file

@ -0,0 +1,18 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { AggregatedResult } from '@jest/test-result';
import type { SummaryOptions } from './types';
export declare const printDisplayName: (config: Config.ProjectConfig) => string;
export declare const trimAndFormatPath: (pad: number, config: Config.ProjectConfig | Config.GlobalConfig, testPath: Config.Path, columns: number) => string;
export declare const formatTestPath: (config: Config.GlobalConfig | Config.ProjectConfig, testPath: Config.Path) => string;
export declare const relativePath: (config: Config.GlobalConfig | Config.ProjectConfig, testPath: Config.Path) => {
basename: string;
dirname: string;
};
export declare const getSummary: (aggregatedResults: AggregatedResult, options?: SummaryOptions | undefined) => string;
export declare const wrapAnsiString: (string: string, terminalWidth: number) => string;

429
node_modules/@jest/reporters/build/utils.js generated vendored Normal file
View file

@ -0,0 +1,429 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.wrapAnsiString = exports.getSummary = exports.relativePath = exports.formatTestPath = exports.trimAndFormatPath = exports.printDisplayName = void 0;
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _slash() {
const data = _interopRequireDefault(require('slash'));
_slash = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _getRequireWildcardCache() {
if (typeof WeakMap !== 'function') return null;
var cache = new WeakMap();
_getRequireWildcardCache = function () {
return cache;
};
return cache;
}
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
}
if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
return {default: obj};
}
var cache = _getRequireWildcardCache();
if (cache && cache.has(obj)) {
return cache.get(obj);
}
var newObj = {};
var hasPropertyDescriptor =
Object.defineProperty && Object.getOwnPropertyDescriptor;
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
var desc = hasPropertyDescriptor
? Object.getOwnPropertyDescriptor(obj, key)
: null;
if (desc && (desc.get || desc.set)) {
Object.defineProperty(newObj, key, desc);
} else {
newObj[key] = obj[key];
}
}
}
newObj.default = obj;
if (cache) {
cache.set(obj, newObj);
}
return newObj;
}
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const PROGRESS_BAR_WIDTH = 40;
const printDisplayName = config => {
const {displayName} = config;
const white = _chalk().default.reset.inverse.white;
if (!displayName) {
return '';
}
const {name, color} = displayName;
const chosenColor = _chalk().default.reset.inverse[color]
? _chalk().default.reset.inverse[color]
: white;
return _chalk().default.supportsColor ? chosenColor(` ${name} `) : name;
};
exports.printDisplayName = printDisplayName;
const trimAndFormatPath = (pad, config, testPath, columns) => {
const maxLength = columns - pad;
const relative = relativePath(config, testPath);
const {basename} = relative;
let {dirname} = relative; // length is ok
if ((dirname + path().sep + basename).length <= maxLength) {
return (0, _slash().default)(
_chalk().default.dim(dirname + path().sep) +
_chalk().default.bold(basename)
);
} // we can fit trimmed dirname and full basename
const basenameLength = basename.length;
if (basenameLength + 4 < maxLength) {
const dirnameLength = maxLength - 4 - basenameLength;
dirname =
'...' + dirname.slice(dirname.length - dirnameLength, dirname.length);
return (0, _slash().default)(
_chalk().default.dim(dirname + path().sep) +
_chalk().default.bold(basename)
);
}
if (basenameLength + 4 === maxLength) {
return (0, _slash().default)(
_chalk().default.dim('...' + path().sep) + _chalk().default.bold(basename)
);
} // can't fit dirname, but can fit trimmed basename
return (0, _slash().default)(
_chalk().default.bold(
'...' + basename.slice(basename.length - maxLength - 4, basename.length)
)
);
};
exports.trimAndFormatPath = trimAndFormatPath;
const formatTestPath = (config, testPath) => {
const {dirname, basename} = relativePath(config, testPath);
return (0, _slash().default)(
_chalk().default.dim(dirname + path().sep) + _chalk().default.bold(basename)
);
};
exports.formatTestPath = formatTestPath;
const relativePath = (config, testPath) => {
// this function can be called with ProjectConfigs or GlobalConfigs. GlobalConfigs
// do not have config.cwd, only config.rootDir. Try using config.cwd, fallback
// to config.rootDir. (Also, some unit just use config.rootDir, which is ok)
testPath = path().relative(config.cwd || config.rootDir, testPath);
const dirname = path().dirname(testPath);
const basename = path().basename(testPath);
return {
basename,
dirname
};
};
exports.relativePath = relativePath;
const getValuesCurrentTestCases = (currentTestCases = []) => {
let numFailingTests = 0;
let numPassingTests = 0;
let numPendingTests = 0;
let numTodoTests = 0;
let numTotalTests = 0;
currentTestCases.forEach(testCase => {
switch (testCase.testCaseResult.status) {
case 'failed': {
numFailingTests++;
break;
}
case 'passed': {
numPassingTests++;
break;
}
case 'skipped': {
numPendingTests++;
break;
}
case 'todo': {
numTodoTests++;
break;
}
}
numTotalTests++;
});
return {
numFailingTests,
numPassingTests,
numPendingTests,
numTodoTests,
numTotalTests
};
};
const getSummary = (aggregatedResults, options) => {
let runTime = (Date.now() - aggregatedResults.startTime) / 1000;
if (options && options.roundTime) {
runTime = Math.floor(runTime);
}
const valuesForCurrentTestCases = getValuesCurrentTestCases(
options === null || options === void 0 ? void 0 : options.currentTestCases
);
const estimatedTime = (options && options.estimatedTime) || 0;
const snapshotResults = aggregatedResults.snapshot;
const snapshotsAdded = snapshotResults.added;
const snapshotsFailed = snapshotResults.unmatched;
const snapshotsOutdated = snapshotResults.unchecked;
const snapshotsFilesRemoved = snapshotResults.filesRemoved;
const snapshotsDidUpdate = snapshotResults.didUpdate;
const snapshotsPassed = snapshotResults.matched;
const snapshotsTotal = snapshotResults.total;
const snapshotsUpdated = snapshotResults.updated;
const suitesFailed = aggregatedResults.numFailedTestSuites;
const suitesPassed = aggregatedResults.numPassedTestSuites;
const suitesPending = aggregatedResults.numPendingTestSuites;
const suitesRun = suitesFailed + suitesPassed;
const suitesTotal = aggregatedResults.numTotalTestSuites;
const testsFailed = aggregatedResults.numFailedTests;
const testsPassed = aggregatedResults.numPassedTests;
const testsPending = aggregatedResults.numPendingTests;
const testsTodo = aggregatedResults.numTodoTests;
const testsTotal = aggregatedResults.numTotalTests;
const width = (options && options.width) || 0;
const suites =
_chalk().default.bold('Test Suites: ') +
(suitesFailed
? _chalk().default.bold.red(`${suitesFailed} failed`) + ', '
: '') +
(suitesPending
? _chalk().default.bold.yellow(`${suitesPending} skipped`) + ', '
: '') +
(suitesPassed
? _chalk().default.bold.green(`${suitesPassed} passed`) + ', '
: '') +
(suitesRun !== suitesTotal
? suitesRun + ' of ' + suitesTotal
: suitesTotal) +
` total`;
const updatedTestsFailed =
testsFailed + valuesForCurrentTestCases.numFailingTests;
const updatedTestsPending =
testsPending + valuesForCurrentTestCases.numPendingTests;
const updatedTestsTodo = testsTodo + valuesForCurrentTestCases.numTodoTests;
const updatedTestsPassed =
testsPassed + valuesForCurrentTestCases.numPassingTests;
const updatedTestsTotal =
testsTotal + valuesForCurrentTestCases.numTotalTests;
const tests =
_chalk().default.bold('Tests: ') +
(updatedTestsFailed > 0
? _chalk().default.bold.red(`${updatedTestsFailed} failed`) + ', '
: '') +
(updatedTestsPending > 0
? _chalk().default.bold.yellow(`${updatedTestsPending} skipped`) + ', '
: '') +
(updatedTestsTodo > 0
? _chalk().default.bold.magenta(`${updatedTestsTodo} todo`) + ', '
: '') +
(updatedTestsPassed > 0
? _chalk().default.bold.green(`${updatedTestsPassed} passed`) + ', '
: '') +
`${updatedTestsTotal} total`;
const snapshots =
_chalk().default.bold('Snapshots: ') +
(snapshotsFailed
? _chalk().default.bold.red(`${snapshotsFailed} failed`) + ', '
: '') +
(snapshotsOutdated && !snapshotsDidUpdate
? _chalk().default.bold.yellow(`${snapshotsOutdated} obsolete`) + ', '
: '') +
(snapshotsOutdated && snapshotsDidUpdate
? _chalk().default.bold.green(`${snapshotsOutdated} removed`) + ', '
: '') +
(snapshotsFilesRemoved && !snapshotsDidUpdate
? _chalk().default.bold.yellow(
(0, _jestUtil().pluralize)('file', snapshotsFilesRemoved) +
' obsolete'
) + ', '
: '') +
(snapshotsFilesRemoved && snapshotsDidUpdate
? _chalk().default.bold.green(
(0, _jestUtil().pluralize)('file', snapshotsFilesRemoved) + ' removed'
) + ', '
: '') +
(snapshotsUpdated
? _chalk().default.bold.green(`${snapshotsUpdated} updated`) + ', '
: '') +
(snapshotsAdded
? _chalk().default.bold.green(`${snapshotsAdded} written`) + ', '
: '') +
(snapshotsPassed
? _chalk().default.bold.green(`${snapshotsPassed} passed`) + ', '
: '') +
`${snapshotsTotal} total`;
const time = renderTime(runTime, estimatedTime, width);
return [suites, tests, snapshots, time].join('\n');
};
exports.getSummary = getSummary;
const renderTime = (runTime, estimatedTime, width) => {
// If we are more than one second over the estimated time, highlight it.
const renderedTime =
estimatedTime && runTime >= estimatedTime + 1
? _chalk().default.bold.yellow((0, _jestUtil().formatTime)(runTime, 0))
: (0, _jestUtil().formatTime)(runTime, 0);
let time = _chalk().default.bold(`Time:`) + ` ${renderedTime}`;
if (runTime < estimatedTime) {
time += `, estimated ${(0, _jestUtil().formatTime)(estimatedTime, 0)}`;
} // Only show a progress bar if the test run is actually going to take
// some time.
if (estimatedTime > 2 && runTime < estimatedTime && width) {
const availableWidth = Math.min(PROGRESS_BAR_WIDTH, width);
const length = Math.min(
Math.floor((runTime / estimatedTime) * availableWidth),
availableWidth
);
if (availableWidth >= 2) {
time +=
'\n' +
_chalk().default.green('█').repeat(length) +
_chalk()
.default.white('█')
.repeat(availableWidth - length);
}
}
return time;
}; // word-wrap a string that contains ANSI escape sequences.
// ANSI escape sequences do not add to the string length.
const wrapAnsiString = (string, terminalWidth) => {
if (terminalWidth === 0) {
// if the terminal width is zero, don't bother word-wrapping
return string;
}
const ANSI_REGEXP = /[\u001b\u009b]\[\d{1,2}m/g;
const tokens = [];
let lastIndex = 0;
let match;
while ((match = ANSI_REGEXP.exec(string))) {
const ansi = match[0];
const index = match['index'];
if (index != lastIndex) {
tokens.push(['string', string.slice(lastIndex, index)]);
}
tokens.push(['ansi', ansi]);
lastIndex = index + ansi.length;
}
if (lastIndex != string.length - 1) {
tokens.push(['string', string.slice(lastIndex, string.length)]);
}
let lastLineLength = 0;
return tokens
.reduce(
(lines, [kind, token]) => {
if (kind === 'string') {
if (lastLineLength + token.length > terminalWidth) {
while (token.length) {
const chunk = token.slice(0, terminalWidth - lastLineLength);
const remaining = token.slice(
terminalWidth - lastLineLength,
token.length
);
lines[lines.length - 1] += chunk;
lastLineLength += chunk.length;
token = remaining;
if (token.length) {
lines.push('');
lastLineLength = 0;
}
}
} else {
lines[lines.length - 1] += token;
lastLineLength += token.length;
}
} else {
lines[lines.length - 1] += token;
}
return lines;
},
['']
)
.join('\n');
};
exports.wrapAnsiString = wrapAnsiString;

View file

@ -0,0 +1,24 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type { Config } from '@jest/types';
import type { AggregatedResult, AssertionResult, Suite, TestResult } from '@jest/test-result';
import type { Test } from './types';
import DefaultReporter from './default_reporter';
export default class VerboseReporter extends DefaultReporter {
protected _globalConfig: Config.GlobalConfig;
constructor(globalConfig: Config.GlobalConfig);
static filterTestResults(testResults: Array<AssertionResult>): Array<AssertionResult>;
static groupTestsBySuites(testResults: Array<AssertionResult>): Suite;
onTestResult(test: Test, result: TestResult, aggregatedResults: AggregatedResult): void;
private _logTestResults;
private _logSuite;
private _getIcon;
private _logTest;
private _logTests;
private _logTodoOrPendingTest;
private _logLine;
}

209
node_modules/@jest/reporters/build/verbose_reporter.js generated vendored Normal file
View file

@ -0,0 +1,209 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
function _chalk() {
const data = _interopRequireDefault(require('chalk'));
_chalk = function () {
return data;
};
return data;
}
function _jestUtil() {
const data = require('jest-util');
_jestUtil = function () {
return data;
};
return data;
}
var _default_reporter = _interopRequireDefault(require('./default_reporter'));
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {default: obj};
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
const {ICONS} = _jestUtil().specialChars;
class VerboseReporter extends _default_reporter.default {
constructor(globalConfig) {
super(globalConfig);
_defineProperty(this, '_globalConfig', void 0);
this._globalConfig = globalConfig;
}
static filterTestResults(testResults) {
return testResults.filter(({status}) => status !== 'pending');
}
static groupTestsBySuites(testResults) {
const root = {
suites: [],
tests: [],
title: ''
};
testResults.forEach(testResult => {
let targetSuite = root; // Find the target suite for this test,
// creating nested suites as necessary.
for (const title of testResult.ancestorTitles) {
let matchingSuite = targetSuite.suites.find(s => s.title === title);
if (!matchingSuite) {
matchingSuite = {
suites: [],
tests: [],
title
};
targetSuite.suites.push(matchingSuite);
}
targetSuite = matchingSuite;
}
targetSuite.tests.push(testResult);
});
return root;
}
onTestResult(test, result, aggregatedResults) {
super.testFinished(test.context.config, result, aggregatedResults);
if (!result.skipped) {
this.printTestFileHeader(
result.testFilePath,
test.context.config,
result
);
if (!result.testExecError && !result.skipped) {
this._logTestResults(result.testResults);
}
this.printTestFileFailureMessage(
result.testFilePath,
test.context.config,
result
);
}
super.forceFlushBufferedOutput();
}
_logTestResults(testResults) {
this._logSuite(VerboseReporter.groupTestsBySuites(testResults), 0);
this._logLine();
}
_logSuite(suite, indentLevel) {
if (suite.title) {
this._logLine(suite.title, indentLevel);
}
this._logTests(suite.tests, indentLevel + 1);
suite.suites.forEach(suite => this._logSuite(suite, indentLevel + 1));
}
_getIcon(status) {
if (status === 'failed') {
return _chalk().default.red(ICONS.failed);
} else if (status === 'pending') {
return _chalk().default.yellow(ICONS.pending);
} else if (status === 'todo') {
return _chalk().default.magenta(ICONS.todo);
} else {
return _chalk().default.green(ICONS.success);
}
}
_logTest(test, indentLevel) {
const status = this._getIcon(test.status);
const time = test.duration
? ` (${(0, _jestUtil().formatTime)(Math.round(test.duration))})`
: '';
this._logLine(
status + ' ' + _chalk().default.dim(test.title + time),
indentLevel
);
}
_logTests(tests, indentLevel) {
if (this._globalConfig.expand) {
tests.forEach(test => this._logTest(test, indentLevel));
} else {
const summedTests = tests.reduce(
(result, test) => {
if (test.status === 'pending') {
result.pending.push(test);
} else if (test.status === 'todo') {
result.todo.push(test);
} else {
this._logTest(test, indentLevel);
}
return result;
},
{
pending: [],
todo: []
}
);
if (summedTests.pending.length > 0) {
summedTests.pending.forEach(this._logTodoOrPendingTest(indentLevel));
}
if (summedTests.todo.length > 0) {
summedTests.todo.forEach(this._logTodoOrPendingTest(indentLevel));
}
}
}
_logTodoOrPendingTest(indentLevel) {
return test => {
const printedTestStatus =
test.status === 'pending' ? 'skipped' : test.status;
const icon = this._getIcon(test.status);
const text = _chalk().default.dim(`${printedTestStatus} ${test.title}`);
this._logLine(`${icon} ${text}`, indentLevel);
};
}
_logLine(str, indentLevel) {
const indentation = ' '.repeat(indentLevel || 0);
this.log(indentation + (str || ''));
}
}
exports.default = VerboseReporter;

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Facebook, Inc. and its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,187 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="node" />
import type * as Global from './Global';
declare type Process = NodeJS.Process;
export declare type DoneFn = Global.DoneFn;
export declare type BlockFn = Global.BlockFn;
export declare type BlockName = Global.BlockName;
export declare type BlockMode = void | 'skip' | 'only' | 'todo';
export declare type TestMode = BlockMode;
export declare type TestName = Global.TestName;
export declare type TestFn = Global.TestFn;
export declare type HookFn = Global.HookFn;
export declare type AsyncFn = TestFn | HookFn;
export declare type SharedHookType = 'afterAll' | 'beforeAll';
export declare type HookType = SharedHookType | 'afterEach' | 'beforeEach';
export declare type TestContext = Record<string, any>;
export declare type Exception = any;
export declare type FormattedError = string;
export declare type Hook = {
asyncError: Error;
fn: HookFn;
type: HookType;
parent: DescribeBlock;
timeout: number | undefined | null;
};
export interface EventHandler {
(event: AsyncEvent, state: State): void | Promise<void>;
(event: SyncEvent, state: State): void;
}
export declare type Event = SyncEvent | AsyncEvent;
export declare type SyncEvent = {
asyncError: Error;
mode: BlockMode;
name: 'start_describe_definition';
blockName: BlockName;
} | {
mode: BlockMode;
name: 'finish_describe_definition';
blockName: BlockName;
} | {
asyncError: Error;
name: 'add_hook';
hookType: HookType;
fn: HookFn;
timeout: number | undefined;
} | {
asyncError: Error;
name: 'add_test';
testName: TestName;
fn?: TestFn;
mode?: TestMode;
timeout: number | undefined;
} | {
name: 'error';
error: Exception;
};
export declare type AsyncEvent = {
name: 'setup';
testNamePattern?: string;
parentProcess: Process;
} | {
name: 'include_test_location_in_result';
} | {
name: 'hook_start';
hook: Hook;
} | {
name: 'hook_success';
describeBlock?: DescribeBlock;
test?: TestEntry;
hook: Hook;
} | {
name: 'hook_failure';
error: string | Exception;
describeBlock?: DescribeBlock;
test?: TestEntry;
hook: Hook;
} | {
name: 'test_fn_start';
test: TestEntry;
} | {
name: 'test_fn_success';
test: TestEntry;
} | {
name: 'test_fn_failure';
error: Exception;
test: TestEntry;
} | {
name: 'test_retry';
test: TestEntry;
} | {
name: 'test_start';
test: TestEntry;
} | {
name: 'test_skip';
test: TestEntry;
} | {
name: 'test_todo';
test: TestEntry;
} | {
name: 'test_done';
test: TestEntry;
} | {
name: 'run_describe_start';
describeBlock: DescribeBlock;
} | {
name: 'run_describe_finish';
describeBlock: DescribeBlock;
} | {
name: 'run_start';
} | {
name: 'run_finish';
} | {
name: 'teardown';
};
export declare type MatcherResults = {
actual: unknown;
expected: unknown;
name: string;
pass: boolean;
};
export declare type TestStatus = 'skip' | 'done' | 'todo';
export declare type TestResult = {
duration?: number | null;
errors: Array<FormattedError>;
errorsDetailed: Array<MatcherResults | unknown>;
invocations: number;
status: TestStatus;
location?: {
column: number;
line: number;
} | null;
testPath: Array<TestName | BlockName>;
};
export declare type RunResult = {
unhandledErrors: Array<FormattedError>;
testResults: TestResults;
};
export declare type TestResults = Array<TestResult>;
export declare type GlobalErrorHandlers = {
uncaughtException: Array<(exception: Exception) => void>;
unhandledRejection: Array<(exception: Exception, promise: Promise<any>) => void>;
};
export declare type State = {
currentDescribeBlock: DescribeBlock;
currentlyRunningTest?: TestEntry | null;
expand?: boolean;
hasFocusedTests: boolean;
hasStarted: boolean;
originalGlobalErrorHandlers?: GlobalErrorHandlers;
parentProcess: Process | null;
rootDescribeBlock: DescribeBlock;
testNamePattern?: RegExp | null;
testTimeout: number;
unhandledErrors: Array<Exception>;
includeTestLocationInResult: boolean;
};
export declare type DescribeBlock = {
type: 'describeBlock';
children: Array<DescribeBlock | TestEntry>;
hooks: Array<Hook>;
mode: BlockMode;
name: BlockName;
parent?: DescribeBlock;
/** @deprecated Please get from `children` array instead */
tests: Array<TestEntry>;
};
export declare type TestError = Exception | [Exception | undefined, Exception];
export declare type TestEntry = {
type: 'test';
asyncError: Exception;
errors: Array<TestError>;
fn?: TestFn;
invocations: number;
mode: TestMode;
name: TestName;
parent: DescribeBlock;
startedAt?: number | null;
duration?: number | null;
status?: TestStatus | null;
timeout?: number;
};
export {};

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1,421 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="node" />
import type { Arguments } from 'yargs';
import type { ReportOptions } from 'istanbul-reports';
import type { ForegroundColor } from 'chalk';
declare type CoverageProvider = 'babel' | 'v8';
export declare type Path = string;
export declare type Glob = string;
export declare type HasteConfig = {
computeSha1?: boolean;
defaultPlatform?: string | null;
hasteImplModulePath?: string;
platforms?: Array<string>;
throwOnModuleCollision?: boolean;
};
export declare type CoverageReporterName = keyof ReportOptions;
export declare type CoverageReporterWithOptions<K = CoverageReporterName> = K extends CoverageReporterName ? ReportOptions[K] extends never ? never : [K, Partial<ReportOptions[K]>] : never;
export declare type CoverageReporters = Array<CoverageReporterName | CoverageReporterWithOptions>;
export declare type ReporterConfig = [string, Record<string, unknown>];
export declare type TransformerConfig = [string, Record<string, unknown>];
export interface ConfigGlobals {
[K: string]: unknown;
}
export declare type DefaultOptions = {
automock: boolean;
bail: number;
cache: boolean;
cacheDirectory: Path;
changedFilesWithAncestor: boolean;
clearMocks: boolean;
collectCoverage: boolean;
coveragePathIgnorePatterns: Array<string>;
coverageReporters: Array<CoverageReporterName>;
coverageProvider: CoverageProvider;
errorOnDeprecated: boolean;
expand: boolean;
forceCoverageMatch: Array<Glob>;
globals: ConfigGlobals;
haste: HasteConfig;
maxConcurrency: number;
maxWorkers: number | string;
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
moduleNameMapper: Record<string, string | Array<string>>;
modulePathIgnorePatterns: Array<string>;
noStackTrace: boolean;
notify: boolean;
notifyMode: NotifyMode;
prettierPath: string;
resetMocks: boolean;
resetModules: boolean;
restoreMocks: boolean;
roots: Array<Path>;
runTestsByPath: boolean;
runner: 'jest-runner';
setupFiles: Array<Path>;
setupFilesAfterEnv: Array<Path>;
skipFilter: boolean;
slowTestThreshold: number;
snapshotSerializers: Array<Path>;
testEnvironment: string;
testEnvironmentOptions: Record<string, any>;
testFailureExitCode: string | number;
testLocationInResults: boolean;
testMatch: Array<Glob>;
testPathIgnorePatterns: Array<string>;
testRegex: Array<string>;
testRunner: string;
testSequencer: string;
testURL: string;
timers: 'real' | 'fake';
transformIgnorePatterns: Array<Glob>;
useStderr: boolean;
watch: boolean;
watchPathIgnorePatterns: Array<string>;
watchman: boolean;
};
export declare type DisplayName = {
name: string;
color: typeof ForegroundColor;
};
export declare type InitialOptionsWithRootDir = InitialOptions & Required<Pick<InitialOptions, 'rootDir'>>;
export declare type InitialOptions = Partial<{
automock: boolean;
bail: boolean | number;
cache: boolean;
cacheDirectory: Path;
clearMocks: boolean;
changedFilesWithAncestor: boolean;
changedSince: string;
collectCoverage: boolean;
collectCoverageFrom: Array<Glob>;
collectCoverageOnlyFrom: {
[key: string]: boolean;
};
coverageDirectory: string;
coveragePathIgnorePatterns: Array<string>;
coverageProvider: CoverageProvider;
coverageReporters: CoverageReporters;
coverageThreshold: {
global: {
[key: string]: number;
};
};
dependencyExtractor: string;
detectLeaks: boolean;
detectOpenHandles: boolean;
displayName: string | DisplayName;
expand: boolean;
extraGlobals: Array<string>;
filter: Path;
findRelatedTests: boolean;
forceCoverageMatch: Array<Glob>;
forceExit: boolean;
json: boolean;
globals: ConfigGlobals;
globalSetup: string | null | undefined;
globalTeardown: string | null | undefined;
haste: HasteConfig;
reporters: Array<string | ReporterConfig>;
logHeapUsage: boolean;
lastCommit: boolean;
listTests: boolean;
mapCoverage: boolean;
maxConcurrency: number;
maxWorkers: number | string;
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
moduleLoader: Path;
moduleNameMapper: {
[key: string]: string | Array<string>;
};
modulePathIgnorePatterns: Array<string>;
modulePaths: Array<string>;
name: string;
noStackTrace: boolean;
notify: boolean;
notifyMode: string;
onlyChanged: boolean;
outputFile: Path;
passWithNoTests: boolean;
preprocessorIgnorePatterns: Array<Glob>;
preset: string | null | undefined;
prettierPath: string | null | undefined;
projects: Array<Glob>;
replname: string | null | undefined;
resetMocks: boolean;
resetModules: boolean;
resolver: Path | null | undefined;
restoreMocks: boolean;
rootDir: Path;
roots: Array<Path>;
runner: string;
runTestsByPath: boolean;
scriptPreprocessor: string;
setupFiles: Array<Path>;
setupTestFrameworkScriptFile: Path;
setupFilesAfterEnv: Array<Path>;
silent: boolean;
skipFilter: boolean;
skipNodeResolution: boolean;
slowTestThreshold: number;
snapshotResolver: Path;
snapshotSerializers: Array<Path>;
errorOnDeprecated: boolean;
testEnvironment: string;
testEnvironmentOptions: Record<string, any>;
testFailureExitCode: string | number;
testLocationInResults: boolean;
testMatch: Array<Glob>;
testNamePattern: string;
testPathDirs: Array<Path>;
testPathIgnorePatterns: Array<string>;
testRegex: string | Array<string>;
testResultsProcessor: string;
testRunner: string;
testSequencer: string;
testURL: string;
testTimeout: number;
timers: 'real' | 'fake';
transform: {
[regex: string]: Path | TransformerConfig;
};
transformIgnorePatterns: Array<Glob>;
watchPathIgnorePatterns: Array<string>;
unmockedModulePathPatterns: Array<string>;
updateSnapshot: boolean;
useStderr: boolean;
verbose?: boolean;
watch: boolean;
watchAll: boolean;
watchman: boolean;
watchPlugins: Array<string | [string, Record<string, any>]>;
}>;
export declare type SnapshotUpdateState = 'all' | 'new' | 'none';
declare type NotifyMode = 'always' | 'failure' | 'success' | 'change' | 'success-change' | 'failure-change';
export declare type CoverageThresholdValue = {
branches?: number;
functions?: number;
lines?: number;
statements?: number;
};
declare type CoverageThreshold = {
[path: string]: CoverageThresholdValue;
global: CoverageThresholdValue;
};
export declare type GlobalConfig = {
bail: number;
changedSince?: string;
changedFilesWithAncestor: boolean;
collectCoverage: boolean;
collectCoverageFrom: Array<Glob>;
collectCoverageOnlyFrom?: {
[key: string]: boolean;
};
coverageDirectory: string;
coveragePathIgnorePatterns?: Array<string>;
coverageProvider: CoverageProvider;
coverageReporters: CoverageReporters;
coverageThreshold?: CoverageThreshold;
detectLeaks: boolean;
detectOpenHandles: boolean;
enabledTestsMap?: {
[key: string]: {
[key: string]: boolean;
};
};
expand: boolean;
filter?: Path;
findRelatedTests: boolean;
forceExit: boolean;
json: boolean;
globalSetup?: string;
globalTeardown?: string;
lastCommit: boolean;
logHeapUsage: boolean;
listTests: boolean;
maxConcurrency: number;
maxWorkers: number;
noStackTrace: boolean;
nonFlagArgs: Array<string>;
noSCM?: boolean;
notify: boolean;
notifyMode: NotifyMode;
outputFile?: Path;
onlyChanged: boolean;
onlyFailures: boolean;
passWithNoTests: boolean;
projects: Array<Glob>;
replname?: string;
reporters?: Array<string | ReporterConfig>;
runTestsByPath: boolean;
rootDir: Path;
silent?: boolean;
skipFilter: boolean;
errorOnDeprecated: boolean;
testFailureExitCode: number;
testNamePattern?: string;
testPathPattern: string;
testResultsProcessor?: string;
testSequencer: string;
testTimeout?: number;
updateSnapshot: SnapshotUpdateState;
useStderr: boolean;
verbose?: boolean;
watch: boolean;
watchAll: boolean;
watchman: boolean;
watchPlugins?: Array<{
path: string;
config: Record<string, any>;
}> | null;
};
export declare type ProjectConfig = {
automock: boolean;
cache: boolean;
cacheDirectory: Path;
clearMocks: boolean;
coveragePathIgnorePatterns: Array<string>;
cwd: Path;
dependencyExtractor?: string;
detectLeaks: boolean;
detectOpenHandles: boolean;
displayName?: DisplayName;
errorOnDeprecated: boolean;
extraGlobals: Array<keyof NodeJS.Global>;
filter?: Path;
forceCoverageMatch: Array<Glob>;
globalSetup?: string;
globalTeardown?: string;
globals: ConfigGlobals;
haste: HasteConfig;
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
moduleLoader?: Path;
moduleNameMapper: Array<[string, string]>;
modulePathIgnorePatterns: Array<string>;
modulePaths?: Array<string>;
name: string;
prettierPath: string;
resetMocks: boolean;
resetModules: boolean;
resolver?: Path;
restoreMocks: boolean;
rootDir: Path;
roots: Array<Path>;
runner: string;
setupFiles: Array<Path>;
setupFilesAfterEnv: Array<Path>;
skipFilter: boolean;
skipNodeResolution?: boolean;
slowTestThreshold: number;
snapshotResolver?: Path;
snapshotSerializers: Array<Path>;
testEnvironment: string;
testEnvironmentOptions: Record<string, any>;
testMatch: Array<Glob>;
testLocationInResults: boolean;
testPathIgnorePatterns: Array<string>;
testRegex: Array<string | RegExp>;
testRunner: string;
testURL: string;
timers: 'real' | 'fake' | 'modern' | 'legacy';
transform: Array<[string, Path, Record<string, unknown>]>;
transformIgnorePatterns: Array<Glob>;
watchPathIgnorePatterns: Array<string>;
unmockedModulePathPatterns?: Array<string>;
};
export declare type Argv = Arguments<Partial<{
all: boolean;
automock: boolean;
bail: boolean | number;
cache: boolean;
cacheDirectory: string;
changedFilesWithAncestor: boolean;
changedSince: string;
ci: boolean;
clearCache: boolean;
clearMocks: boolean;
collectCoverage: boolean;
collectCoverageFrom: string;
collectCoverageOnlyFrom: Array<string>;
color: boolean;
colors: boolean;
config: string;
coverage: boolean;
coverageDirectory: string;
coveragePathIgnorePatterns: Array<string>;
coverageReporters: Array<string>;
coverageThreshold: string;
debug: boolean;
env: string;
expand: boolean;
findRelatedTests: boolean;
forceExit: boolean;
globals: string;
globalSetup: string | null | undefined;
globalTeardown: string | null | undefined;
haste: string;
init: boolean;
json: boolean;
lastCommit: boolean;
logHeapUsage: boolean;
maxWorkers: number | string;
moduleDirectories: Array<string>;
moduleFileExtensions: Array<string>;
moduleNameMapper: string;
modulePathIgnorePatterns: Array<string>;
modulePaths: Array<string>;
noStackTrace: boolean;
notify: boolean;
notifyMode: string;
onlyChanged: boolean;
outputFile: string;
preset: string | null | undefined;
projects: Array<string>;
prettierPath: string | null | undefined;
resetMocks: boolean;
resetModules: boolean;
resolver: string | null | undefined;
restoreMocks: boolean;
rootDir: string;
roots: Array<string>;
runInBand: boolean;
selectProjects: Array<string>;
setupFiles: Array<string>;
setupFilesAfterEnv: Array<string>;
showConfig: boolean;
silent: boolean;
snapshotSerializers: Array<string>;
testEnvironment: string;
testFailureExitCode: string | null | undefined;
testMatch: Array<string>;
testNamePattern: string;
testPathIgnorePatterns: Array<string>;
testPathPattern: Array<string>;
testRegex: string | Array<string>;
testResultsProcessor: string;
testRunner: string;
testSequencer: string;
testURL: string;
testTimeout: number | null | undefined;
timers: string;
transform: string;
transformIgnorePatterns: Array<string>;
unmockedModulePathPatterns: Array<string> | null | undefined;
updateSnapshot: boolean;
useStderr: boolean;
verbose: boolean;
version: boolean;
watch: boolean;
watchAll: boolean;
watchman: boolean;
watchPathIgnorePatterns: Array<string>;
}>>;
export {};

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1,85 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/// <reference types="node" />
import type { CoverageMapData } from 'istanbul-lib-coverage';
export declare type DoneFn = (reason?: string | Error) => void;
export declare type TestName = string;
export declare type TestFn = (done?: DoneFn) => Promise<void | undefined | unknown> | void | undefined;
export declare type ConcurrentTestFn = (done?: DoneFn) => Promise<void | undefined | unknown>;
export declare type BlockFn = () => void;
export declare type BlockName = string;
export declare type HookFn = TestFn;
export declare type Col = unknown;
export declare type Row = Array<Col>;
export declare type Table = Array<Row>;
export declare type ArrayTable = Table | Row;
export declare type TemplateTable = TemplateStringsArray;
export declare type TemplateData = Array<unknown>;
export declare type EachTable = ArrayTable | TemplateTable;
export declare type TestCallback = BlockFn | TestFn | ConcurrentTestFn;
export declare type EachTestFn<EachCallback extends TestCallback> = (...args: Array<any>) => ReturnType<EachCallback>;
declare type Jasmine = {
_DEFAULT_TIMEOUT_INTERVAL?: number;
addMatchers: Function;
};
declare type Each<EachCallback extends TestCallback> = ((table: EachTable, ...taggedTemplateData: Array<unknown>) => (title: string, test: EachTestFn<EachCallback>, timeout?: number) => void) | (() => void);
export interface ItBase {
(testName: TestName, fn: TestFn, timeout?: number): void;
each: Each<TestFn>;
}
export interface It extends ItBase {
only: ItBase;
skip: ItBase;
todo: (testName: TestName, ...rest: Array<any>) => void;
}
export interface ItConcurrentBase {
(testName: string, testFn: ConcurrentTestFn, timeout?: number): void;
each: Each<ConcurrentTestFn>;
}
export interface ItConcurrentExtended extends ItConcurrentBase {
only: ItConcurrentBase;
skip: ItConcurrentBase;
}
export interface ItConcurrent extends It {
concurrent: ItConcurrentExtended;
}
export interface DescribeBase {
(blockName: BlockName, blockFn: BlockFn): void;
each: Each<BlockFn>;
}
export interface Describe extends DescribeBase {
only: DescribeBase;
skip: DescribeBase;
}
export interface TestFrameworkGlobals {
it: ItConcurrent;
test: ItConcurrent;
fit: ItBase & {
concurrent?: ItConcurrentBase;
};
xit: ItBase;
xtest: ItBase;
describe: Describe;
xdescribe: DescribeBase;
fdescribe: DescribeBase;
beforeAll: HookFn;
beforeEach: HookFn;
afterEach: HookFn;
afterAll: HookFn;
}
export interface GlobalAdditions extends TestFrameworkGlobals {
__coverage__: CoverageMapData;
jasmine: Jasmine;
fail: () => void;
pending: () => void;
spyOn: () => void;
spyOnProperty: () => void;
}
export interface Global extends GlobalAdditions, Omit<NodeJS.Global, keyof GlobalAdditions> {
[extras: string]: any;
}
export {};

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1,31 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare type Milliseconds = number;
declare type Status = 'passed' | 'failed' | 'skipped' | 'pending' | 'todo' | 'disabled';
declare type Callsite = {
column: number;
line: number;
};
export declare type AssertionResult = {
ancestorTitles: Array<string>;
duration?: Milliseconds | null;
failureDetails: Array<unknown>;
failureMessages: Array<string>;
fullName: string;
invocations?: number;
location?: Callsite | null;
numPassingAsserts: number;
status: Status;
title: string;
};
export declare type SerializableError = {
code?: unknown;
message: string;
stack: string | null | undefined;
type?: string;
};
export {};

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
export declare type TransformResult = {
code: string;
originalCode: string;
mapCoverage?: boolean;
sourceMapPath: string | null;
};

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1,12 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import type * as Circus from './Circus';
import type * as Config from './Config';
import type * as Global from './Global';
import type * as TestResult from './TestResult';
import type * as TransformTypes from './Transform';
export type { Circus, Config, Global, TestResult, TransformTypes };

View file

@ -0,0 +1 @@
'use strict';

View file

@ -0,0 +1,26 @@
{
"name": "@jest/types",
"version": "26.3.0",
"repository": {
"type": "git",
"url": "https://github.com/facebook/jest.git",
"directory": "packages/jest-types"
},
"engines": {
"node": ">= 10.14.2"
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"@types/istanbul-lib-coverage": "^2.0.0",
"@types/istanbul-reports": "^3.0.0",
"@types/node": "*",
"@types/yargs": "^15.0.0",
"chalk": "^4.0.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "3a7e06fe855515a848241bb06a6f6e117847443d"
}

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View file

@ -0,0 +1,16 @@
# Installation
> `npm install --save @types/istanbul-reports`
# Summary
This package contains type definitions for istanbul-reports (https://github.com/istanbuljs/istanbuljs).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/istanbul-reports.
### Additional Details
* Last updated: Mon, 20 Jul 2020 21:55:27 GMT
* Dependencies: [@types/istanbul-lib-report](https://npmjs.com/package/@types/istanbul-lib-report)
* Global values: none
# Credits
These definitions were written by [Jason Cheatham](https://github.com/jason0x43), and [Elena Shcherbakova](https://github.com/not-a-doctor).

View file

@ -0,0 +1,74 @@
// Type definitions for istanbul-reports 3.0
// Project: https://github.com/istanbuljs/istanbuljs, https://istanbul.js.org
// Definitions by: Jason Cheatham <https://github.com/jason0x43>
// Elena Shcherbakova <https://github.com/not-a-doctor>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
import { Node, Visitor } from 'istanbul-lib-report';
export function create<T extends keyof ReportOptions>(name: T, options?: Partial<ReportOptions[T]>): Visitor;
export interface FileOptions {
file: string;
}
export interface ProjectOptions {
projectRoot: string;
}
export interface ReportOptions {
clover: CloverOptions;
cobertura: CoberturaOptions;
'html-spa': HtmlSpaOptions;
html: HtmlOptions;
json: JsonOptions;
'json-summary': JsonSummaryOptions;
lcov: LcovOptions;
lcovonly: LcovOnlyOptions;
none: never;
teamcity: TeamcityOptions;
text: TextOptions;
'text-lcov': TextLcovOptions;
'text-summary': TextSummaryOptions;
}
export type ReportType = keyof ReportOptions;
export interface CloverOptions extends FileOptions, ProjectOptions {}
export interface CoberturaOptions extends FileOptions, ProjectOptions {}
export interface HtmlSpaOptions extends HtmlOptions {
metricsToShow: Array<'lines' | 'branches' | 'functions' | 'statements'>;
}
export interface HtmlOptions {
verbose: boolean;
skipEmpty: boolean;
subdir: string;
linkMapper: LinkMapper;
}
export type JsonOptions = FileOptions;
export type JsonSummaryOptions = FileOptions;
export interface LcovOptions extends FileOptions, ProjectOptions {}
export interface LcovOnlyOptions extends FileOptions, ProjectOptions {}
export interface TeamcityOptions extends FileOptions {
blockName: string;
}
export interface TextOptions extends FileOptions {
maxCols: number;
skipEmpty: boolean;
skipFull: boolean;
}
export type TextLcovOptions = ProjectOptions;
export type TextSummaryOptions = FileOptions;
export interface LinkMapper {
getPath(node: string | Node): string;
relativePath(source: string | Node, target: string | Node): string;
assetPath(node: Node, name: string): string;
}

View file

@ -0,0 +1,31 @@
{
"name": "@types/istanbul-reports",
"version": "3.0.0",
"description": "TypeScript definitions for istanbul-reports",
"license": "MIT",
"contributors": [
{
"name": "Jason Cheatham",
"url": "https://github.com/jason0x43",
"githubUsername": "jason0x43"
},
{
"name": "Elena Shcherbakova",
"url": "https://github.com/not-a-doctor",
"githubUsername": "not-a-doctor"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/istanbul-reports"
},
"scripts": {},
"dependencies": {
"@types/istanbul-lib-report": "*"
},
"typesPublisherContentHash": "71342edcc57e7212d17e794fa519955e496dd3b6696e2738904679ef3aa59d70",
"typeScriptVersion": "3.0"
}

View file

@ -0,0 +1,415 @@
/**
Basic foreground colors.
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type ForegroundColor =
| 'black'
| 'red'
| 'green'
| 'yellow'
| 'blue'
| 'magenta'
| 'cyan'
| 'white'
| 'gray'
| 'grey'
| 'blackBright'
| 'redBright'
| 'greenBright'
| 'yellowBright'
| 'blueBright'
| 'magentaBright'
| 'cyanBright'
| 'whiteBright';
/**
Basic background colors.
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type BackgroundColor =
| 'bgBlack'
| 'bgRed'
| 'bgGreen'
| 'bgYellow'
| 'bgBlue'
| 'bgMagenta'
| 'bgCyan'
| 'bgWhite'
| 'bgGray'
| 'bgGrey'
| 'bgBlackBright'
| 'bgRedBright'
| 'bgGreenBright'
| 'bgYellowBright'
| 'bgBlueBright'
| 'bgMagentaBright'
| 'bgCyanBright'
| 'bgWhiteBright';
/**
Basic colors.
[More colors here.](https://github.com/chalk/chalk/blob/master/readme.md#256-and-truecolor-color-support)
*/
declare type Color = ForegroundColor | BackgroundColor;
declare type Modifiers =
| 'reset'
| 'bold'
| 'dim'
| 'italic'
| 'underline'
| 'inverse'
| 'hidden'
| 'strikethrough'
| 'visible';
declare namespace chalk {
/**
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
type Level = 0 | 1 | 2 | 3;
interface Options {
/**
Specify the color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
level?: Level;
}
/**
Return a new Chalk instance.
*/
type Instance = new (options?: Options) => Chalk;
/**
Detect whether the terminal supports color.
*/
interface ColorSupport {
/**
The color level used by Chalk.
*/
level: Level;
/**
Return whether Chalk supports basic 16 colors.
*/
hasBasic: boolean;
/**
Return whether Chalk supports ANSI 256 colors.
*/
has256: boolean;
/**
Return whether Chalk supports Truecolor 16 million colors.
*/
has16m: boolean;
}
interface ChalkFunction {
/**
Use a template string.
@remarks Template literals are unsupported for nested calls (see [issue #341](https://github.com/chalk/chalk/issues/341))
@example
```
import chalk = require('chalk');
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
```
@example
```
import chalk = require('chalk');
log(chalk.red.bgBlack`2 + 3 = {bold ${2 + 3}}`)
```
*/
(text: TemplateStringsArray, ...placeholders: unknown[]): string;
(...text: unknown[]): string;
}
interface Chalk extends ChalkFunction {
/**
Return a new Chalk instance.
*/
Instance: Instance;
/**
The color support for Chalk.
By default, color support is automatically detected based on the environment.
Levels:
- `0` - All colors disabled.
- `1` - Basic 16 colors support.
- `2` - ANSI 256 colors support.
- `3` - Truecolor 16 million colors support.
*/
level: Level;
/**
Use HEX value to set text color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.hex('#DEADED');
```
*/
hex(color: string): Chalk;
/**
Use keyword color value to set text color.
@param color - Keyword value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.keyword('orange');
```
*/
keyword(color: string): Chalk;
/**
Use RGB values to set text color.
*/
rgb(red: number, green: number, blue: number): Chalk;
/**
Use HSL values to set text color.
*/
hsl(hue: number, saturation: number, lightness: number): Chalk;
/**
Use HSV values to set text color.
*/
hsv(hue: number, saturation: number, value: number): Chalk;
/**
Use HWB values to set text color.
*/
hwb(hue: number, whiteness: number, blackness: number): Chalk;
/**
Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set text color.
30 <= code && code < 38 || 90 <= code && code < 98
For example, 31 for red, 91 for redBright.
*/
ansi(code: number): Chalk;
/**
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set text color.
*/
ansi256(index: number): Chalk;
/**
Use HEX value to set background color.
@param color - Hexadecimal value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.bgHex('#DEADED');
```
*/
bgHex(color: string): Chalk;
/**
Use keyword color value to set background color.
@param color - Keyword value representing the desired color.
@example
```
import chalk = require('chalk');
chalk.bgKeyword('orange');
```
*/
bgKeyword(color: string): Chalk;
/**
Use RGB values to set background color.
*/
bgRgb(red: number, green: number, blue: number): Chalk;
/**
Use HSL values to set background color.
*/
bgHsl(hue: number, saturation: number, lightness: number): Chalk;
/**
Use HSV values to set background color.
*/
bgHsv(hue: number, saturation: number, value: number): Chalk;
/**
Use HWB values to set background color.
*/
bgHwb(hue: number, whiteness: number, blackness: number): Chalk;
/**
Use a [Select/Set Graphic Rendition](https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_parameters) (SGR) [color code number](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) to set background color.
30 <= code && code < 38 || 90 <= code && code < 98
For example, 31 for red, 91 for redBright.
Use the foreground code, not the background code (for example, not 41, nor 101).
*/
bgAnsi(code: number): Chalk;
/**
Use a [8-bit unsigned number](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) to set background color.
*/
bgAnsi256(index: number): Chalk;
/**
Modifier: Resets the current color chain.
*/
readonly reset: Chalk;
/**
Modifier: Make text bold.
*/
readonly bold: Chalk;
/**
Modifier: Emitting only a small amount of light.
*/
readonly dim: Chalk;
/**
Modifier: Make text italic. (Not widely supported)
*/
readonly italic: Chalk;
/**
Modifier: Make text underline. (Not widely supported)
*/
readonly underline: Chalk;
/**
Modifier: Inverse background and foreground colors.
*/
readonly inverse: Chalk;
/**
Modifier: Prints the text, but makes it invisible.
*/
readonly hidden: Chalk;
/**
Modifier: Puts a horizontal line through the center of the text. (Not widely supported)
*/
readonly strikethrough: Chalk;
/**
Modifier: Prints the text only when Chalk has a color support level > 0.
Can be useful for things that are purely cosmetic.
*/
readonly visible: Chalk;
readonly black: Chalk;
readonly red: Chalk;
readonly green: Chalk;
readonly yellow: Chalk;
readonly blue: Chalk;
readonly magenta: Chalk;
readonly cyan: Chalk;
readonly white: Chalk;
/*
Alias for `blackBright`.
*/
readonly gray: Chalk;
/*
Alias for `blackBright`.
*/
readonly grey: Chalk;
readonly blackBright: Chalk;
readonly redBright: Chalk;
readonly greenBright: Chalk;
readonly yellowBright: Chalk;
readonly blueBright: Chalk;
readonly magentaBright: Chalk;
readonly cyanBright: Chalk;
readonly whiteBright: Chalk;
readonly bgBlack: Chalk;
readonly bgRed: Chalk;
readonly bgGreen: Chalk;
readonly bgYellow: Chalk;
readonly bgBlue: Chalk;
readonly bgMagenta: Chalk;
readonly bgCyan: Chalk;
readonly bgWhite: Chalk;
/*
Alias for `bgBlackBright`.
*/
readonly bgGray: Chalk;
/*
Alias for `bgBlackBright`.
*/
readonly bgGrey: Chalk;
readonly bgBlackBright: Chalk;
readonly bgRedBright: Chalk;
readonly bgGreenBright: Chalk;
readonly bgYellowBright: Chalk;
readonly bgBlueBright: Chalk;
readonly bgMagentaBright: Chalk;
readonly bgCyanBright: Chalk;
readonly bgWhiteBright: Chalk;
}
}
/**
Main Chalk object that allows to chain styles together.
Call the last one as a method with a string argument.
Order doesn't matter, and later styles take precedent in case of a conflict.
This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
*/
declare const chalk: chalk.Chalk & chalk.ChalkFunction & {
supportsColor: chalk.ColorSupport | false;
Level: chalk.Level;
Color: Color;
ForegroundColor: ForegroundColor;
BackgroundColor: BackgroundColor;
Modifiers: Modifiers;
stderr: chalk.Chalk & {supportsColor: chalk.ColorSupport | false};
};
export = chalk;

View file

@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,68 @@
{
"name": "chalk",
"version": "4.1.0",
"description": "Terminal string styling done right",
"license": "MIT",
"repository": "chalk/chalk",
"funding": "https://github.com/chalk/chalk?sponsor=1",
"main": "source",
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && nyc ava && tsd",
"bench": "matcha benchmark.js"
},
"files": [
"source",
"index.d.ts"
],
"keywords": [
"color",
"colour",
"colors",
"terminal",
"console",
"cli",
"string",
"str",
"ansi",
"style",
"styles",
"tty",
"formatting",
"rgb",
"256",
"shell",
"xterm",
"log",
"logging",
"command-line",
"text"
],
"dependencies": {
"ansi-styles": "^4.1.0",
"supports-color": "^7.1.0"
},
"devDependencies": {
"ava": "^2.4.0",
"coveralls": "^3.0.7",
"execa": "^4.0.0",
"import-fresh": "^3.1.0",
"matcha": "^0.7.0",
"nyc": "^15.0.0",
"resolve-from": "^5.0.0",
"tsd": "^0.7.4",
"xo": "^0.28.2"
},
"xo": {
"rules": {
"unicorn/prefer-string-slice": "off",
"unicorn/prefer-includes": "off",
"@typescript-eslint/member-ordering": "off",
"no-redeclare": "off",
"unicorn/string-content": "off",
"unicorn/better-regex": "off"
}
}
}

View file

@ -0,0 +1,293 @@
<h1 align="center">
<br>
<br>
<img width="320" src="media/logo.svg" alt="Chalk">
<br>
<br>
<br>
</h1>
> Terminal string styling done right
[![Build Status](https://travis-ci.org/chalk/chalk.svg?branch=master)](https://travis-ci.org/chalk/chalk) [![Coverage Status](https://coveralls.io/repos/github/chalk/chalk/badge.svg?branch=master)](https://coveralls.io/github/chalk/chalk?branch=master) [![npm dependents](https://badgen.net/npm/dependents/chalk)](https://www.npmjs.com/package/chalk?activeTab=dependents) [![Downloads](https://badgen.net/npm/dt/chalk)](https://www.npmjs.com/package/chalk) [![](https://img.shields.io/badge/unicorn-approved-ff69b4.svg)](https://www.youtube.com/watch?v=9auOCbH5Ns4) [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/xojs/xo) ![TypeScript-ready](https://img.shields.io/npm/types/chalk.svg) [![run on repl.it](https://repl.it/badge/github/chalk/chalk)](https://repl.it/github/chalk/chalk)
<img src="https://cdn.jsdelivr.net/gh/chalk/ansi-styles@8261697c95bf34b6c7767e2cbe9941a851d59385/screenshot.svg" width="900">
## Highlights
- Expressive API
- Highly performant
- Ability to nest styles
- [256/Truecolor color support](#256-and-truecolor-color-support)
- Auto-detects color support
- Doesn't extend `String.prototype`
- Clean and focused
- Actively maintained
- [Used by ~50,000 packages](https://www.npmjs.com/browse/depended/chalk) as of January 1, 2020
## Install
```console
$ npm install chalk
```
## Usage
```js
const chalk = require('chalk');
console.log(chalk.blue('Hello world!'));
```
Chalk comes with an easy to use composable API where you just chain and nest the styles you want.
```js
const chalk = require('chalk');
const log = console.log;
// Combine styled and normal strings
log(chalk.blue('Hello') + ' World' + chalk.red('!'));
// Compose multiple styles using the chainable API
log(chalk.blue.bgRed.bold('Hello world!'));
// Pass in multiple arguments
log(chalk.blue('Hello', 'World!', 'Foo', 'bar', 'biz', 'baz'));
// Nest styles
log(chalk.red('Hello', chalk.underline.bgBlue('world') + '!'));
// Nest styles of the same type even (color, underline, background)
log(chalk.green(
'I am a green line ' +
chalk.blue.underline.bold('with a blue substring') +
' that becomes green again!'
));
// ES2015 template literal
log(`
CPU: ${chalk.red('90%')}
RAM: ${chalk.green('40%')}
DISK: ${chalk.yellow('70%')}
`);
// ES2015 tagged template literal
log(chalk`
CPU: {red ${cpu.totalPercent}%}
RAM: {green ${ram.used / ram.total * 100}%}
DISK: {rgb(255,131,0) ${disk.used / disk.total * 100}%}
`);
// Use RGB colors in terminal emulators that support it.
log(chalk.keyword('orange')('Yay for orange colored text!'));
log(chalk.rgb(123, 45, 67).underline('Underlined reddish color'));
log(chalk.hex('#DEADED').bold('Bold gray!'));
```
Easily define your own themes:
```js
const chalk = require('chalk');
const error = chalk.bold.red;
const warning = chalk.keyword('orange');
console.log(error('Error!'));
console.log(warning('Warning!'));
```
Take advantage of console.log [string substitution](https://nodejs.org/docs/latest/api/console.html#console_console_log_data_args):
```js
const name = 'Sindre';
console.log(chalk.green('Hello %s'), name);
//=> 'Hello Sindre'
```
## API
### chalk.`<style>[.<style>...](string, [string...])`
Example: `chalk.red.bold.underline('Hello', 'world');`
Chain [styles](#styles) and call the last one as a method with a string argument. Order doesn't matter, and later styles take precedent in case of a conflict. This simply means that `chalk.red.yellow.green` is equivalent to `chalk.green`.
Multiple arguments will be separated by space.
### chalk.level
Specifies the level of color support.
Color support is automatically detected, but you can override it by setting the `level` property. You should however only do this in your own code as it applies globally to all Chalk consumers.
If you need to change this in a reusable module, create a new instance:
```js
const ctx = new chalk.Instance({level: 0});
```
| Level | Description |
| :---: | :--- |
| `0` | All colors disabled |
| `1` | Basic color support (16 colors) |
| `2` | 256 color support |
| `3` | Truecolor support (16 million colors) |
### chalk.supportsColor
Detect whether the terminal [supports color](https://github.com/chalk/supports-color). Used internally and handled for you, but exposed for convenience.
Can be overridden by the user with the flags `--color` and `--no-color`. For situations where using `--color` is not possible, use the environment variable `FORCE_COLOR=1` (level 1), `FORCE_COLOR=2` (level 2), or `FORCE_COLOR=3` (level 3) to forcefully enable color, or `FORCE_COLOR=0` to forcefully disable. The use of `FORCE_COLOR` overrides all other color support checks.
Explicit 256/Truecolor mode can be enabled using the `--color=256` and `--color=16m` flags, respectively.
### chalk.stderr and chalk.stderr.supportsColor
`chalk.stderr` contains a separate instance configured with color support detected for `stderr` stream instead of `stdout`. Override rules from `chalk.supportsColor` apply to this too. `chalk.stderr.supportsColor` is exposed for convenience.
## Styles
### Modifiers
- `reset` - Resets the current color chain.
- `bold` - Make text bold.
- `dim` - Emitting only a small amount of light.
- `italic` - Make text italic. *(Not widely supported)*
- `underline` - Make text underline. *(Not widely supported)*
- `inverse`- Inverse background and foreground colors.
- `hidden` - Prints the text, but makes it invisible.
- `strikethrough` - Puts a horizontal line through the center of the text. *(Not widely supported)*
- `visible`- Prints the text only when Chalk has a color level > 0. Can be useful for things that are purely cosmetic.
### Colors
- `black`
- `red`
- `green`
- `yellow`
- `blue`
- `magenta`
- `cyan`
- `white`
- `blackBright` (alias: `gray`, `grey`)
- `redBright`
- `greenBright`
- `yellowBright`
- `blueBright`
- `magentaBright`
- `cyanBright`
- `whiteBright`
### Background colors
- `bgBlack`
- `bgRed`
- `bgGreen`
- `bgYellow`
- `bgBlue`
- `bgMagenta`
- `bgCyan`
- `bgWhite`
- `bgBlackBright` (alias: `bgGray`, `bgGrey`)
- `bgRedBright`
- `bgGreenBright`
- `bgYellowBright`
- `bgBlueBright`
- `bgMagentaBright`
- `bgCyanBright`
- `bgWhiteBright`
## Tagged template literal
Chalk can be used as a [tagged template literal](https://exploringjs.com/es6/ch_template-literals.html#_tagged-template-literals).
```js
const chalk = require('chalk');
const miles = 18;
const calculateFeet = miles => miles * 5280;
console.log(chalk`
There are {bold 5280 feet} in a mile.
In {bold ${miles} miles}, there are {green.bold ${calculateFeet(miles)} feet}.
`);
```
Blocks are delimited by an opening curly brace (`{`), a style, some content, and a closing curly brace (`}`).
Template styles are chained exactly like normal Chalk styles. The following three statements are equivalent:
```js
console.log(chalk.bold.rgb(10, 100, 200)('Hello!'));
console.log(chalk.bold.rgb(10, 100, 200)`Hello!`);
console.log(chalk`{bold.rgb(10,100,200) Hello!}`);
```
Note that function styles (`rgb()`, `hsl()`, `keyword()`, etc.) may not contain spaces between parameters.
All interpolated values (`` chalk`${foo}` ``) are converted to strings via the `.toString()` method. All curly braces (`{` and `}`) in interpolated value strings are escaped.
## 256 and Truecolor color support
Chalk supports 256 colors and [Truecolor](https://gist.github.com/XVilka/8346728) (16 million colors) on supported terminal apps.
Colors are downsampled from 16 million RGB values to an ANSI color format that is supported by the terminal emulator (or by specifying `{level: n}` as a Chalk option). For example, Chalk configured to run at level 1 (basic color support) will downsample an RGB value of #FF0000 (red) to 31 (ANSI escape for red).
Examples:
- `chalk.hex('#DEADED').underline('Hello, world!')`
- `chalk.keyword('orange')('Some orange text')`
- `chalk.rgb(15, 100, 204).inverse('Hello!')`
Background versions of these models are prefixed with `bg` and the first level of the module capitalized (e.g. `keyword` for foreground colors and `bgKeyword` for background colors).
- `chalk.bgHex('#DEADED').underline('Hello, world!')`
- `chalk.bgKeyword('orange')('Some orange text')`
- `chalk.bgRgb(15, 100, 204).inverse('Hello!')`
The following color models can be used:
- [`rgb`](https://en.wikipedia.org/wiki/RGB_color_model) - Example: `chalk.rgb(255, 136, 0).bold('Orange!')`
- [`hex`](https://en.wikipedia.org/wiki/Web_colors#Hex_triplet) - Example: `chalk.hex('#FF8800').bold('Orange!')`
- [`keyword`](https://www.w3.org/wiki/CSS/Properties/color/keywords) (CSS keywords) - Example: `chalk.keyword('orange').bold('Orange!')`
- [`hsl`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsl(32, 100, 50).bold('Orange!')`
- [`hsv`](https://en.wikipedia.org/wiki/HSL_and_HSV) - Example: `chalk.hsv(32, 100, 100).bold('Orange!')`
- [`hwb`](https://en.wikipedia.org/wiki/HWB_color_model) - Example: `chalk.hwb(32, 0, 50).bold('Orange!')`
- [`ansi`](https://en.wikipedia.org/wiki/ANSI_escape_code#3/4_bit) - Example: `chalk.ansi(31).bgAnsi(93)('red on yellowBright')`
- [`ansi256`](https://en.wikipedia.org/wiki/ANSI_escape_code#8-bit) - Example: `chalk.bgAnsi256(194)('Honeydew, more or less')`
## Windows
If you're on Windows, do yourself a favor and use [Windows Terminal](https://github.com/microsoft/terminal) instead of `cmd.exe`.
## Origin story
[colors.js](https://github.com/Marak/colors.js) used to be the most popular string styling module, but it has serious deficiencies like extending `String.prototype` which causes all kinds of [problems](https://github.com/yeoman/yo/issues/68) and the package is unmaintained. Although there are other packages, they either do too much or not enough. Chalk is a clean and focused alternative.
## chalk for enterprise
Available as part of the Tidelift Subscription.
The maintainers of chalk and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-chalk?utm_source=npm-chalk&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
## Related
- [chalk-cli](https://github.com/chalk/chalk-cli) - CLI for this module
- [ansi-styles](https://github.com/chalk/ansi-styles) - ANSI escape codes for styling strings in the terminal
- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color
- [strip-ansi](https://github.com/chalk/strip-ansi) - Strip ANSI escape codes
- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Strip ANSI escape codes from a stream
- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes
- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes
- [wrap-ansi](https://github.com/chalk/wrap-ansi) - Wordwrap a string with ANSI escape codes
- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes
- [color-convert](https://github.com/qix-/color-convert) - Converts colors between different models
- [chalk-animation](https://github.com/bokub/chalk-animation) - Animate strings in the terminal
- [gradient-string](https://github.com/bokub/gradient-string) - Apply color gradients to strings
- [chalk-pipe](https://github.com/LitoMore/chalk-pipe) - Create chalk style schemes with simpler style strings
- [terminal-link](https://github.com/sindresorhus/terminal-link) - Create clickable links in the terminal
## Maintainers
- [Sindre Sorhus](https://github.com/sindresorhus)
- [Josh Junon](https://github.com/qix-)

View file

@ -0,0 +1,229 @@
'use strict';
const ansiStyles = require('ansi-styles');
const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color');
const {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
} = require('./util');
const {isArray} = Array;
// `supportsColor.level` → `ansiStyles.color[name]` mapping
const levelMapping = [
'ansi',
'ansi',
'ansi256',
'ansi16m'
];
const styles = Object.create(null);
const applyOptions = (object, options = {}) => {
if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) {
throw new Error('The `level` option should be an integer from 0 to 3');
}
// Detect level if not set manually
const colorLevel = stdoutColor ? stdoutColor.level : 0;
object.level = options.level === undefined ? colorLevel : options.level;
};
class ChalkClass {
constructor(options) {
// eslint-disable-next-line no-constructor-return
return chalkFactory(options);
}
}
const chalkFactory = options => {
const chalk = {};
applyOptions(chalk, options);
chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_);
Object.setPrototypeOf(chalk, Chalk.prototype);
Object.setPrototypeOf(chalk.template, chalk);
chalk.template.constructor = () => {
throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.');
};
chalk.template.Instance = ChalkClass;
return chalk.template;
};
function Chalk(options) {
return chalkFactory(options);
}
for (const [styleName, style] of Object.entries(ansiStyles)) {
styles[styleName] = {
get() {
const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty);
Object.defineProperty(this, styleName, {value: builder});
return builder;
}
};
}
styles.visible = {
get() {
const builder = createBuilder(this, this._styler, true);
Object.defineProperty(this, 'visible', {value: builder});
return builder;
}
};
const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256'];
for (const model of usedModels) {
styles[model] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler);
return createBuilder(this, styler, this._isEmpty);
};
}
};
}
for (const model of usedModels) {
const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1);
styles[bgModel] = {
get() {
const {level} = this;
return function (...arguments_) {
const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler);
return createBuilder(this, styler, this._isEmpty);
};
}
};
}
const proto = Object.defineProperties(() => {}, {
...styles,
level: {
enumerable: true,
get() {
return this._generator.level;
},
set(level) {
this._generator.level = level;
}
}
});
const createStyler = (open, close, parent) => {
let openAll;
let closeAll;
if (parent === undefined) {
openAll = open;
closeAll = close;
} else {
openAll = parent.openAll + open;
closeAll = close + parent.closeAll;
}
return {
open,
close,
openAll,
closeAll,
parent
};
};
const createBuilder = (self, _styler, _isEmpty) => {
const builder = (...arguments_) => {
if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) {
// Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}`
return applyStyle(builder, chalkTag(builder, ...arguments_));
}
// Single argument is hot path, implicit coercion is faster than anything
// eslint-disable-next-line no-implicit-coercion
return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' '));
};
// We alter the prototype because we must return a function, but there is
// no way to create a function with a different prototype
Object.setPrototypeOf(builder, proto);
builder._generator = self;
builder._styler = _styler;
builder._isEmpty = _isEmpty;
return builder;
};
const applyStyle = (self, string) => {
if (self.level <= 0 || !string) {
return self._isEmpty ? '' : string;
}
let styler = self._styler;
if (styler === undefined) {
return string;
}
const {openAll, closeAll} = styler;
if (string.indexOf('\u001B') !== -1) {
while (styler !== undefined) {
// Replace any instances already present with a re-opening code
// otherwise only the part of the string until said closing code
// will be colored, and the rest will simply be 'plain'.
string = stringReplaceAll(string, styler.close, styler.open);
styler = styler.parent;
}
}
// We can move both next actions out of loop, because remaining actions in loop won't have
// any/visible effect on parts we add here. Close the styling before a linebreak and reopen
// after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92
const lfIndex = string.indexOf('\n');
if (lfIndex !== -1) {
string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex);
}
return openAll + string + closeAll;
};
let template;
const chalkTag = (chalk, ...strings) => {
const [firstString] = strings;
if (!isArray(firstString) || !isArray(firstString.raw)) {
// If chalk() was called by itself or with a string,
// return the string itself as a string.
return strings.join(' ');
}
const arguments_ = strings.slice(1);
const parts = [firstString.raw[0]];
for (let i = 1; i < firstString.length; i++) {
parts.push(
String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'),
String(firstString.raw[i])
);
}
if (template === undefined) {
template = require('./templates');
}
return template(chalk, parts.join(''));
};
Object.defineProperties(Chalk.prototype, styles);
const chalk = Chalk(); // eslint-disable-line new-cap
chalk.supportsColor = stdoutColor;
chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap
chalk.stderr.supportsColor = stderrColor;
module.exports = chalk;

View file

@ -0,0 +1,134 @@
'use strict';
const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi;
const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g;
const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/;
const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi;
const ESCAPES = new Map([
['n', '\n'],
['r', '\r'],
['t', '\t'],
['b', '\b'],
['f', '\f'],
['v', '\v'],
['0', '\0'],
['\\', '\\'],
['e', '\u001B'],
['a', '\u0007']
]);
function unescape(c) {
const u = c[0] === 'u';
const bracket = c[1] === '{';
if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) {
return String.fromCharCode(parseInt(c.slice(1), 16));
}
if (u && bracket) {
return String.fromCodePoint(parseInt(c.slice(2, -1), 16));
}
return ESCAPES.get(c) || c;
}
function parseArguments(name, arguments_) {
const results = [];
const chunks = arguments_.trim().split(/\s*,\s*/g);
let matches;
for (const chunk of chunks) {
const number = Number(chunk);
if (!Number.isNaN(number)) {
results.push(number);
} else if ((matches = chunk.match(STRING_REGEX))) {
results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character));
} else {
throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`);
}
}
return results;
}
function parseStyle(style) {
STYLE_REGEX.lastIndex = 0;
const results = [];
let matches;
while ((matches = STYLE_REGEX.exec(style)) !== null) {
const name = matches[1];
if (matches[2]) {
const args = parseArguments(name, matches[2]);
results.push([name].concat(args));
} else {
results.push([name]);
}
}
return results;
}
function buildStyle(chalk, styles) {
const enabled = {};
for (const layer of styles) {
for (const style of layer.styles) {
enabled[style[0]] = layer.inverse ? null : style.slice(1);
}
}
let current = chalk;
for (const [styleName, styles] of Object.entries(enabled)) {
if (!Array.isArray(styles)) {
continue;
}
if (!(styleName in current)) {
throw new Error(`Unknown Chalk style: ${styleName}`);
}
current = styles.length > 0 ? current[styleName](...styles) : current[styleName];
}
return current;
}
module.exports = (chalk, temporary) => {
const styles = [];
const chunks = [];
let chunk = [];
// eslint-disable-next-line max-params
temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => {
if (escapeCharacter) {
chunk.push(unescape(escapeCharacter));
} else if (style) {
const string = chunk.join('');
chunk = [];
chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string));
styles.push({inverse, styles: parseStyle(style)});
} else if (close) {
if (styles.length === 0) {
throw new Error('Found extraneous } in Chalk template literal');
}
chunks.push(buildStyle(chalk, styles)(chunk.join('')));
chunk = [];
styles.pop();
} else {
chunk.push(character);
}
});
chunks.push(chunk.join(''));
if (styles.length > 0) {
const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`;
throw new Error(errMessage);
}
return chunks.join('');
};

View file

@ -0,0 +1,39 @@
'use strict';
const stringReplaceAll = (string, substring, replacer) => {
let index = string.indexOf(substring);
if (index === -1) {
return string;
}
const substringLength = substring.length;
let endIndex = 0;
let returnValue = '';
do {
returnValue += string.substr(endIndex, index - endIndex) + substring + replacer;
endIndex = index + substringLength;
index = string.indexOf(substring, endIndex);
} while (index !== -1);
returnValue += string.substr(endIndex);
return returnValue;
};
const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => {
let endIndex = 0;
let returnValue = '';
do {
const gotCR = string[index - 1] === '\r';
returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix;
endIndex = index + 1;
index = string.indexOf('\n', endIndex);
} while (index !== -1);
returnValue += string.substr(endIndex);
return returnValue;
};
module.exports = {
stringReplaceAll,
stringEncaseCRLFWithFirstIndex
};

66
node_modules/@jest/reporters/package.json generated vendored Normal file
View file

@ -0,0 +1,66 @@
{
"name": "@jest/reporters",
"description": "Jest's reporters",
"version": "26.4.1",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"@bcoe/v8-coverage": "^0.2.3",
"@jest/console": "^26.3.0",
"@jest/test-result": "^26.3.0",
"@jest/transform": "^26.3.0",
"@jest/types": "^26.3.0",
"chalk": "^4.0.0",
"collect-v8-coverage": "^1.0.0",
"exit": "^0.1.2",
"glob": "^7.1.2",
"graceful-fs": "^4.2.4",
"istanbul-lib-coverage": "^3.0.0",
"istanbul-lib-instrument": "^4.0.3",
"istanbul-lib-report": "^3.0.0",
"istanbul-lib-source-maps": "^4.0.0",
"istanbul-reports": "^3.0.2",
"jest-haste-map": "^26.3.0",
"jest-resolve": "^26.4.0",
"jest-util": "^26.3.0",
"jest-worker": "^26.3.0",
"slash": "^3.0.0",
"source-map": "^0.6.0",
"string-length": "^4.0.1",
"terminal-link": "^2.0.0",
"v8-to-istanbul": "^5.0.1"
},
"devDependencies": {
"@types/exit": "^0.1.30",
"@types/glob": "^7.1.1",
"@types/graceful-fs": "^4.1.3",
"@types/istanbul-lib-coverage": "^2.0.0",
"@types/istanbul-lib-instrument": "^1.7.2",
"@types/istanbul-lib-report": "^3.0.0",
"@types/istanbul-lib-source-maps": "^4.0.0",
"@types/istanbul-reports": "^3.0.0",
"@types/node-notifier": "^6.0.0",
"mock-fs": "^4.4.1",
"strip-ansi": "^6.0.0"
},
"optionalDependencies": {
"node-notifier": "^8.0.0"
},
"engines": {
"node": ">= 10.14.2"
},
"repository": {
"type": "git",
"url": "https://github.com/facebook/jest",
"directory": "packages/jest-reporters"
},
"bugs": {
"url": "https://github.com/facebook/jest/issues"
},
"homepage": "https://jestjs.io/",
"license": "MIT",
"publishConfig": {
"access": "public"
},
"gitHead": "e1d51deea8d089a06f28b4dbe9287a4428508610"
}