Add node modules and new code for release (#39)

Co-authored-by: tbarnes94 <tbarnes94@users.noreply.github.com>
This commit is contained in:
github-actions[bot] 2022-01-05 11:26:06 -05:00 committed by GitHub
parent a10d84bc2e
commit 7ad2aa66bb
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7655 changed files with 1763577 additions and 14 deletions

21
node_modules/jest-haste-map/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.

27
node_modules/jest-haste-map/build/HasteFS.d.ts generated vendored Normal file
View file

@ -0,0 +1,27 @@
/**
* 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 { FileData } from './types';
export default class HasteFS {
private readonly _rootDir;
private readonly _files;
constructor({ rootDir, files }: {
rootDir: Config.Path;
files: FileData;
});
getModuleName(file: Config.Path): string | null;
getSize(file: Config.Path): number | null;
getDependencies(file: Config.Path): Array<string> | null;
getSha1(file: Config.Path): string | null;
exists(file: Config.Path): boolean;
getAllFiles(): Array<Config.Path>;
getFileIterator(): Iterable<Config.Path>;
getAbsoluteFileIterator(): Iterable<Config.Path>;
matchFiles(pattern: RegExp | string): Array<Config.Path>;
matchFilesWithGlob(globs: Array<Config.Glob>, root: Config.Path | null): Set<Config.Path>;
private _getFileData;
}

179
node_modules/jest-haste-map/build/HasteFS.js generated vendored Normal file
View file

@ -0,0 +1,179 @@
'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;
}
var fastPath = _interopRequireWildcard(require('./lib/fast_path'));
var _constants = _interopRequireDefault(require('./constants'));
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;
}
class HasteFS {
constructor({rootDir, files}) {
_defineProperty(this, '_rootDir', void 0);
_defineProperty(this, '_files', void 0);
this._rootDir = rootDir;
this._files = files;
}
getModuleName(file) {
const fileMetadata = this._getFileData(file);
return (fileMetadata && fileMetadata[_constants.default.ID]) || null;
}
getSize(file) {
const fileMetadata = this._getFileData(file);
return (fileMetadata && fileMetadata[_constants.default.SIZE]) || null;
}
getDependencies(file) {
const fileMetadata = this._getFileData(file);
if (fileMetadata) {
return fileMetadata[_constants.default.DEPENDENCIES]
? fileMetadata[_constants.default.DEPENDENCIES].split(
_constants.default.DEPENDENCY_DELIM
)
: [];
} else {
return null;
}
}
getSha1(file) {
const fileMetadata = this._getFileData(file);
return (fileMetadata && fileMetadata[_constants.default.SHA1]) || null;
}
exists(file) {
return this._getFileData(file) != null;
}
getAllFiles() {
return Array.from(this.getAbsoluteFileIterator());
}
getFileIterator() {
return this._files.keys();
}
*getAbsoluteFileIterator() {
for (const file of this.getFileIterator()) {
yield fastPath.resolve(this._rootDir, file);
}
}
matchFiles(pattern) {
if (!(pattern instanceof RegExp)) {
pattern = new RegExp(pattern);
}
const files = [];
for (const file of this.getAbsoluteFileIterator()) {
if (pattern.test(file)) {
files.push(file);
}
}
return files;
}
matchFilesWithGlob(globs, root) {
const files = new Set();
const matcher = (0, _jestUtil().globsToMatcher)(globs);
for (const file of this.getAbsoluteFileIterator()) {
const filePath = root ? fastPath.relative(root, file) : file;
if (matcher((0, _jestUtil().replacePathSepForGlob)(filePath))) {
files.add(file);
}
}
return files;
}
_getFileData(file) {
const relativePath = fastPath.relative(this._rootDir, file);
return this._files.get(relativePath);
}
}
exports.default = HasteFS;

48
node_modules/jest-haste-map/build/ModuleMap.d.ts generated vendored Normal file
View file

@ -0,0 +1,48 @@
/**
* 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 { DuplicatesSet, HTypeValue, MockData, ModuleMapData, RawModuleMap } from './types';
declare type ValueType<T> = T extends Map<string, infer V> ? V : never;
export declare type SerializableModuleMap = {
duplicates: ReadonlyArray<[string, [string, [string, [string, number]]]]>;
map: ReadonlyArray<[string, ValueType<ModuleMapData>]>;
mocks: ReadonlyArray<[string, ValueType<MockData>]>;
rootDir: Config.Path;
};
export default class ModuleMap {
static DuplicateHasteCandidatesError: typeof DuplicateHasteCandidatesError;
private readonly _raw;
private json;
private static mapToArrayRecursive;
private static mapFromArrayRecursive;
constructor(raw: RawModuleMap);
getModule(name: string, platform?: string | null, supportsNativePlatform?: boolean | null, type?: HTypeValue | null): Config.Path | null;
getPackage(name: string, platform: string | null | undefined, _supportsNativePlatform: boolean | null): Config.Path | null;
getMockModule(name: string): Config.Path | undefined;
getRawModuleMap(): RawModuleMap;
toJSON(): SerializableModuleMap;
static fromJSON(serializableModuleMap: SerializableModuleMap): ModuleMap;
/**
* When looking up a module's data, we walk through each eligible platform for
* the query. For each platform, we want to check if there are known
* duplicates for that name+platform pair. The duplication logic normally
* removes elements from the `map` object, but we want to check upfront to be
* extra sure. If metadata exists both in the `duplicates` object and the
* `map`, this would be a bug.
*/
private _getModuleMetadata;
private _assertNoDuplicates;
static create(rootDir: Config.Path): ModuleMap;
}
declare class DuplicateHasteCandidatesError extends Error {
hasteName: string;
platform: string | null;
supportsNativePlatform: boolean;
duplicatesSet: DuplicatesSet;
constructor(name: string, platform: string, supportsNativePlatform: boolean, duplicatesSet: DuplicatesSet);
}
export {};

305
node_modules/jest-haste-map/build/ModuleMap.js generated vendored Normal file
View file

@ -0,0 +1,305 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
var fastPath = _interopRequireWildcard(require('./lib/fast_path'));
var _constants = _interopRequireDefault(require('./constants'));
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 EMPTY_OBJ = {};
const EMPTY_MAP = new Map();
class ModuleMap {
static mapToArrayRecursive(map) {
let arr = Array.from(map);
if (arr[0] && arr[0][1] instanceof Map) {
arr = arr.map(el => [el[0], this.mapToArrayRecursive(el[1])]);
}
return arr;
}
static mapFromArrayRecursive(arr) {
if (arr[0] && Array.isArray(arr[1])) {
arr = arr.map(el => [el[0], this.mapFromArrayRecursive(el[1])]);
}
return new Map(arr);
}
constructor(raw) {
_defineProperty(this, '_raw', void 0);
_defineProperty(this, 'json', void 0);
this._raw = raw;
}
getModule(name, platform, supportsNativePlatform, type) {
if (type == null) {
type = _constants.default.MODULE;
}
const module = this._getModuleMetadata(
name,
platform,
!!supportsNativePlatform
);
if (module && module[_constants.default.TYPE] === type) {
const modulePath = module[_constants.default.PATH];
return modulePath && fastPath.resolve(this._raw.rootDir, modulePath);
}
return null;
}
getPackage(name, platform, _supportsNativePlatform) {
return this.getModule(name, platform, null, _constants.default.PACKAGE);
}
getMockModule(name) {
const mockPath =
this._raw.mocks.get(name) || this._raw.mocks.get(name + '/index');
return mockPath && fastPath.resolve(this._raw.rootDir, mockPath);
}
getRawModuleMap() {
return {
duplicates: this._raw.duplicates,
map: this._raw.map,
mocks: this._raw.mocks,
rootDir: this._raw.rootDir
};
}
toJSON() {
if (!this.json) {
this.json = {
duplicates: ModuleMap.mapToArrayRecursive(this._raw.duplicates),
map: Array.from(this._raw.map),
mocks: Array.from(this._raw.mocks),
rootDir: this._raw.rootDir
};
}
return this.json;
}
static fromJSON(serializableModuleMap) {
return new ModuleMap({
duplicates: ModuleMap.mapFromArrayRecursive(
serializableModuleMap.duplicates
),
map: new Map(serializableModuleMap.map),
mocks: new Map(serializableModuleMap.mocks),
rootDir: serializableModuleMap.rootDir
});
}
/**
* When looking up a module's data, we walk through each eligible platform for
* the query. For each platform, we want to check if there are known
* duplicates for that name+platform pair. The duplication logic normally
* removes elements from the `map` object, but we want to check upfront to be
* extra sure. If metadata exists both in the `duplicates` object and the
* `map`, this would be a bug.
*/
_getModuleMetadata(name, platform, supportsNativePlatform) {
const map = this._raw.map.get(name) || EMPTY_OBJ;
const dupMap = this._raw.duplicates.get(name) || EMPTY_MAP;
if (platform != null) {
this._assertNoDuplicates(
name,
platform,
supportsNativePlatform,
dupMap.get(platform)
);
if (map[platform] != null) {
return map[platform];
}
}
if (supportsNativePlatform) {
this._assertNoDuplicates(
name,
_constants.default.NATIVE_PLATFORM,
supportsNativePlatform,
dupMap.get(_constants.default.NATIVE_PLATFORM)
);
if (map[_constants.default.NATIVE_PLATFORM]) {
return map[_constants.default.NATIVE_PLATFORM];
}
}
this._assertNoDuplicates(
name,
_constants.default.GENERIC_PLATFORM,
supportsNativePlatform,
dupMap.get(_constants.default.GENERIC_PLATFORM)
);
if (map[_constants.default.GENERIC_PLATFORM]) {
return map[_constants.default.GENERIC_PLATFORM];
}
return null;
}
_assertNoDuplicates(name, platform, supportsNativePlatform, relativePathSet) {
if (relativePathSet == null) {
return;
} // Force flow refinement
const previousSet = relativePathSet;
const duplicates = new Map();
for (const [relativePath, type] of previousSet) {
const duplicatePath = fastPath.resolve(this._raw.rootDir, relativePath);
duplicates.set(duplicatePath, type);
}
throw new DuplicateHasteCandidatesError(
name,
platform,
supportsNativePlatform,
duplicates
);
}
static create(rootDir) {
return new ModuleMap({
duplicates: new Map(),
map: new Map(),
mocks: new Map(),
rootDir
});
}
}
exports.default = ModuleMap;
_defineProperty(ModuleMap, 'DuplicateHasteCandidatesError', void 0);
class DuplicateHasteCandidatesError extends Error {
constructor(name, platform, supportsNativePlatform, duplicatesSet) {
const platformMessage = getPlatformMessage(platform);
super(
`The name \`${name}\` was looked up in the Haste module map. It ` +
`cannot be resolved, because there exists several different ` +
`files, or packages, that provide a module for ` +
`that particular name and platform. ${platformMessage} You must ` +
`delete or exclude files until there remains only one of these:\n\n` +
Array.from(duplicatesSet)
.map(
([dupFilePath, dupFileType]) =>
` * \`${dupFilePath}\` (${getTypeMessage(dupFileType)})\n`
)
.sort()
.join('')
);
_defineProperty(this, 'hasteName', void 0);
_defineProperty(this, 'platform', void 0);
_defineProperty(this, 'supportsNativePlatform', void 0);
_defineProperty(this, 'duplicatesSet', void 0);
this.hasteName = name;
this.platform = platform;
this.supportsNativePlatform = supportsNativePlatform;
this.duplicatesSet = duplicatesSet;
}
}
function getPlatformMessage(platform) {
if (platform === _constants.default.GENERIC_PLATFORM) {
return 'The platform is generic (no extension).';
}
return `The platform extension is \`${platform}\`.`;
}
function getTypeMessage(type) {
switch (type) {
case _constants.default.MODULE:
return 'module';
case _constants.default.PACKAGE:
return 'package';
}
return 'unknown';
}
ModuleMap.DuplicateHasteCandidatesError = DuplicateHasteCandidatesError;

8
node_modules/jest-haste-map/build/blacklist.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
/**
* 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.
*/
declare const extensions: Set<string>;
export default extensions;

59
node_modules/jest-haste-map/build/blacklist.js generated vendored Normal file
View file

@ -0,0 +1,59 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
/**
* 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.
*/
// This list is compiled after the MDN list of the most common MIME types (see
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/
// Complete_list_of_MIME_types).
//
// Only MIME types starting with "image/", "video/", "audio/" and "font/" are
// reflected in the list. Adding "application/" is too risky since some text
// file formats (like ".js" and ".json") have an "application/" MIME type.
//
// Feel free to add any extensions that cannot be a Haste module.
const extensions = new Set([
// JSONs are never haste modules, except for "package.json", which is handled.
'.json', // Image extensions.
'.bmp',
'.gif',
'.ico',
'.jpeg',
'.jpg',
'.png',
'.svg',
'.tiff',
'.tif',
'.webp', // Video extensions.
'.avi',
'.mp4',
'.mpeg',
'.mpg',
'.ogv',
'.webm',
'.3gp',
'.3g2', // Audio extensions.
'.aac',
'.midi',
'.mid',
'.mp3',
'.oga',
'.wav',
'.3gp',
'.3g2', // Font extensions.
'.eot',
'.otf',
'.ttf',
'.woff',
'.woff2'
]);
var _default = extensions;
exports.default = _default;

9
node_modules/jest-haste-map/build/constants.d.ts generated vendored Normal file
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 { HType } from './types';
declare const constants: HType;
export default constants;

52
node_modules/jest-haste-map/build/constants.js generated vendored Normal file
View file

@ -0,0 +1,52 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = void 0;
/**
* 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.
*/
/*
* This file exports a set of constants that are used for Jest's haste map
* serialization. On very large repositories, the haste map cache becomes very
* large to the point where it is the largest overhead in starting up Jest.
*
* This constant key map allows to keep the map smaller without having to build
* a custom serialization library.
*/
/* eslint-disable sort-keys */
const constants = {
/* dependency serialization */
DEPENDENCY_DELIM: '\0',
/* file map attributes */
ID: 0,
MTIME: 1,
SIZE: 2,
VISITED: 3,
DEPENDENCIES: 4,
SHA1: 5,
/* module map attributes */
PATH: 0,
TYPE: 1,
/* module types */
MODULE: 0,
PACKAGE: 1,
/* platforms */
GENERIC_PLATFORM: 'g',
NATIVE_PLATFORM: 'native'
};
/* eslint-enable */
var _default = constants;
exports.default = _default;

12
node_modules/jest-haste-map/build/crawlers/node.d.ts generated vendored Normal file
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 { CrawlerOptions, FileData, InternalHasteMap } from '../types';
declare const _default: (options: CrawlerOptions) => Promise<{
removedFiles: FileData;
hasteMap: InternalHasteMap;
}>;
export = _default;

320
node_modules/jest-haste-map/build/crawlers/node.js generated vendored Normal file
View file

@ -0,0 +1,320 @@
'use strict';
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _child_process() {
const data = require('child_process');
_child_process = function () {
return data;
};
return data;
}
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
function _constants() {
const data = _interopRequireDefault(require('../constants'));
_constants = function () {
return data;
};
return data;
}
function fastPath() {
const data = _interopRequireWildcard(require('../lib/fast_path'));
fastPath = 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.
*/
async function hasNativeFindSupport(forceNodeFilesystemAPI) {
if (forceNodeFilesystemAPI) {
return false;
}
try {
return await new Promise(resolve => {
// Check the find binary supports the non-POSIX -iname parameter wrapped in parens.
const args = [
'.',
'-type',
'f',
'(',
'-iname',
'*.ts',
'-o',
'-iname',
'*.js',
')'
];
const child = (0, _child_process().spawn)('find', args, {
cwd: __dirname
});
child.on('error', () => {
resolve(false);
});
child.on('exit', code => {
resolve(code === 0);
});
});
} catch {
return false;
}
}
function find(roots, extensions, ignore, callback) {
const result = [];
let activeCalls = 0;
function search(directory) {
activeCalls++;
fs().readdir(
directory,
{
withFileTypes: true
},
(err, entries) => {
activeCalls--;
if (err) {
callback(result);
return;
} // node < v10.10 does not support the withFileTypes option, and
// entry will be a string.
entries.forEach(entry => {
const file = path().join(
directory,
typeof entry === 'string' ? entry : entry.name
);
if (ignore(file)) {
return;
}
if (typeof entry !== 'string') {
if (entry.isSymbolicLink()) {
return;
}
if (entry.isDirectory()) {
search(file);
return;
}
}
activeCalls++;
fs().lstat(file, (err, stat) => {
activeCalls--; // This logic is unnecessary for node > v10.10, but leaving it in
// since we need it for backwards-compatibility still.
if (!err && stat && !stat.isSymbolicLink()) {
if (stat.isDirectory()) {
search(file);
} else {
const ext = path().extname(file).substr(1);
if (extensions.indexOf(ext) !== -1) {
result.push([file, stat.mtime.getTime(), stat.size]);
}
}
}
if (activeCalls === 0) {
callback(result);
}
});
});
if (activeCalls === 0) {
callback(result);
}
}
);
}
if (roots.length > 0) {
roots.forEach(search);
} else {
callback(result);
}
}
function findNative(roots, extensions, ignore, callback) {
const args = Array.from(roots);
args.push('-type', 'f');
if (extensions.length) {
args.push('(');
}
extensions.forEach((ext, index) => {
if (index) {
args.push('-o');
}
args.push('-iname');
args.push('*.' + ext);
});
if (extensions.length) {
args.push(')');
}
const child = (0, _child_process().spawn)('find', args);
let stdout = '';
if (child.stdout === null) {
throw new Error(
'stdout is null - this should never happen. Please open up an issue at https://github.com/facebook/jest'
);
}
child.stdout.setEncoding('utf-8');
child.stdout.on('data', data => (stdout += data));
child.stdout.on('close', () => {
const lines = stdout
.trim()
.split('\n')
.filter(x => !ignore(x));
const result = [];
let count = lines.length;
if (!count) {
callback([]);
} else {
lines.forEach(path => {
fs().stat(path, (err, stat) => {
if (!err && stat) {
result.push([path, stat.mtime.getTime(), stat.size]);
}
if (--count === 0) {
callback(result);
}
});
});
}
});
}
module.exports = async function nodeCrawl(options) {
const {
data,
extensions,
forceNodeFilesystemAPI,
ignore,
rootDir,
roots
} = options;
const useNativeFind = await hasNativeFindSupport(forceNodeFilesystemAPI);
return new Promise(resolve => {
const callback = list => {
const files = new Map();
const removedFiles = new Map(data.files);
list.forEach(fileData => {
const [filePath, mtime, size] = fileData;
const relativeFilePath = fastPath().relative(rootDir, filePath);
const existingFile = data.files.get(relativeFilePath);
if (
existingFile &&
existingFile[_constants().default.MTIME] === mtime
) {
files.set(relativeFilePath, existingFile);
} else {
// See ../constants.js; SHA-1 will always be null and fulfilled later.
files.set(relativeFilePath, ['', mtime, size, 0, '', null]);
}
removedFiles.delete(relativeFilePath);
});
data.files = files;
resolve({
hasteMap: data,
removedFiles
});
};
if (useNativeFind) {
findNative(roots, extensions, ignore, callback);
} else {
find(roots, extensions, ignore, callback);
}
});
};

View file

@ -0,0 +1,13 @@
/**
* 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 { CrawlerOptions, FileData, InternalHasteMap } from '../types';
declare const _default: (options: CrawlerOptions) => Promise<{
changedFiles?: FileData | undefined;
removedFiles: FileData;
hasteMap: InternalHasteMap;
}>;
export = _default;

327
node_modules/jest-haste-map/build/crawlers/watchman.js generated vendored Normal file
View file

@ -0,0 +1,327 @@
'use strict';
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _fbWatchman() {
const data = _interopRequireDefault(require('fb-watchman'));
_fbWatchman = function () {
return data;
};
return data;
}
function fastPath() {
const data = _interopRequireWildcard(require('../lib/fast_path'));
fastPath = function () {
return data;
};
return data;
}
function _normalizePathSep() {
const data = _interopRequireDefault(require('../lib/normalizePathSep'));
_normalizePathSep = function () {
return data;
};
return data;
}
function _constants() {
const data = _interopRequireDefault(require('../constants'));
_constants = 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 watchmanURL = 'https://facebook.github.io/watchman/docs/troubleshooting';
function WatchmanError(error) {
error.message =
`Watchman error: ${error.message.trim()}. Make sure watchman ` +
`is running for this project. See ${watchmanURL}.`;
return error;
}
module.exports = async function watchmanCrawl(options) {
const fields = ['name', 'exists', 'mtime_ms', 'size'];
const {data, extensions, ignore, rootDir, roots} = options;
const defaultWatchExpression = [
'allof',
['type', 'f'],
['anyof', ...extensions.map(extension => ['suffix', extension])]
];
const clocks = data.clocks;
const client = new (_fbWatchman().default.Client)();
let clientError;
client.on('error', error => (clientError = WatchmanError(error))); // TODO: type better than `any`
const cmd = (...args) =>
new Promise((resolve, reject) =>
client.command(args, (error, result) =>
error ? reject(WatchmanError(error)) : resolve(result)
)
);
if (options.computeSha1) {
const {capabilities} = await cmd('list-capabilities');
if (capabilities.indexOf('field-content.sha1hex') !== -1) {
fields.push('content.sha1hex');
}
}
async function getWatchmanRoots(roots) {
const watchmanRoots = new Map();
await Promise.all(
roots.map(async root => {
const response = await cmd('watch-project', root);
const existing = watchmanRoots.get(response.watch); // A root can only be filtered if it was never seen with a
// relative_path before.
const canBeFiltered = !existing || existing.length > 0;
if (canBeFiltered) {
if (response.relative_path) {
watchmanRoots.set(
response.watch,
(existing || []).concat(response.relative_path)
);
} else {
// Make the filter directories an empty array to signal that this
// root was already seen and needs to be watched for all files or
// directories.
watchmanRoots.set(response.watch, []);
}
}
})
);
return watchmanRoots;
}
async function queryWatchmanForDirs(rootProjectDirMappings) {
const files = new Map();
let isFresh = false;
await Promise.all(
Array.from(rootProjectDirMappings).map(
async ([root, directoryFilters]) => {
const expression = Array.from(defaultWatchExpression);
const glob = [];
if (directoryFilters.length > 0) {
expression.push([
'anyof',
...directoryFilters.map(dir => ['dirname', dir])
]);
for (const directory of directoryFilters) {
for (const extension of extensions) {
glob.push(`${directory}/**/*.${extension}`);
}
}
} else {
for (const extension of extensions) {
glob.push(`**/*.${extension}`);
}
}
const relativeRoot = fastPath().relative(rootDir, root);
const query = clocks.has(relativeRoot) // Use the `since` generator if we have a clock available
? {
expression,
fields,
since: clocks.get(relativeRoot)
} // Otherwise use the `glob` filter
: {
expression,
fields,
glob,
glob_includedotfiles: true
};
const response = await cmd('query', root, query);
if ('warning' in response) {
console.warn('watchman warning: ', response.warning);
}
isFresh = isFresh || response.is_fresh_instance;
files.set(root, response);
}
)
);
return {
files,
isFresh
};
}
let files = data.files;
let removedFiles = new Map();
const changedFiles = new Map();
let watchmanFiles;
let isFresh = false;
try {
const watchmanRoots = await getWatchmanRoots(roots);
const watchmanFileResults = await queryWatchmanForDirs(watchmanRoots); // Reset the file map if watchman was restarted and sends us a list of
// files.
if (watchmanFileResults.isFresh) {
files = new Map();
removedFiles = new Map(data.files);
isFresh = true;
}
watchmanFiles = watchmanFileResults.files;
} finally {
client.end();
}
if (clientError) {
throw clientError;
} // TODO: remove non-null
for (const [watchRoot, response] of watchmanFiles) {
const fsRoot = (0, _normalizePathSep().default)(watchRoot);
const relativeFsRoot = fastPath().relative(rootDir, fsRoot);
clocks.set(relativeFsRoot, response.clock);
for (const fileData of response.files) {
const filePath =
fsRoot + path().sep + (0, _normalizePathSep().default)(fileData.name);
const relativeFilePath = fastPath().relative(rootDir, filePath);
const existingFileData = data.files.get(relativeFilePath); // If watchman is fresh, the removed files map starts with all files
// and we remove them as we verify they still exist.
if (isFresh && existingFileData && fileData.exists) {
removedFiles.delete(relativeFilePath);
}
if (!fileData.exists) {
// No need to act on files that do not exist and were not tracked.
if (existingFileData) {
files.delete(relativeFilePath); // If watchman is not fresh, we will know what specific files were
// deleted since we last ran and can track only those files.
if (!isFresh) {
removedFiles.set(relativeFilePath, existingFileData);
}
}
} else if (!ignore(filePath)) {
const mtime =
typeof fileData.mtime_ms === 'number'
? fileData.mtime_ms
: fileData.mtime_ms.toNumber();
const size = fileData.size;
let sha1hex = fileData['content.sha1hex'];
if (typeof sha1hex !== 'string' || sha1hex.length !== 40) {
sha1hex = null;
}
let nextData;
if (
existingFileData &&
existingFileData[_constants().default.MTIME] === mtime
) {
nextData = existingFileData;
} else if (
existingFileData &&
sha1hex &&
existingFileData[_constants().default.SHA1] === sha1hex
) {
nextData = [
existingFileData[0],
mtime,
existingFileData[2],
existingFileData[3],
existingFileData[4],
existingFileData[5]
];
} else {
// See ../constants.ts
nextData = ['', mtime, size, 0, '', sha1hex];
}
files.set(relativeFilePath, nextData);
changedFiles.set(relativeFilePath, nextData);
}
}
}
data.files = files;
return {
changedFiles: isFresh ? undefined : changedFiles,
hasteMap: data,
removedFiles
};
};

8
node_modules/jest-haste-map/build/getMockName.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
/**
* 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.
*/
declare const getMockName: (filePath: string) => string;
export default getMockName;

76
node_modules/jest-haste-map/build/getMockName.js generated vendored Normal file
View file

@ -0,0 +1,76 @@
'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 _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 MOCKS_PATTERN = path().sep + '__mocks__' + path().sep;
const getMockName = filePath => {
const mockPath = filePath.split(MOCKS_PATTERN)[1];
return mockPath
.substring(0, mockPath.lastIndexOf(path().extname(mockPath)))
.replace(/\\/g, '/');
};
var _default = getMockName;
exports.default = _default;

187
node_modules/jest-haste-map/build/index.d.ts generated vendored Normal file
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 { EventEmitter } from 'events';
import type { Config } from '@jest/types';
import H from './constants';
import HasteFS from './HasteFS';
import HasteModuleMap, { SerializableModuleMap as HasteSerializableModuleMap } from './ModuleMap';
import type { ChangeEvent, HasteRegExp, InternalHasteMap, HasteMap as InternalHasteMapObject } from './types';
declare type HType = typeof H;
declare type Options = {
cacheDirectory?: string;
computeDependencies?: boolean;
computeSha1?: boolean;
console?: Console;
dependencyExtractor?: string | null;
extensions: Array<string>;
forceNodeFilesystemAPI?: boolean;
hasteImplModulePath?: string;
ignorePattern?: HasteRegExp;
maxWorkers: number;
mocksPattern?: string;
name: string;
platforms: Array<string>;
resetCache?: boolean;
retainAllFiles: boolean;
rootDir: string;
roots: Array<string>;
skipPackageJson?: boolean;
throwOnModuleCollision?: boolean;
useWatchman?: boolean;
watch?: boolean;
};
declare namespace HasteMap {
type ModuleMap = HasteModuleMap;
type SerializableModuleMap = HasteSerializableModuleMap;
type FS = HasteFS;
type HasteMapObject = InternalHasteMapObject;
type HasteChangeEvent = ChangeEvent;
}
/**
* HasteMap is a JavaScript implementation of Facebook's haste module system.
*
* This implementation is inspired by https://github.com/facebook/node-haste
* and was built with for high-performance in large code repositories with
* hundreds of thousands of files. This implementation is scalable and provides
* predictable performance.
*
* Because the haste map creation and synchronization is critical to startup
* performance and most tasks are blocked by I/O this class makes heavy use of
* synchronous operations. It uses worker processes for parallelizing file
* access and metadata extraction.
*
* The data structures created by `jest-haste-map` can be used directly from the
* cache without further processing. The metadata objects in the `files` and
* `map` objects contain cross-references: a metadata object from one can look
* up the corresponding metadata object in the other map. Note that in most
* projects, the number of files will be greater than the number of haste
* modules one module can refer to many files based on platform extensions.
*
* type HasteMap = {
* clocks: WatchmanClocks,
* files: {[filepath: string]: FileMetaData},
* map: {[id: string]: ModuleMapItem},
* mocks: {[id: string]: string},
* }
*
* // Watchman clocks are used for query synchronization and file system deltas.
* type WatchmanClocks = {[filepath: string]: string};
*
* type FileMetaData = {
* id: ?string, // used to look up module metadata objects in `map`.
* mtime: number, // check for outdated files.
* size: number, // size of the file in bytes.
* visited: boolean, // whether the file has been parsed or not.
* dependencies: Array<string>, // all relative dependencies of this file.
* sha1: ?string, // SHA-1 of the file, if requested via options.
* };
*
* // Modules can be targeted to a specific platform based on the file name.
* // Example: platform.ios.js and Platform.android.js will both map to the same
* // `Platform` module. The platform should be specified during resolution.
* type ModuleMapItem = {[platform: string]: ModuleMetaData};
*
* //
* type ModuleMetaData = {
* path: string, // the path to look up the file object in `files`.
* type: string, // the module type (either `package` or `module`).
* };
*
* Note that the data structures described above are conceptual only. The actual
* implementation uses arrays and constant keys for metadata storage. Instead of
* `{id: 'flatMap', mtime: 3421, size: 42, visited: true, dependencies: []}` the real
* representation is similar to `['flatMap', 3421, 42, 1, []]` to save storage space
* and reduce parse and write time of a big JSON blob.
*
* The HasteMap is created as follows:
* 1. read data from the cache or create an empty structure.
*
* 2. crawl the file system.
* * empty cache: crawl the entire file system.
* * cache available:
* * if watchman is available: get file system delta changes.
* * if watchman is unavailable: crawl the entire file system.
* * build metadata objects for every file. This builds the `files` part of
* the `HasteMap`.
*
* 3. parse and extract metadata from changed files.
* * this is done in parallel over worker processes to improve performance.
* * the worst case is to parse all files.
* * the best case is no file system access and retrieving all data from
* the cache.
* * the average case is a small number of changed files.
*
* 4. serialize the new `HasteMap` in a cache file.
* Worker processes can directly access the cache through `HasteMap.read()`.
*
*/
declare class HasteMap extends EventEmitter {
private _buildPromise;
private _cachePath;
private _changeInterval?;
private _console;
private _options;
private _watchers;
private _worker;
constructor(options: Options);
static getCacheFilePath(tmpdir: Config.Path, name: string, ...extra: Array<string>): string;
getCacheFilePath(): string;
build(): Promise<InternalHasteMapObject>;
/**
* 1. read data from the cache or create an empty structure.
*/
read(): InternalHasteMap;
readModuleMap(): HasteModuleMap;
/**
* 2. crawl the file system.
*/
private _buildFileMap;
/**
* 3. parse and extract metadata from changed files.
*/
private _processFile;
private _buildHasteMap;
private _cleanup;
/**
* 4. serialize the new `HasteMap` in a cache file.
*/
private _persist;
/**
* Creates workers or parses files and extracts metadata in-process.
*/
private _getWorker;
private _crawl;
/**
* Watch mode
*/
private _watch;
/**
* This function should be called when the file under `filePath` is removed
* or changed. When that happens, we want to figure out if that file was
* part of a group of files that had the same ID. If it was, we want to
* remove it from the group. Furthermore, if there is only one file
* remaining in the group, then we want to restore that single file as the
* correct resolution for its ID, and cleanup the duplicates index.
*/
private _recoverDuplicates;
end(): Promise<void>;
/**
* Helpers
*/
private _ignore;
private _createEmptyMap;
static H: HType;
static DuplicateError: typeof DuplicateError;
static ModuleMap: typeof HasteModuleMap;
}
declare class DuplicateError extends Error {
mockPath1: string;
mockPath2: string;
constructor(mockPath1: string, mockPath2: string);
}
export = HasteMap;

1246
node_modules/jest-haste-map/build/index.js generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,44 @@
/**
* 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 { EventEmitter } from 'events';
import { Matcher } from 'anymatch';
/**
* Export `FSEventsWatcher` class.
* Watches `dir`.
*/
declare class FSEventsWatcher extends EventEmitter {
readonly root: string;
readonly ignored?: Matcher;
readonly glob: Array<string>;
readonly dot: boolean;
readonly hasIgnore: boolean;
readonly doIgnore: (path: string) => boolean;
readonly fsEventsWatchStopper: () => Promise<void>;
private _tracked;
static isSupported(): boolean;
private static normalizeProxy;
private static recReaddir;
constructor(dir: string, opts: {
root: string;
ignored?: Matcher;
glob: string | Array<string>;
dot: boolean;
});
/**
* End watching.
*/
close(callback?: () => void): void;
private isFileIncluded;
private handleEvent;
/**
* Emit events.
*/
private _emit;
}
export = FSEventsWatcher;

View file

@ -0,0 +1,295 @@
'use strict';
function path() {
const data = _interopRequireWildcard(require('path'));
path = function () {
return data;
};
return data;
}
function _events() {
const data = require('events');
_events = function () {
return data;
};
return data;
}
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
function _anymatch() {
const data = _interopRequireDefault(require('anymatch'));
_anymatch = function () {
return data;
};
return data;
}
function _micromatch() {
const data = _interopRequireDefault(require('micromatch'));
_micromatch = function () {
return data;
};
return data;
}
function _walker() {
const data = _interopRequireDefault(require('walker'));
_walker = 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;
}
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;
}
// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
// @ts-ignore: this is for CI which runs linux and might not have this
let fsevents = null;
try {
fsevents = require('fsevents');
} catch {
// Optional dependency, only supported on Darwin.
}
const CHANGE_EVENT = 'change';
const DELETE_EVENT = 'delete';
const ADD_EVENT = 'add';
const ALL_EVENT = 'all';
/**
* Export `FSEventsWatcher` class.
* Watches `dir`.
*/
class FSEventsWatcher extends _events().EventEmitter {
static isSupported() {
return fsevents !== null;
}
static normalizeProxy(callback) {
return (filepath, stats) => callback(path().normalize(filepath), stats);
}
static recReaddir(
dir,
dirCallback,
fileCallback,
endCallback,
errorCallback,
ignored
) {
(0, _walker().default)(dir)
.filterDir(
currentDir => !ignored || !(0, _anymatch().default)(ignored, currentDir)
)
.on('dir', FSEventsWatcher.normalizeProxy(dirCallback))
.on('file', FSEventsWatcher.normalizeProxy(fileCallback))
.on('error', errorCallback)
.on('end', () => {
endCallback();
});
}
constructor(dir, opts) {
if (!fsevents) {
throw new Error(
'`fsevents` unavailable (this watcher can only be used on Darwin)'
);
}
super();
_defineProperty(this, 'root', void 0);
_defineProperty(this, 'ignored', void 0);
_defineProperty(this, 'glob', void 0);
_defineProperty(this, 'dot', void 0);
_defineProperty(this, 'hasIgnore', void 0);
_defineProperty(this, 'doIgnore', void 0);
_defineProperty(this, 'fsEventsWatchStopper', void 0);
_defineProperty(this, '_tracked', void 0);
this.dot = opts.dot || false;
this.ignored = opts.ignored;
this.glob = Array.isArray(opts.glob) ? opts.glob : [opts.glob];
this.hasIgnore =
Boolean(opts.ignored) && !(Array.isArray(opts) && opts.length > 0);
this.doIgnore = opts.ignored
? (0, _anymatch().default)(opts.ignored)
: () => false;
this.root = path().resolve(dir);
this.fsEventsWatchStopper = fsevents.watch(
this.root,
this.handleEvent.bind(this)
);
this._tracked = new Set();
FSEventsWatcher.recReaddir(
this.root,
filepath => {
this._tracked.add(filepath);
},
filepath => {
this._tracked.add(filepath);
},
this.emit.bind(this, 'ready'),
this.emit.bind(this, 'error'),
this.ignored
);
}
/**
* End watching.
*/
close(callback) {
this.fsEventsWatchStopper().then(() => {
this.removeAllListeners();
if (typeof callback === 'function') {
process.nextTick(callback.bind(null, null, true));
}
});
}
isFileIncluded(relativePath) {
if (this.doIgnore(relativePath)) {
return false;
}
return this.glob.length
? (0, _micromatch().default)([relativePath], this.glob, {
dot: this.dot
}).length > 0
: this.dot ||
(0, _micromatch().default)([relativePath], '**/*').length > 0;
}
handleEvent(filepath) {
const relativePath = path().relative(this.root, filepath);
if (!this.isFileIncluded(relativePath)) {
return;
}
fs().lstat(filepath, (error, stat) => {
if (error && error.code !== 'ENOENT') {
this.emit('error', error);
return;
}
if (error) {
// Ignore files that aren't tracked and don't exist.
if (!this._tracked.has(filepath)) {
return;
}
this._emit(DELETE_EVENT, relativePath);
this._tracked.delete(filepath);
return;
}
if (this._tracked.has(filepath)) {
this._emit(CHANGE_EVENT, relativePath, stat);
} else {
this._tracked.add(filepath);
this._emit(ADD_EVENT, relativePath, stat);
}
});
}
/**
* Emit events.
*/
_emit(type, file, stat) {
this.emit(type, file, this.root, stat);
this.emit(ALL_EVENT, type, file, this.root, stat);
}
}
module.exports = FSEventsWatcher;

View file

@ -0,0 +1,442 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = WatchmanWatcher;
function _path() {
const data = _interopRequireDefault(require('path'));
_path = function () {
return data;
};
return data;
}
function _assert() {
const data = _interopRequireDefault(require('assert'));
_assert = function () {
return data;
};
return data;
}
function _events() {
const data = require('events');
_events = function () {
return data;
};
return data;
}
function fs() {
const data = _interopRequireWildcard(require('graceful-fs'));
fs = function () {
return data;
};
return data;
}
function _fbWatchman() {
const data = _interopRequireDefault(require('fb-watchman'));
_fbWatchman = function () {
return data;
};
return data;
}
function _common() {
const data = _interopRequireDefault(require('sane/src/common'));
_common = function () {
return data;
};
return data;
}
function _recrawlWarningDedupe() {
const data = _interopRequireDefault(
require('sane/src/utils/recrawl-warning-dedupe')
);
_recrawlWarningDedupe = 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;
}
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 CHANGE_EVENT = _common().default.CHANGE_EVENT;
const DELETE_EVENT = _common().default.DELETE_EVENT;
const ADD_EVENT = _common().default.ADD_EVENT;
const ALL_EVENT = _common().default.ALL_EVENT;
const SUB_NAME = 'sane-sub';
/**
* Watches `dir`.
*
* @class PollWatcher
* @param String dir
* @param {Object} opts
* @public
*/
function WatchmanWatcher(dir, opts) {
_common().default.assignOptions(this, opts);
this.root = _path().default.resolve(dir);
this.init();
} // eslint-disable-next-line no-proto
WatchmanWatcher.prototype.__proto__ = _events().EventEmitter.prototype;
/**
* Run the watchman `watch` command on the root and subscribe to changes.
*
* @private
*/
WatchmanWatcher.prototype.init = function () {
if (this.client) {
this.client.removeAllListeners();
}
const self = this;
this.client = new (_fbWatchman().default.Client)();
this.client.on('error', error => {
self.emit('error', error);
});
this.client.on('subscription', this.handleChangeEvent.bind(this));
this.client.on('end', () => {
console.warn('[sane] Warning: Lost connection to watchman, reconnecting..');
self.init();
});
this.watchProjectInfo = null;
function getWatchRoot() {
return self.watchProjectInfo ? self.watchProjectInfo.root : self.root;
}
function onCapability(error, resp) {
if (handleError(self, error)) {
// The Watchman watcher is unusable on this system, we cannot continue
return;
}
handleWarning(resp);
self.capabilities = resp.capabilities;
if (self.capabilities.relative_root) {
self.client.command(['watch-project', getWatchRoot()], onWatchProject);
} else {
self.client.command(['watch', getWatchRoot()], onWatch);
}
}
function onWatchProject(error, resp) {
if (handleError(self, error)) {
return;
}
handleWarning(resp);
self.watchProjectInfo = {
relativePath: resp.relative_path ? resp.relative_path : '',
root: resp.watch
};
self.client.command(['clock', getWatchRoot()], onClock);
}
function onWatch(error, resp) {
if (handleError(self, error)) {
return;
}
handleWarning(resp);
self.client.command(['clock', getWatchRoot()], onClock);
}
function onClock(error, resp) {
if (handleError(self, error)) {
return;
}
handleWarning(resp);
const options = {
fields: ['name', 'exists', 'new'],
since: resp.clock
}; // If the server has the wildmatch capability available it supports
// the recursive **/*.foo style match and we can offload our globs
// to the watchman server. This saves both on data size to be
// communicated back to us and compute for evaluating the globs
// in our node process.
if (self.capabilities.wildmatch) {
if (self.globs.length === 0) {
if (!self.dot) {
// Make sure we honor the dot option if even we're not using globs.
options.expression = [
'match',
'**',
'wholename',
{
includedotfiles: false
}
];
}
} else {
options.expression = ['anyof'];
for (const i in self.globs) {
options.expression.push([
'match',
self.globs[i],
'wholename',
{
includedotfiles: self.dot
}
]);
}
}
}
if (self.capabilities.relative_root) {
options.relative_root = self.watchProjectInfo.relativePath;
}
self.client.command(
['subscribe', getWatchRoot(), SUB_NAME, options],
onSubscribe
);
}
function onSubscribe(error, resp) {
if (handleError(self, error)) {
return;
}
handleWarning(resp);
self.emit('ready');
}
self.client.capabilityCheck(
{
optional: ['wildmatch', 'relative_root']
},
onCapability
);
};
/**
* Handles a change event coming from the subscription.
*
* @param {Object} resp
* @private
*/
WatchmanWatcher.prototype.handleChangeEvent = function (resp) {
_assert().default.equal(
resp.subscription,
SUB_NAME,
'Invalid subscription event.'
);
if (resp.is_fresh_instance) {
this.emit('fresh_instance');
}
if (resp.is_fresh_instance) {
this.emit('fresh_instance');
}
if (Array.isArray(resp.files)) {
resp.files.forEach(this.handleFileChange, this);
}
};
/**
* Handles a single change event record.
*
* @param {Object} changeDescriptor
* @private
*/
WatchmanWatcher.prototype.handleFileChange = function (changeDescriptor) {
const self = this;
let absPath;
let relativePath;
if (this.capabilities.relative_root) {
relativePath = changeDescriptor.name;
absPath = _path().default.join(
this.watchProjectInfo.root,
this.watchProjectInfo.relativePath,
relativePath
);
} else {
absPath = _path().default.join(this.root, changeDescriptor.name);
relativePath = changeDescriptor.name;
}
if (
!(self.capabilities.wildmatch && !this.hasIgnore) &&
!_common().default.isFileIncluded(
this.globs,
this.dot,
this.doIgnore,
relativePath
)
) {
return;
}
if (!changeDescriptor.exists) {
self.emitEvent(DELETE_EVENT, relativePath, self.root);
} else {
fs().lstat(absPath, (error, stat) => {
// Files can be deleted between the event and the lstat call
// the most reliable thing to do here is to ignore the event.
if (error && error.code === 'ENOENT') {
return;
}
if (handleError(self, error)) {
return;
}
const eventType = changeDescriptor.new ? ADD_EVENT : CHANGE_EVENT; // Change event on dirs are mostly useless.
if (!(eventType === CHANGE_EVENT && stat.isDirectory())) {
self.emitEvent(eventType, relativePath, self.root, stat);
}
});
}
};
/**
* Dispatches the event.
*
* @param {string} eventType
* @param {string} filepath
* @param {string} root
* @param {fs.Stat} stat
* @private
*/
WatchmanWatcher.prototype.emitEvent = function (
eventType,
filepath,
root,
stat
) {
this.emit(eventType, filepath, root, stat);
this.emit(ALL_EVENT, eventType, filepath, root, stat);
};
/**
* Closes the watcher.
*
* @param {function} callback
* @private
*/
WatchmanWatcher.prototype.close = function (callback) {
this.client.removeAllListeners();
this.client.end();
callback && callback(null, true);
};
/**
* Handles an error and returns true if exists.
*
* @param {WatchmanWatcher} self
* @param {Error} error
* @private
*/
function handleError(self, error) {
if (error != null) {
self.emit('error', error);
return true;
} else {
return false;
}
}
/**
* Handles a warning in the watchman resp object.
*
* @param {object} resp
* @private
*/
function handleWarning(resp) {
if ('warning' in resp) {
if (_recrawlWarningDedupe().default.isRecrawlWarningDupe(resp.warning)) {
return true;
}
console.warn(resp.warning);
return true;
} else {
return false;
}
}

View file

@ -0,0 +1,7 @@
/**
* 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 function extract(code: string): Set<string>;

View file

@ -0,0 +1,99 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.extract = extract;
var _isRegExpSupported = _interopRequireDefault(require('./isRegExpSupported'));
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.
*/
// Negative look behind is only supported in Node 9+
const NOT_A_DOT = (0, _isRegExpSupported.default)('(?<!\\.\\s*)')
? '(?<!\\.\\s*)'
: '(?:^|[^.]\\s*)';
const CAPTURE_STRING_LITERAL = pos => `([\`'"])([^'"\`]*?)(?:\\${pos})`;
const WORD_SEPARATOR = '\\b';
const LEFT_PARENTHESIS = '\\(';
const RIGHT_PARENTHESIS = '\\)';
const WHITESPACE = '\\s*';
const OPTIONAL_COMMA = '(:?,\\s*)?';
function createRegExp(parts, flags) {
return new RegExp(parts.join(''), flags);
}
function alternatives(...parts) {
return `(?:${parts.join('|')})`;
}
function functionCallStart(...names) {
return [
NOT_A_DOT,
WORD_SEPARATOR,
alternatives(...names),
WHITESPACE,
LEFT_PARENTHESIS,
WHITESPACE
];
}
const BLOCK_COMMENT_RE = /\/\*[^]*?\*\//g;
const LINE_COMMENT_RE = /\/\/.*/g;
const REQUIRE_OR_DYNAMIC_IMPORT_RE = createRegExp(
[
...functionCallStart('require', 'import'),
CAPTURE_STRING_LITERAL(1),
WHITESPACE,
OPTIONAL_COMMA,
RIGHT_PARENTHESIS
],
'g'
);
const IMPORT_OR_EXPORT_RE = createRegExp(
[
'\\b(?:import|export)\\s+(?!type(?:of)?\\s+)(?:[^\'"]+\\s+from\\s+)?',
CAPTURE_STRING_LITERAL(1)
],
'g'
);
const JEST_EXTENSIONS_RE = createRegExp(
[
...functionCallStart(
'jest\\s*\\.\\s*(?:requireActual|requireMock|genMockFromModule|createMockFromModule)'
),
CAPTURE_STRING_LITERAL(1),
WHITESPACE,
OPTIONAL_COMMA,
RIGHT_PARENTHESIS
],
'g'
);
function extract(code) {
const dependencies = new Set();
const addDependency = (match, _, dep) => {
dependencies.add(dep);
return match;
};
code
.replace(BLOCK_COMMENT_RE, '')
.replace(LINE_COMMENT_RE, '')
.replace(IMPORT_OR_EXPORT_RE, addDependency)
.replace(REQUIRE_OR_DYNAMIC_IMPORT_RE, addDependency)
.replace(JEST_EXTENSIONS_RE, addDependency);
return dependencies;
}

8
node_modules/jest-haste-map/build/lib/fast_path.d.ts generated vendored Normal file
View file

@ -0,0 +1,8 @@
/**
* 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 function relative(rootDir: string, filename: string): string;
export declare function resolve(rootDir: string, relativeFilename: string): string;

81
node_modules/jest-haste-map/build/lib/fast_path.js generated vendored Normal file
View file

@ -0,0 +1,81 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.relative = relative;
exports.resolve = resolve;
function path() {
const data = _interopRequireWildcard(require('path'));
path = 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.
*/
// rootDir and filename must be absolute paths (resolved)
function relative(rootDir, filename) {
return filename.indexOf(rootDir + path().sep) === 0
? filename.substr(rootDir.length + 1)
: path().relative(rootDir, filename);
}
const INDIRECTION_FRAGMENT = '..' + path().sep; // rootDir must be an absolute path and relativeFilename must be simple
// (e.g.: foo/bar or ../foo/bar, but never ./foo or foo/../bar)
function resolve(rootDir, relativeFilename) {
return relativeFilename.indexOf(INDIRECTION_FRAGMENT) === 0
? path().resolve(rootDir, relativeFilename)
: rootDir + path().sep + relativeFilename;
}

View file

@ -0,0 +1,7 @@
/**
* 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 default function getPlatformExtension(file: string, platforms?: Array<string>): string | null;

View file

@ -0,0 +1,31 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = getPlatformExtension;
/**
* 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 SUPPORTED_PLATFORM_EXTS = new Set(['android', 'ios', 'native', 'web']); // Extract platform extension: index.ios.js -> ios
function getPlatformExtension(file, platforms) {
const last = file.lastIndexOf('.');
const secondToLast = file.lastIndexOf('.', last - 1);
if (secondToLast === -1) {
return null;
}
const platform = file.substring(secondToLast + 1, last); // If an overriding platform array is passed, check that first
if (platforms && platforms.indexOf(platform) !== -1) {
return platform;
}
return SUPPORTED_PLATFORM_EXTS.has(platform) ? platform : null;
}

View file

@ -0,0 +1,7 @@
/**
* 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 default function isRegExpSupported(value: string): boolean;

View file

@ -0,0 +1,22 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.default = isRegExpSupported;
/**
* 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 isRegExpSupported(value) {
try {
// eslint-disable-next-line no-new
new RegExp(value);
return true;
} catch {
return false;
}
}

View file

@ -0,0 +1,8 @@
/**
* 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.
*/
declare let normalizePathSep: (string: string) => string;
export default normalizePathSep;

View file

@ -0,0 +1,75 @@
'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 _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.
*/
let normalizePathSep;
if (path().sep === '/') {
normalizePathSep = filePath => filePath;
} else {
normalizePathSep = filePath => filePath.replace(/\//g, path().sep);
}
var _default = normalizePathSep;
exports.default = _default;

95
node_modules/jest-haste-map/build/types.d.ts generated vendored Normal file
View file

@ -0,0 +1,95 @@
/**
* 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 { Stats } from 'graceful-fs';
import type { Config } from '@jest/types';
import type ModuleMap from './ModuleMap';
import type HasteFS from './HasteFS';
export declare type IgnoreMatcher = (item: string) => boolean;
export declare type WorkerMessage = {
computeDependencies: boolean;
computeSha1: boolean;
dependencyExtractor?: string | null;
rootDir: string;
filePath: string;
hasteImplModulePath?: string;
};
export declare type WorkerMetadata = {
dependencies: Array<string> | undefined | null;
id: string | undefined | null;
module: ModuleMetaData | undefined | null;
sha1: string | undefined | null;
};
export declare type CrawlerOptions = {
computeSha1: boolean;
data: InternalHasteMap;
extensions: Array<string>;
forceNodeFilesystemAPI: boolean;
ignore: IgnoreMatcher;
rootDir: string;
roots: Array<string>;
};
export declare type HasteImpl = {
getHasteName(filePath: Config.Path): string | undefined;
};
export declare type FileData = Map<Config.Path, FileMetaData>;
export declare type FileMetaData = [string, number, number, 0 | 1, string, string | null | undefined];
export declare type MockData = Map<string, Config.Path>;
export declare type ModuleMapData = Map<string, ModuleMapItem>;
export declare type WatchmanClocks = Map<Config.Path, string>;
export declare type HasteRegExp = RegExp | ((str: string) => boolean);
export declare type DuplicatesSet = Map<string, /* type */ number>;
export declare type DuplicatesIndex = Map<string, Map<string, DuplicatesSet>>;
export declare type InternalHasteMap = {
clocks: WatchmanClocks;
duplicates: DuplicatesIndex;
files: FileData;
map: ModuleMapData;
mocks: MockData;
};
export declare type HasteMap = {
hasteFS: HasteFS;
moduleMap: ModuleMap;
__hasteMapForTest?: InternalHasteMap | null;
};
export declare type RawModuleMap = {
rootDir: Config.Path;
duplicates: DuplicatesIndex;
map: ModuleMapData;
mocks: MockData;
};
declare type ModuleMapItem = {
[platform: string]: ModuleMetaData;
};
export declare type ModuleMetaData = [Config.Path, /* type */ number];
export declare type HType = {
ID: 0;
MTIME: 1;
SIZE: 2;
VISITED: 3;
DEPENDENCIES: 4;
SHA1: 5;
PATH: 0;
TYPE: 1;
MODULE: 0;
PACKAGE: 1;
GENERIC_PLATFORM: 'g';
NATIVE_PLATFORM: 'native';
DEPENDENCY_DELIM: '\0';
};
export declare type HTypeValue = HType[keyof HType];
export declare type EventsQueue = Array<{
filePath: Config.Path;
stat: Stats | undefined;
type: string;
}>;
export declare type ChangeEvent = {
eventsQueue: EventsQueue;
hasteFS: HasteFS;
moduleMap: ModuleMap;
};
export {};

1
node_modules/jest-haste-map/build/types.js generated vendored Normal file
View file

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

9
node_modules/jest-haste-map/build/worker.d.ts generated vendored Normal file
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 { WorkerMessage, WorkerMetadata } from './types';
export declare function worker(data: WorkerMessage): Promise<WorkerMetadata>;
export declare function getSha1(data: WorkerMessage): Promise<WorkerMetadata>;

197
node_modules/jest-haste-map/build/worker.js generated vendored Normal file
View file

@ -0,0 +1,197 @@
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports.worker = worker;
exports.getSha1 = getSha1;
function _crypto() {
const data = require('crypto');
_crypto = function () {
return data;
};
return data;
}
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;
}
var _blacklist = _interopRequireDefault(require('./blacklist'));
var _constants = _interopRequireDefault(require('./constants'));
var dependencyExtractor = _interopRequireWildcard(
require('./lib/dependencyExtractor')
);
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 PACKAGE_JSON = path().sep + 'package.json';
let hasteImpl = null;
let hasteImplModulePath = null;
function sha1hex(content) {
return (0, _crypto().createHash)('sha1').update(content).digest('hex');
}
async function worker(data) {
if (
data.hasteImplModulePath &&
data.hasteImplModulePath !== hasteImplModulePath
) {
if (hasteImpl) {
throw new Error('jest-haste-map: hasteImplModulePath changed');
}
hasteImplModulePath = data.hasteImplModulePath;
hasteImpl = require(hasteImplModulePath);
}
let content;
let dependencies;
let id;
let module;
let sha1;
const {computeDependencies, computeSha1, rootDir, filePath} = data;
const getContent = () => {
if (content === undefined) {
content = fs().readFileSync(filePath, 'utf8');
}
return content;
};
if (filePath.endsWith(PACKAGE_JSON)) {
// Process a package.json that is returned as a PACKAGE type with its name.
try {
const fileData = JSON.parse(getContent());
if (fileData.name) {
const relativeFilePath = path().relative(rootDir, filePath);
id = fileData.name;
module = [relativeFilePath, _constants.default.PACKAGE];
}
} catch (err) {
throw new Error(`Cannot parse ${filePath} as JSON: ${err.message}`);
}
} else if (
!_blacklist.default.has(filePath.substr(filePath.lastIndexOf('.')))
) {
// Process a random file that is returned as a MODULE.
if (hasteImpl) {
id = hasteImpl.getHasteName(filePath);
}
if (computeDependencies) {
const content = getContent();
dependencies = Array.from(
data.dependencyExtractor
? require(data.dependencyExtractor).extract(
content,
filePath,
dependencyExtractor.extract
)
: dependencyExtractor.extract(content)
);
}
if (id) {
const relativeFilePath = path().relative(rootDir, filePath);
module = [relativeFilePath, _constants.default.MODULE];
}
} // If a SHA-1 is requested on update, compute it.
if (computeSha1) {
sha1 = sha1hex(getContent() || fs().readFileSync(filePath));
}
return {
dependencies,
id,
module,
sha1
};
}
async function getSha1(data) {
const sha1 = data.computeSha1
? sha1hex(fs().readFileSync(data.filePath))
: null;
return {
dependencies: undefined,
id: undefined,
module: undefined,
sha1
};
}

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
};

45
node_modules/jest-haste-map/package.json generated vendored Normal file
View file

@ -0,0 +1,45 @@
{
"name": "jest-haste-map",
"version": "26.3.0",
"repository": {
"type": "git",
"url": "https://github.com/facebook/jest.git",
"directory": "packages/jest-haste-map"
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"dependencies": {
"@jest/types": "^26.3.0",
"@types/graceful-fs": "^4.1.2",
"@types/node": "*",
"anymatch": "^3.0.3",
"fb-watchman": "^2.0.0",
"graceful-fs": "^4.2.4",
"jest-regex-util": "^26.0.0",
"jest-serializer": "^26.3.0",
"jest-util": "^26.3.0",
"jest-worker": "^26.3.0",
"micromatch": "^4.0.2",
"sane": "^4.0.3",
"walker": "^1.0.7"
},
"devDependencies": {
"@jest/test-utils": "^26.3.0",
"@types/anymatch": "^1.3.1",
"@types/fb-watchman": "^2.0.0",
"@types/micromatch": "^4.0.0",
"@types/sane": "^2.0.0",
"slash": "^3.0.0"
},
"optionalDependencies": {
"fsevents": "^2.1.2"
},
"engines": {
"node": ">= 10.14.2"
},
"publishConfig": {
"access": "public"
},
"gitHead": "3a7e06fe855515a848241bb06a6f6e117847443d"
}