initial commit taken from gitlab.lrz.de

This commit is contained in:
privatereese
2018-08-24 18:09:42 +02:00
parent ae54ed4c48
commit fc05486403
28494 changed files with 2159823 additions and 0 deletions

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

@@ -0,0 +1,40 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright (c) 2014-present, Facebook, Inc. 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 contain any "@providesModule"
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']);
exports.default = extensions;

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

@@ -0,0 +1,42 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright (c) 2014-present, Facebook, Inc. 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.
*
*
*/
/* eslint-disable sort-keys */
/*
* 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.
*/
exports.default = {
/* file map attributes */
ID: 0,
MTIME: 1,
VISITED: 2,
DEPENDENCIES: 3,
/* module map attributes */
PATH: 0,
TYPE: 1,
/* module types */
MODULE: 0,
PACKAGE: 1,
/* platforms */
GENERIC_PLATFORM: 'g',
NATIVE_PLATFORM: 'native'
};

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

@@ -0,0 +1,161 @@
'use strict';
var _fs;
function _load_fs() {
return _fs = _interopRequireDefault(require('fs'));
}
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _child_process;
function _load_child_process() {
return _child_process = require('child_process');
}
var _constants;
function _load_constants() {
return _constants = _interopRequireDefault(require('../constants'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Copyright (c) 2014-present, Facebook, Inc. 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 find(roots, extensions, ignore, callback) {
const result = [];
let activeCalls = 0;
function search(directory) {
activeCalls++;
(_fs || _load_fs()).default.readdir(directory, (err, names) => {
activeCalls--;
names.forEach(file => {
file = (_path || _load_path()).default.join(directory, file);
if (ignore(file)) {
return;
}
activeCalls++;
(_fs || _load_fs()).default.lstat(file, (err, stat) => {
activeCalls--;
if (!err && stat && !stat.isSymbolicLink()) {
if (stat.isDirectory()) {
search(file);
} else {
const ext = (_path || _load_path()).default.extname(file).substr(1);
if (extensions.indexOf(ext) !== -1) {
result.push([file, stat.mtime.getTime()]);
}
}
}
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 = [].concat(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 || _load_child_process()).spawn)('find', args);
let stdout = '';
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 || _load_fs()).default.stat(path, (err, stat) => {
if (!err && stat) {
result.push([path, stat.mtime.getTime()]);
}
if (--count === 0) {
callback(result);
}
});
});
}
});
}
module.exports = function nodeCrawl(options) {
const data = options.data,
extensions = options.extensions,
forceNodeFilesystemAPI = options.forceNodeFilesystemAPI,
ignore = options.ignore,
roots = options.roots;
return new Promise(resolve => {
const callback = list => {
const files = Object.create(null);
list.forEach(fileData => {
const name = fileData[0];
const mtime = fileData[1];
const existingFile = data.files[name];
if (existingFile && existingFile[(_constants || _load_constants()).default.MTIME] === mtime) {
files[name] = existingFile;
} else {
// See ../constants.js
files[name] = ['', mtime, 0, []];
}
});
data.files = files;
resolve(data);
};
if (forceNodeFilesystemAPI || process.platform === 'win32') {
find(roots, extensions, ignore, callback);
} else {
findNative(roots, extensions, ignore, callback);
}
});
};

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

@@ -0,0 +1,212 @@
'use strict';
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _normalize_path_sep;
function _load_normalize_path_sep() {
return _normalize_path_sep = _interopRequireDefault(require('../lib/normalize_path_sep'));
}
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _fbWatchman;
function _load_fbWatchman() {
return _fbWatchman = _interopRequireDefault(require('fb-watchman'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireDefault(require('../constants'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /**
* Copyright (c) 2014-present, Facebook, Inc. 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.html';
function WatchmanError(error) {
error.message = `Watchman error: ${error.message.trim()}. Make sure watchman ` + `is running for this project. See ${watchmanURL}.`;
return error;
}
module.exports = (() => {
var _ref = _asyncToGenerator(function* (options) {
let getWatchmanRoots = (() => {
var _ref2 = _asyncToGenerator(function* (roots) {
const watchmanRoots = new Map();
yield Promise.all(roots.map((() => {
var _ref3 = _asyncToGenerator(function* (root) {
const response = yield 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/directories
watchmanRoots.set(response.watch, []);
}
}
});
return function (_x3) {
return _ref3.apply(this, arguments);
};
})()));
return watchmanRoots;
});
return function getWatchmanRoots(_x2) {
return _ref2.apply(this, arguments);
};
})();
let queryWatchmanForDirs = (() => {
var _ref4 = _asyncToGenerator(function* (rootProjectDirMappings) {
const files = new Map();
let isFresh = false;
yield Promise.all(Array.from(rootProjectDirMappings).map((() => {
var _ref6 = _asyncToGenerator(function* (_ref5) {
var _ref7 = _slicedToArray(_ref5, 2);
let root = _ref7[0],
directoryFilters = _ref7[1];
const expression = Array.from(defaultWatchExpression);
if (directoryFilters.length > 0) {
expression.push(['anyof'].concat(_toConsumableArray(directoryFilters.map(function (dir) {
return ['dirname', dir];
}))));
}
const fields = ['name', 'exists', 'mtime_ms'];
const query = clocks[root] ? // Use the `since` generator if we have a clock available
{ expression, fields, since: clocks[root] } : // Otherwise use the `suffix` generator
{ expression, fields, suffix: extensions };
const response = yield 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 function (_x5) {
return _ref6.apply(this, arguments);
};
})()));
return {
files,
isFresh
};
});
return function queryWatchmanForDirs(_x4) {
return _ref4.apply(this, arguments);
};
})();
const data = options.data,
extensions = options.extensions,
ignore = options.ignore,
roots = options.roots;
const defaultWatchExpression = ['allof', ['type', 'f'], ['anyof'].concat(extensions.map(function (extension) {
return ['suffix', extension];
}))];
const clocks = data.clocks;
const client = new (_fbWatchman || _load_fbWatchman()).default.Client();
let clientError;
client.on('error', function (error) {
return clientError = WatchmanError(error);
});
const cmd = function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new Promise(function (resolve, reject) {
return client.command(args, function (error, result) {
return error ? reject(WatchmanError(error)) : resolve(result);
});
});
};
let files = data.files;
let watchmanFiles;
try {
const watchmanRoots = yield getWatchmanRoots(roots);
const watchmanFileResults = yield queryWatchmanForDirs(watchmanRoots);
// Reset the file map if watchman was restarted and sends us a list of files.
if (watchmanFileResults.isFresh) {
files = Object.create(null);
}
watchmanFiles = watchmanFileResults.files;
} finally {
client.end();
}
if (clientError) {
throw clientError;
}
for (const _ref8 of watchmanFiles) {
var _ref9 = _slicedToArray(_ref8, 2);
const watchRoot = _ref9[0];
const response = _ref9[1];
const fsRoot = (0, (_normalize_path_sep || _load_normalize_path_sep()).default)(watchRoot);
clocks[fsRoot] = response.clock;
for (const fileData of response.files) {
const name = fsRoot + (_path || _load_path()).default.sep + (0, (_normalize_path_sep || _load_normalize_path_sep()).default)(fileData.name);
if (!fileData.exists) {
delete files[name];
} else if (!ignore(name)) {
const mtime = typeof fileData.mtime_ms === 'number' ? fileData.mtime_ms : fileData.mtime_ms.toNumber();
const existingFileData = data.files[name];
const isOld = existingFileData && existingFileData[(_constants || _load_constants()).default.MTIME] === mtime;
if (isOld) {
files[name] = existingFileData;
} else {
// See ../constants.js
files[name] = ['', mtime, 0, []];
}
}
}
}
data.files = files;
return data;
});
function watchmanCrawl(_x) {
return _ref.apply(this, arguments);
}
return watchmanCrawl;
})();

29
node_modules/jest-haste-map/build/get_mock_name.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const MOCKS_PATTERN = (_path || _load_path()).default.sep + '__mocks__' + (_path || _load_path()).default.sep; /**
* Copyright (c) 2014-present, Facebook, Inc. 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 getMockName = filePath => {
const mockPath = filePath.split(MOCKS_PATTERN)[1];
return mockPath.substring(0, mockPath.lastIndexOf((_path || _load_path()).default.extname(mockPath))).replace(/\\/g, '/');
};
exports.default = getMockName;

80
node_modules/jest-haste-map/build/haste_fs.js generated vendored Normal file
View File

@@ -0,0 +1,80 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _micromatch;
function _load_micromatch() {
return _micromatch = _interopRequireDefault(require('micromatch'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireDefault(require('./constants'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
class HasteFS {
constructor(files) {
this._files = files;
}
getModuleName(file) {
return this._files[file] && this._files[file][(_constants || _load_constants()).default.ID] || null;
}
getDependencies(file) {
return this._files[file] && this._files[file][(_constants || _load_constants()).default.DEPENDENCIES] || null;
}
exists(file) {
return !!this._files[file];
}
getAllFiles() {
return Object.keys(this._files);
}
matchFiles(pattern) {
if (!(pattern instanceof RegExp)) {
pattern = new RegExp(pattern);
}
const files = [];
for (const file in this._files) {
if (pattern.test(file)) {
files.push(file);
}
}
return files;
}
matchFilesWithGlob(globs, root) {
const files = new Set();
for (const file in this._files) {
const filePath = root ? (_path || _load_path()).default.relative(root, file) : file;
if ((0, (_micromatch || _load_micromatch()).default)([filePath], globs).length) {
files.add(file);
}
}
return files;
}
}
exports.default = HasteFS; /**
* Copyright (c) 2014-present, Facebook, Inc. 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.
*
*
*/

786
node_modules/jest-haste-map/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,786 @@
'use strict';
var _child_process;
function _load_child_process() {
return _child_process = require('child_process');
}
var _package;
function _load_package() {
return _package = require('../package.json');
}
var _worker;
function _load_worker() {
return _worker = require('./worker');
}
var _crypto;
function _load_crypto() {
return _crypto = _interopRequireDefault(require('crypto'));
}
var _events;
function _load_events() {
return _events = _interopRequireDefault(require('events'));
}
var _get_mock_name;
function _load_get_mock_name() {
return _get_mock_name = _interopRequireDefault(require('./get_mock_name'));
}
var _get_platform_extension;
function _load_get_platform_extension() {
return _get_platform_extension = _interopRequireDefault(require('./lib/get_platform_extension'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireDefault(require('./constants'));
}
var _haste_fs;
function _load_haste_fs() {
return _haste_fs = _interopRequireDefault(require('./haste_fs'));
}
var _module_map;
function _load_module_map() {
return _module_map = _interopRequireDefault(require('./module_map'));
}
var _node;
function _load_node() {
return _node = _interopRequireDefault(require('./crawlers/node'));
}
var _normalize_path_sep;
function _load_normalize_path_sep() {
return _normalize_path_sep = _interopRequireDefault(require('./lib/normalize_path_sep'));
}
var _os;
function _load_os() {
return _os = _interopRequireDefault(require('os'));
}
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _sane;
function _load_sane() {
return _sane = _interopRequireDefault(require('sane'));
}
var _jestSerializer;
function _load_jestSerializer() {
return _jestSerializer = _interopRequireDefault(require('jest-serializer'));
}
var _watchman;
function _load_watchman() {
return _watchman = _interopRequireDefault(require('./crawlers/watchman'));
}
var _watchman_watcher;
function _load_watchman_watcher() {
return _watchman_watcher = _interopRequireDefault(require('./lib/watchman_watcher'));
}
var _jestWorker;
function _load_jestWorker() {
return _jestWorker = _interopRequireDefault(require('jest-worker'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// eslint-disable-next-line import/no-duplicates
// eslint-disable-next-line import/no-duplicates
const CHANGE_INTERVAL = 30;
// eslint-disable-next-line import/default
// eslint-disable-next-line import/default
/**
* Copyright (c) 2014-present, Facebook, Inc. 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 MAX_WAIT_TIME = 240000;
const NODE_MODULES = (_path || _load_path()).default.sep + 'node_modules' + (_path || _load_path()).default.sep;
const canUseWatchman = (() => {
try {
(0, (_child_process || _load_child_process()).execSync)('watchman --version', { stdio: ['ignore'] });
return true;
} catch (e) {}
return false;
})();
const escapePathSeparator = string => (_path || _load_path()).default.sep === '\\' ? string.replace(/(\/|\\)/g, '\\\\') : string;
const getWhiteList = list => {
if (list && list.length) {
return new RegExp('(' + escapePathSeparator(NODE_MODULES) + '(?:' + list.join('|') + ')(?=$|' + escapePathSeparator((_path || _load_path()).default.sep) + '))', 'g');
}
return null;
};
/**
* 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.
* visited: boolean, // whether the file has been parsed or not.
* dependencies: Array<string>, // all relative dependencies of this file.
* };
*
* // 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, visited: true, dependencies: []}` the real
* representation is similar to `['flatMap', 3421, 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()`.
*
*/
class HasteMap extends (_events || _load_events()).default {
constructor(options) {
super();
this._options = {
cacheDirectory: options.cacheDirectory || (_os || _load_os()).default.tmpdir(),
extensions: options.extensions,
forceNodeFilesystemAPI: !!options.forceNodeFilesystemAPI,
hasteImplModulePath: options.hasteImplModulePath,
ignorePattern: options.ignorePattern,
maxWorkers: options.maxWorkers,
mocksPattern: options.mocksPattern ? new RegExp(options.mocksPattern) : null,
name: options.name,
platforms: options.platforms,
resetCache: options.resetCache,
retainAllFiles: options.retainAllFiles,
roots: Array.from(new Set(options.roots)),
throwOnModuleCollision: !!options.throwOnModuleCollision,
useWatchman: options.useWatchman == null ? true : options.useWatchman,
watch: !!options.watch
};
this._console = options.console || global.console;
if (!(options.ignorePattern instanceof RegExp)) {
this._console.warn('jest-haste-map: the `ignorePattern` options as a function is being ' + 'deprecated. Provide a RegExp instead. See https://github.com/facebook/jest/pull/4063.');
}
this._cachePath = HasteMap.getCacheFilePath(this._options.cacheDirectory, `haste-map-${this._options.name}`, (_package || _load_package()).version, this._options.roots.join(':'), this._options.extensions.join(':'), this._options.platforms.join(':'), options.mocksPattern || '', options.ignorePattern.toString());
this._whitelist = getWhiteList(options.providesModuleNodeModules);
this._buildPromise = null;
this._watchers = [];
this._worker = null;
}
static getCacheFilePath(tmpdir, name) {
for (var _len = arguments.length, extra = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
extra[_key - 2] = arguments[_key];
}
const hash = (_crypto || _load_crypto()).default.createHash('md5').update(name + extra.join(''));
return (_path || _load_path()).default.join(tmpdir, name.replace(/\W/g, '-') + '-' + hash.digest('hex'));
}
build() {
if (!this._buildPromise) {
this._buildPromise = this._buildFileMap().then(data => this._buildHasteMap(data)).then(hasteMap => {
this._persist(hasteMap);
const hasteFS = new (_haste_fs || _load_haste_fs()).default(hasteMap.files);
const moduleMap = new (_module_map || _load_module_map()).default({
duplicates: hasteMap.duplicates,
map: hasteMap.map,
mocks: hasteMap.mocks
});
const __hasteMapForTest = process.env.NODE_ENV === 'test' && hasteMap || null;
return this._watch(hasteMap, hasteFS, moduleMap).then(() => ({
__hasteMapForTest,
hasteFS,
moduleMap
}));
});
}
return this._buildPromise;
}
/**
* 1. read data from the cache or create an empty structure.
*/
read() {
let hasteMap;
try {
hasteMap = (_jestSerializer || _load_jestSerializer()).default.readFileSync(this._cachePath);
} catch (err) {
hasteMap = this._createEmptyMap();
}
for (const key in hasteMap) {
Object.setPrototypeOf(hasteMap[key], null);
}
return hasteMap;
}
readModuleMap() {
const data = this.read();
return new (_module_map || _load_module_map()).default({
duplicates: data.duplicates,
map: data.map,
mocks: data.mocks
});
}
/**
* 2. crawl the file system.
*/
_buildFileMap() {
const read = this._options.resetCache ? this._createEmptyMap : this.read;
return Promise.resolve().then(() => read.call(this)).catch(() => this._createEmptyMap()).then(cachedHasteMap => {
const cachedFiles = Object.keys(cachedHasteMap.files).map(filePath => {
const moduleName = cachedHasteMap.files[filePath][(_constants || _load_constants()).default.ID];
return { moduleName, path: filePath };
});
return this._crawl(cachedHasteMap).then(hasteMap => {
const deprecatedFiles = cachedFiles.filter(file => {
const fileData = hasteMap.files[file.path];
return fileData == null || file.moduleName !== fileData[(_constants || _load_constants()).default.ID];
});
return { deprecatedFiles, hasteMap };
});
});
}
/**
* 3. parse and extract metadata from changed files.
*/
_processFile(hasteMap, map, mocks, filePath, workerOptions) {
const setModule = (id, module) => {
if (!map[id]) {
// $FlowFixMe
map[id] = Object.create(null);
}
const moduleMap = map[id];
const platform = (0, (_get_platform_extension || _load_get_platform_extension()).default)(module[(_constants || _load_constants()).default.PATH], this._options.platforms) || (_constants || _load_constants()).default.GENERIC_PLATFORM;
const existingModule = moduleMap[platform];
if (existingModule && existingModule[(_constants || _load_constants()).default.PATH] !== module[(_constants || _load_constants()).default.PATH]) {
const message = `jest-haste-map: @providesModule naming collision:\n` + ` Duplicate module name: ${id}\n` + ` Paths: ${module[(_constants || _load_constants()).default.PATH]} collides with ` + `${existingModule[(_constants || _load_constants()).default.PATH]}\n\nThis ` + `${this._options.throwOnModuleCollision ? 'error' : 'warning'} ` + `is caused by a @providesModule declaration ` + `with the same name across two different files.`;
if (this._options.throwOnModuleCollision) {
throw new Error(message);
}
this._console.warn(message);
// We do NOT want consumers to use a module that is ambiguous.
delete moduleMap[platform];
if (Object.keys(moduleMap).length === 1) {
delete map[id];
}
let dupsByPlatform = hasteMap.duplicates[id];
if (dupsByPlatform == null) {
dupsByPlatform = hasteMap.duplicates[id] = Object.create(null);
}
const dups = dupsByPlatform[platform] = Object.create(null);
dups[module[(_constants || _load_constants()).default.PATH]] = module[(_constants || _load_constants()).default.TYPE];
dups[existingModule[(_constants || _load_constants()).default.PATH]] = existingModule[(_constants || _load_constants()).default.TYPE];
return;
}
const dupsByPlatform = hasteMap.duplicates[id];
if (dupsByPlatform != null) {
const dups = dupsByPlatform[platform];
if (dups != null) {
dups[module[(_constants || _load_constants()).default.PATH]] = module[(_constants || _load_constants()).default.TYPE];
}
return;
}
moduleMap[platform] = module;
};
// If we retain all files in the virtual HasteFS representation, we avoid
// reading them if they aren't important (node_modules).
if (this._options.retainAllFiles && this._isNodeModulesDir(filePath)) {
return null;
}
if (this._options.mocksPattern && this._options.mocksPattern.test(filePath)) {
const mockPath = (0, (_get_mock_name || _load_get_mock_name()).default)(filePath);
if (mocks[mockPath]) {
this._console.warn(`jest-haste-map: duplicate manual mock found:\n` + ` Module name: ${mockPath}\n` + ` Duplicate Mock path: ${filePath}\nThis warning ` + `is caused by two manual mock files with the same file name.\n` + `Jest will use the mock file found in: \n` + `${filePath}\n` + ` Please delete one of the following two files: \n ` + `${mocks[mockPath]}\n${filePath}\n\n`);
}
mocks[mockPath] = filePath;
}
const fileMetadata = hasteMap.files[filePath];
const moduleMetadata = hasteMap.map[fileMetadata[(_constants || _load_constants()).default.ID]];
if (fileMetadata[(_constants || _load_constants()).default.VISITED]) {
if (!fileMetadata[(_constants || _load_constants()).default.ID]) {
return null;
}
if (moduleMetadata != null) {
const platform = (0, (_get_platform_extension || _load_get_platform_extension()).default)(filePath, this._options.platforms) || (_constants || _load_constants()).default.GENERIC_PLATFORM;
const module = moduleMetadata[platform];
if (module == null) {
return null;
}
const modulesByPlatform = map[fileMetadata[(_constants || _load_constants()).default.ID]] || (map[fileMetadata[(_constants || _load_constants()).default.ID]] = {});
modulesByPlatform[platform] = module;
return null;
}
}
return this._getWorker(workerOptions).worker({
filePath,
hasteImplModulePath: this._options.hasteImplModulePath
}).then(metadata => {
// `1` for truthy values instead of `true` to save cache space.
fileMetadata[(_constants || _load_constants()).default.VISITED] = 1;
const metadataId = metadata.id;
const metadataModule = metadata.module;
if (metadataId && metadataModule) {
fileMetadata[(_constants || _load_constants()).default.ID] = metadataId;
setModule(metadataId, metadataModule);
}
fileMetadata[(_constants || _load_constants()).default.DEPENDENCIES] = metadata.dependencies || [];
}, error => {
if (typeof error !== 'object' || !error.message || !error.stack) {
error = new Error(error);
error.stack = ''; // Remove stack for stack-less errors.
}
// $FlowFixMe: checking error code is OK if error comes from "fs".
if (['ENOENT', 'EACCES'].indexOf(error.code) < 0) {
throw error;
}
// If a file cannot be read we remove it from the file list and
// ignore the failure silently.
delete hasteMap.files[filePath];
});
}
_buildHasteMap(data) {
const deprecatedFiles = data.deprecatedFiles,
hasteMap = data.hasteMap;
const map = Object.create(null);
const mocks = Object.create(null);
const promises = [];
for (let i = 0; i < deprecatedFiles.length; ++i) {
const file = deprecatedFiles[i];
this._recoverDuplicates(hasteMap, file.path, file.moduleName);
}
for (const filePath in hasteMap.files) {
const promise = this._processFile(hasteMap, map, mocks, filePath);
if (promise) {
promises.push(promise);
}
}
return Promise.all(promises).then(() => {
this._cleanup();
hasteMap.map = map;
hasteMap.mocks = mocks;
return hasteMap;
}).catch(error => {
this._cleanup();
return Promise.reject(error);
});
}
_cleanup() {
const worker = this._worker;
if (worker && typeof worker.end === 'function') {
worker.end();
}
this._worker = null;
}
/**
* 4. serialize the new `HasteMap` in a cache file.
*/
_persist(hasteMap) {
(_jestSerializer || _load_jestSerializer()).default.writeFileSync(this._cachePath, hasteMap);
}
/**
* Creates workers or parses files and extracts metadata in-process.
*/
_getWorker(options) {
if (!this._worker) {
if (options && options.forceInBand || this._options.maxWorkers <= 1) {
this._worker = { worker: (_worker || _load_worker()).worker };
} else {
// $FlowFixMe: assignment of a worker with custom properties.
this._worker = new (_jestWorker || _load_jestWorker()).default(require.resolve('./worker'), {
exposedMethods: ['worker'],
maxRetries: 3,
numWorkers: this._options.maxWorkers
});
}
}
return this._worker;
}
_crawl(hasteMap) {
const options = this._options;
const ignore = this._ignore.bind(this);
const crawl = canUseWatchman && this._options.useWatchman ? (_watchman || _load_watchman()).default : (_node || _load_node()).default;
const retry = error => {
if (crawl === (_watchman || _load_watchman()).default) {
this._console.warn(`jest-haste-map: Watchman crawl failed. Retrying once with node ` + `crawler.\n` + ` Usually this happens when watchman isn't running. Create an ` + `empty \`.watchmanconfig\` file in your project's root folder or ` + `initialize a git or hg repository in your project.\n` + ` ` + error);
return (0, (_node || _load_node()).default)({
data: hasteMap,
extensions: options.extensions,
forceNodeFilesystemAPI: options.forceNodeFilesystemAPI,
ignore,
roots: options.roots
}).catch(e => {
throw new Error(`Crawler retry failed:\n` + ` Original error: ${error.message}\n` + ` Retry error: ${e.message}\n`);
});
}
throw error;
};
try {
return crawl({
data: hasteMap,
extensions: options.extensions,
forceNodeFilesystemAPI: options.forceNodeFilesystemAPI,
ignore,
roots: options.roots
}).catch(retry);
} catch (error) {
return retry(error);
}
}
/**
* Watch mode
*/
_watch(hasteMap, hasteFS, moduleMap) {
if (!this._options.watch) {
return Promise.resolve();
}
// In watch mode, we'll only warn about module collisions and we'll retain
// all files, even changes to node_modules.
this._options.throwOnModuleCollision = false;
this._options.retainAllFiles = true;
const Watcher = canUseWatchman && this._options.useWatchman ? (_watchman_watcher || _load_watchman_watcher()).default : (_os || _load_os()).default.platform() === 'darwin' ? (_sane || _load_sane()).default.FSEventsWatcher : (_sane || _load_sane()).default.NodeWatcher;
const extensions = this._options.extensions;
const ignorePattern = this._options.ignorePattern;
let changeQueue = Promise.resolve();
let eventsQueue = [];
// We only need to copy the entire haste map once on every "frame".
let mustCopy = true;
const createWatcher = root => {
const watcher = new Watcher(root, {
dot: false,
glob: extensions.map(extension => '**/*.' + extension),
ignored: ignorePattern
});
return new Promise((resolve, reject) => {
const rejectTimeout = setTimeout(() => reject(new Error('Failed to start watch mode.')), MAX_WAIT_TIME);
watcher.once('ready', () => {
clearTimeout(rejectTimeout);
watcher.on('all', onChange);
resolve(watcher);
});
});
};
const emitChange = () => {
if (eventsQueue.length) {
mustCopy = true;
this.emit('change', {
eventsQueue,
hasteFS: new (_haste_fs || _load_haste_fs()).default(hasteMap.files),
moduleMap: new (_module_map || _load_module_map()).default({
duplicates: hasteMap.duplicates,
map: hasteMap.map,
mocks: hasteMap.mocks
})
});
eventsQueue = [];
}
};
const onChange = (type, filePath, root, stat) => {
filePath = (_path || _load_path()).default.join(root, (0, (_normalize_path_sep || _load_normalize_path_sep()).default)(filePath));
if (this._ignore(filePath) || !extensions.some(extension => filePath.endsWith(extension))) {
return;
}
changeQueue = changeQueue.then(() => {
// If we get duplicate events for the same file, ignore them.
if (eventsQueue.find(event => event.type === type && event.filePath === filePath && (!event.stat && !stat || event.stat && stat && event.stat.mtime.getTime() === stat.mtime.getTime()))) {
return null;
}
if (mustCopy) {
mustCopy = false;
// $FlowFixMe
hasteMap = {
clocks: copy(hasteMap.clocks),
duplicates: copy(hasteMap.duplicates),
files: copy(hasteMap.files),
map: copy(hasteMap.map),
mocks: copy(hasteMap.mocks)
};
}
const add = () => eventsQueue.push({ filePath, stat, type });
// Delete the file and all of its metadata.
const moduleName = hasteMap.files[filePath] && hasteMap.files[filePath][(_constants || _load_constants()).default.ID];
const platform = (0, (_get_platform_extension || _load_get_platform_extension()).default)(filePath, this._options.platforms) || (_constants || _load_constants()).default.GENERIC_PLATFORM;
delete hasteMap.files[filePath];
let moduleMap = hasteMap.map[moduleName];
if (moduleMap != null) {
// We are forced to copy the object because jest-haste-map exposes
// the map as an immutable entity.
moduleMap = copy(moduleMap);
delete moduleMap[platform];
if (Object.keys(moduleMap).length === 0) {
delete hasteMap.map[moduleName];
} else {
// $FlowFixMe
hasteMap.map[moduleName] = moduleMap;
}
}
if (this._options.mocksPattern && this._options.mocksPattern.test(filePath)) {
const mockName = (0, (_get_mock_name || _load_get_mock_name()).default)(filePath);
delete hasteMap.mocks[mockName];
}
this._recoverDuplicates(hasteMap, filePath, moduleName);
// If the file was added or changed,
// parse it and update the haste map.
if (type === 'add' || type === 'change') {
const fileMetadata = ['', stat.mtime.getTime(), 0, []];
hasteMap.files[filePath] = fileMetadata;
const promise = this._processFile(hasteMap, hasteMap.map, hasteMap.mocks, filePath, {
forceInBand: true
});
// Cleanup
this._cleanup();
if (promise) {
return promise.then(add);
} else {
// If a file in node_modules has changed,
// emit an event regardless.
add();
}
} else {
add();
}
return null;
}).catch(error => {
this._console.error(`jest-haste-map: watch error:\n ${error.stack}\n`);
});
};
this._changeInterval = setInterval(emitChange, CHANGE_INTERVAL);
return Promise.all(this._options.roots.map(createWatcher)).then(watchers => {
this._watchers = watchers;
});
}
/**
* 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.
*/
_recoverDuplicates(hasteMap, filePath, moduleName) {
let dupsByPlatform = hasteMap.duplicates[moduleName];
if (dupsByPlatform == null) {
return;
}
const platform = (0, (_get_platform_extension || _load_get_platform_extension()).default)(filePath, this._options.platforms) || (_constants || _load_constants()).default.GENERIC_PLATFORM;
let dups = dupsByPlatform[platform];
if (dups == null) {
return;
}
dupsByPlatform = hasteMap.duplicates[moduleName] = copy(dupsByPlatform);
dups = dupsByPlatform[platform] = copy(dups);
const dedupType = dups[filePath];
delete dups[filePath];
const filePaths = Object.keys(dups);
if (filePaths.length > 1) {
return;
}
let dedupMap = hasteMap.map[moduleName];
if (dedupMap == null) {
dedupMap = hasteMap.map[moduleName] = Object.create(null);
}
dedupMap[platform] = [filePaths[0], dedupType];
delete dupsByPlatform[platform];
if (Object.keys(dupsByPlatform).length === 0) {
delete hasteMap.duplicates[moduleName];
}
}
end() {
clearInterval(this._changeInterval);
if (!this._watchers.length) {
return Promise.resolve();
}
return Promise.all(this._watchers.map(watcher => new Promise(resolve => watcher.close(resolve)))).then(() => {
this._watchers = [];
});
}
/**
* Helpers
*/
_ignore(filePath) {
const ignorePattern = this._options.ignorePattern;
const ignoreMatched = ignorePattern instanceof RegExp ? ignorePattern.test(filePath) : ignorePattern(filePath);
return ignoreMatched || !this._options.retainAllFiles && this._isNodeModulesDir(filePath);
}
_isNodeModulesDir(filePath) {
if (!filePath.includes(NODE_MODULES)) {
return false;
}
if (this._whitelist) {
const whitelist = this._whitelist;
const match = whitelist.exec(filePath);
const matchEndIndex = whitelist.lastIndex;
whitelist.lastIndex = 0;
if (!match) {
return true;
}
const filePathInPackage = filePath.substr(matchEndIndex);
return filePathInPackage.startsWith(NODE_MODULES);
}
return true;
}
_createEmptyMap() {
// $FlowFixMe
return {
clocks: Object.create(null),
duplicates: Object.create(null),
files: Object.create(null),
map: Object.create(null),
mocks: Object.create(null)
};
}
}
const copy = object => Object.assign(Object.create(null), object);
HasteMap.H = (_constants || _load_constants()).default;
HasteMap.ModuleMap = (_module_map || _load_module_map()).default;
module.exports = HasteMap;

View File

@@ -0,0 +1,36 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = extractRequires;
/**
* Copyright (c) 2014-present, Facebook, Inc. 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 blockCommentRe = /\/\*[^]*?\*\//g;
const lineCommentRe = /\/\/.*/g;
const replacePatterns = {
EXPORT_RE: /(\bexport\s+(?!type )(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g,
IMPORT_RE: /(\bimport\s+(?!type )(?:[^'"]+\s+from\s+)??)(['"])([^'"]+)(\2)/g,
REQUIRE_EXTENSIONS_PATTERN: /(?:^|[^.]\s*)(\b(?:require\s*?\.\s*?(?:requireActual|requireMock)|jest\s*?\.\s*?(?:requireActual|requireMock|genMockFromModule))\s*?\(\s*?)([`'"])([^`'"]+)(\2\s*?\))/g,
REQUIRE_RE: /(?:^|[^.]\s*)(\brequire\s*?\(\s*?)([`'"])([^`'"]+)(\2\s*?\))/g
};
function extractRequires(code) {
const dependencies = new Set();
const addDependency = (match, pre, quot, dep, post) => {
dependencies.add(dep);
return match;
};
code.replace(blockCommentRe, '').replace(lineCommentRe, '').replace(replacePatterns.EXPORT_RE, addDependency).replace(replacePatterns.IMPORT_RE, addDependency).replace(replacePatterns.REQUIRE_EXTENSIONS_PATTERN, addDependency).replace(replacePatterns.REQUIRE_RE, addDependency);
return Array.from(dependencies);
}

View File

@@ -0,0 +1,37 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = getPlatformExtension;
/**
* Copyright (c) 2014-present, Facebook, Inc. 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 = {
android: true,
ios: true,
native: true,
web: true
};
// 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[platform] ? platform : null;
}

View File

@@ -0,0 +1,24 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
/**
* Copyright (c) 2014-present, Facebook, Inc. 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 path = require('path');
let normalizePathSep;
if (path.sep === '/') {
normalizePathSep = filePath => filePath;
} else {
normalizePathSep = filePath => filePath.replace(/\//g, path.sep);
}
exports.default = normalizePathSep;

View File

@@ -0,0 +1,339 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = WatchmanWatcher;
var _fs;
function _load_fs() {
return _fs = _interopRequireDefault(require('fs'));
}
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _assert;
function _load_assert() {
return _assert = _interopRequireDefault(require('assert'));
}
var _common;
function _load_common() {
return _common = _interopRequireDefault(require('sane/src/common'));
}
var _fbWatchman;
function _load_fbWatchman() {
return _fbWatchman = _interopRequireDefault(require('fb-watchman'));
}
var _events;
function _load_events() {
return _events = require('events');
}
var _recrawlWarningDedupe;
function _load_recrawlWarningDedupe() {
return _recrawlWarningDedupe = _interopRequireDefault(require('sane/src/utils/recrawl-warning-dedupe'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const CHANGE_EVENT = (_common || _load_common()).default.CHANGE_EVENT; /**
* Copyright (c) 2014-present, Facebook, Inc. 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 DELETE_EVENT = (_common || _load_common()).default.DELETE_EVENT;
const ADD_EVENT = (_common || _load_common()).default.ADD_EVENT;
const ALL_EVENT = (_common || _load_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 || _load_common()).default.assignOptions(this, opts);
this.root = (_path || _load_path()).default.resolve(dir);
this.init();
}
// eslint-disable-next-line no-proto
WatchmanWatcher.prototype.__proto__ = (_events || _load_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 || _load_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 || _load_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 || _load_path()).default.join(this.watchProjectInfo.root, this.watchProjectInfo.relativePath, relativePath);
} else {
absPath = (_path || _load_path()).default.join(this.root, changeDescriptor.name);
relativePath = changeDescriptor.name;
}
if (!(self.capabilities.wildmatch && !this.hasIgnore) && !(_common || _load_common()).default.isFileIncluded(this.globs, this.dot, this.doIgnore, relativePath)) {
return;
}
if (!changeDescriptor.exists) {
self.emitEvent(DELETE_EVENT, relativePath, self.root);
} else {
(_fs || _load_fs()).default.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 || _load_recrawlWarningDedupe()).default.isRecrawlWarningDupe(resp.warning)) {
return true;
}
console.warn(resp.warning);
return true;
} else {
return false;
}
}

128
node_modules/jest-haste-map/build/module_map.js generated vendored Normal file
View File

@@ -0,0 +1,128 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _constants;
function _load_constants() {
return _constants = _interopRequireDefault(require('./constants'));
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const EMPTY_MAP = {}; /**
* Copyright (c) 2014-present, Facebook, Inc. 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.
*
*
*/
class ModuleMap {
constructor(raw) {
this._raw = raw;
}
getModule(name, platform, supportsNativePlatform, type) {
if (!type) {
type = (_constants || _load_constants()).default.MODULE;
}
const module = this._getModuleMetadata(name, platform, !!supportsNativePlatform);
if (module && module[(_constants || _load_constants()).default.TYPE] === type) {
return module[(_constants || _load_constants()).default.PATH];
}
return null;
}
getPackage(name, platform, supportsNativePlatform) {
return this.getModule(name, platform, null, (_constants || _load_constants()).default.PACKAGE);
}
getMockModule(name) {
return this._raw.mocks[name];
}
getRawModuleMap() {
return {
duplicates: this._raw.duplicates,
map: this._raw.map,
mocks: this._raw.mocks
};
}
/**
* 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[name] || EMPTY_MAP;
const dupMap = this._raw.duplicates[name] || EMPTY_MAP;
if (platform != null) {
this._assertNoDuplicates(name, platform, supportsNativePlatform, dupMap[platform]);
if (map[platform] != null) {
return map[platform];
}
}
if (supportsNativePlatform) {
this._assertNoDuplicates(name, (_constants || _load_constants()).default.NATIVE_PLATFORM, supportsNativePlatform, dupMap[(_constants || _load_constants()).default.NATIVE_PLATFORM]);
if (map[(_constants || _load_constants()).default.NATIVE_PLATFORM]) {
return map[(_constants || _load_constants()).default.NATIVE_PLATFORM];
}
}
this._assertNoDuplicates(name, (_constants || _load_constants()).default.GENERIC_PLATFORM, supportsNativePlatform, dupMap[(_constants || _load_constants()).default.GENERIC_PLATFORM]);
if (map[(_constants || _load_constants()).default.GENERIC_PLATFORM]) {
return map[(_constants || _load_constants()).default.GENERIC_PLATFORM];
}
return null;
}
_assertNoDuplicates(name, platform, supportsNativePlatform, set) {
if (set == null) {
return;
}
throw new DuplicateHasteCandidatesError(name, platform, supportsNativePlatform, set);
}
}
exports.default = ModuleMap;
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 blacklist files until there remains only one of these:\n\n` + Object.keys(duplicatesSet).sort().map(dupFilePath => {
const typeMessage = getTypeMessage(duplicatesSet[dupFilePath]);
return ` * \`${dupFilePath}\` (${typeMessage})\n`;
}).join(''));
this.hasteName = name;
this.platform = platform;
this.supportsNativePlatform = supportsNativePlatform;
this.duplicatesSet = duplicatesSet;
}
}
function getPlatformMessage(platform) {
if (platform === (_constants || _load_constants()).default.GENERIC_PLATFORM) {
return 'The platform is generic (no extension).';
}
return `The platform extension is \`${platform}\`.`;
}
function getTypeMessage(type) {
switch (type) {
case (_constants || _load_constants()).default.MODULE:
return 'module';
case (_constants || _load_constants()).default.PACKAGE:
return 'package';
}
return 'unknown';
}
ModuleMap.DuplicateHasteCandidatesError = DuplicateHasteCandidatesError;

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

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

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

@@ -0,0 +1,112 @@
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.worker = undefined;
let worker = exports.worker = (() => {
var _ref = _asyncToGenerator(function* (data) {
if (data.hasteImplModulePath && data.hasteImplModulePath !== hasteImplModulePath) {
if (hasteImpl) {
throw new Error('jest-haste-map: hasteImplModulePath changed');
}
hasteImplModulePath = data.hasteImplModulePath;
// $FlowFixMe: dynamic require
hasteImpl = require(hasteImplModulePath);
}
const filePath = data.filePath;
let module;
let id;
let dependencies;
if (filePath.endsWith(PACKAGE_JSON)) {
const fileData = JSON.parse((_gracefulFs || _load_gracefulFs()).default.readFileSync(filePath, 'utf8'));
if (fileData.name) {
id = fileData.name;
module = [filePath, (_constants || _load_constants()).default.PACKAGE];
}
return { dependencies, id, module };
}
if (!(_blacklist || _load_blacklist()).default.has(filePath.substr(filePath.lastIndexOf('.')))) {
const content = (_gracefulFs || _load_gracefulFs()).default.readFileSync(filePath, 'utf8');
if (hasteImpl) {
id = hasteImpl.getHasteName(filePath);
} else {
const doc = (_jestDocblock || _load_jestDocblock()).parse((_jestDocblock || _load_jestDocblock()).extract(content));
id = [].concat(doc.providesModule || doc.provides)[0];
}
dependencies = (0, (_extract_requires || _load_extract_requires()).default)(content);
if (id) {
module = [filePath, (_constants || _load_constants()).default.MODULE];
}
}
return { dependencies, id, module };
});
return function worker(_x) {
return _ref.apply(this, arguments);
};
})();
var _path;
function _load_path() {
return _path = _interopRequireDefault(require('path'));
}
var _jestDocblock;
function _load_jestDocblock() {
return _jestDocblock = _interopRequireWildcard(require('jest-docblock'));
}
var _gracefulFs;
function _load_gracefulFs() {
return _gracefulFs = _interopRequireDefault(require('graceful-fs'));
}
var _blacklist;
function _load_blacklist() {
return _blacklist = _interopRequireDefault(require('./blacklist'));
}
var _constants;
function _load_constants() {
return _constants = _interopRequireDefault(require('./constants'));
}
var _extract_requires;
function _load_extract_requires() {
return _extract_requires = _interopRequireDefault(require('./lib/extract_requires'));
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } /**
* Copyright (c) 2014-present, Facebook, Inc. 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 || _load_path()).default.sep + 'package.json';
let hasteImpl = null;
let hasteImplModulePath = null;