utils.js
  1  'use strict';
  2  
  3  Object.defineProperty(exports, '__esModule', {
  4    value: true
  5  });
  6  exports.getSequencer = exports.isJSONString = exports.getRunner = exports.getWatchPlugin = exports.getTestEnvironment = exports.resolveWithPrefix = exports._replaceRootDirTags = exports.replaceRootDirInPath = exports.escapeGlobCharacters = exports.resolve = exports.DOCUMENTATION_NOTE = exports.BULLET = void 0;
  7  
  8  function path() {
  9    const data = _interopRequireWildcard(require('path'));
 10  
 11    path = function () {
 12      return data;
 13    };
 14  
 15    return data;
 16  }
 17  
 18  function _chalk() {
 19    const data = _interopRequireDefault(require('chalk'));
 20  
 21    _chalk = function () {
 22      return data;
 23    };
 24  
 25    return data;
 26  }
 27  
 28  function _jestResolve() {
 29    const data = _interopRequireDefault(require('jest-resolve'));
 30  
 31    _jestResolve = function () {
 32      return data;
 33    };
 34  
 35    return data;
 36  }
 37  
 38  function _jestValidate() {
 39    const data = require('jest-validate');
 40  
 41    _jestValidate = function () {
 42      return data;
 43    };
 44  
 45    return data;
 46  }
 47  
 48  function _interopRequireDefault(obj) {
 49    return obj && obj.__esModule ? obj : {default: obj};
 50  }
 51  
 52  function _getRequireWildcardCache() {
 53    if (typeof WeakMap !== 'function') return null;
 54    var cache = new WeakMap();
 55    _getRequireWildcardCache = function () {
 56      return cache;
 57    };
 58    return cache;
 59  }
 60  
 61  function _interopRequireWildcard(obj) {
 62    if (obj && obj.__esModule) {
 63      return obj;
 64    }
 65    if (obj === null || (typeof obj !== 'object' && typeof obj !== 'function')) {
 66      return {default: obj};
 67    }
 68    var cache = _getRequireWildcardCache();
 69    if (cache && cache.has(obj)) {
 70      return cache.get(obj);
 71    }
 72    var newObj = {};
 73    var hasPropertyDescriptor =
 74      Object.defineProperty && Object.getOwnPropertyDescriptor;
 75    for (var key in obj) {
 76      if (Object.prototype.hasOwnProperty.call(obj, key)) {
 77        var desc = hasPropertyDescriptor
 78          ? Object.getOwnPropertyDescriptor(obj, key)
 79          : null;
 80        if (desc && (desc.get || desc.set)) {
 81          Object.defineProperty(newObj, key, desc);
 82        } else {
 83          newObj[key] = obj[key];
 84        }
 85      }
 86    }
 87    newObj.default = obj;
 88    if (cache) {
 89      cache.set(obj, newObj);
 90    }
 91    return newObj;
 92  }
 93  
 94  /**
 95   * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
 96   *
 97   * This source code is licensed under the MIT license found in the
 98   * LICENSE file in the root directory of this source tree.
 99   */
100  const BULLET = _chalk().default.bold('\u25cf ');
101  
102  exports.BULLET = BULLET;
103  const DOCUMENTATION_NOTE = `  ${_chalk().default.bold(
104    'Configuration Documentation:'
105  )}
106    https://jestjs.io/docs/configuration.html
107  `;
108  exports.DOCUMENTATION_NOTE = DOCUMENTATION_NOTE;
109  
110  const createValidationError = message =>
111    new (_jestValidate().ValidationError)(
112      `${BULLET}Validation Error`,
113      message,
114      DOCUMENTATION_NOTE
115    );
116  
117  const resolve = (resolver, {key, filePath, rootDir, optional}) => {
118    const module = _jestResolve().default.findNodeModule(
119      replaceRootDirInPath(rootDir, filePath),
120      {
121        basedir: rootDir,
122        resolver: resolver || undefined
123      }
124    );
125  
126    if (!module && !optional) {
127      throw createValidationError(`  Module ${_chalk().default.bold(
128        filePath
129      )} in the ${_chalk().default.bold(key)} option was not found.
130           ${_chalk().default.bold('<rootDir>')} is: ${rootDir}`);
131    } /// can cast as string since nulls will be thrown
132  
133    return module;
134  };
135  
136  exports.resolve = resolve;
137  
138  const escapeGlobCharacters = path => path.replace(/([()*{}\[\]!?\\])/g, '\\$1');
139  
140  exports.escapeGlobCharacters = escapeGlobCharacters;
141  
142  const replaceRootDirInPath = (rootDir, filePath) => {
143    if (!/^<rootDir>/.test(filePath)) {
144      return filePath;
145    }
146  
147    return path().resolve(
148      rootDir,
149      path().normalize('./' + filePath.substr('<rootDir>'.length))
150    );
151  };
152  
153  exports.replaceRootDirInPath = replaceRootDirInPath;
154  
155  const _replaceRootDirInObject = (rootDir, config) => {
156    const newConfig = {};
157  
158    for (const configKey in config) {
159      newConfig[configKey] =
160        configKey === 'rootDir'
161          ? config[configKey]
162          : _replaceRootDirTags(rootDir, config[configKey]);
163    }
164  
165    return newConfig;
166  };
167  
168  const _replaceRootDirTags = (rootDir, config) => {
169    if (config == null) {
170      return config;
171    }
172  
173    switch (typeof config) {
174      case 'object':
175        if (Array.isArray(config)) {
176          /// can be string[] or {}[]
177          return config.map(item => _replaceRootDirTags(rootDir, item));
178        }
179  
180        if (config instanceof RegExp) {
181          return config;
182        }
183  
184        return _replaceRootDirInObject(rootDir, config);
185  
186      case 'string':
187        return replaceRootDirInPath(rootDir, config);
188    }
189  
190    return config;
191  };
192  
193  exports._replaceRootDirTags = _replaceRootDirTags;
194  
195  const resolveWithPrefix = (
196    resolver,
197    {filePath, humanOptionName, optionName, prefix, rootDir}
198  ) => {
199    const fileName = replaceRootDirInPath(rootDir, filePath);
200  
201    let module = _jestResolve().default.findNodeModule(`${prefix}${fileName}`, {
202      basedir: rootDir,
203      resolver: resolver || undefined
204    });
205  
206    if (module) {
207      return module;
208    }
209  
210    try {
211      return require.resolve(`${prefix}${fileName}`);
212    } catch {}
213  
214    module = _jestResolve().default.findNodeModule(fileName, {
215      basedir: rootDir,
216      resolver: resolver || undefined
217    });
218  
219    if (module) {
220      return module;
221    }
222  
223    try {
224      return require.resolve(fileName);
225    } catch {}
226  
227    throw createValidationError(
228      `  ${humanOptionName} ${_chalk().default.bold(
229        fileName
230      )} cannot be found. Make sure the ${_chalk().default.bold(
231        optionName
232      )} configuration option points to an existing node module.`
233    );
234  };
235  /**
236   * Finds the test environment to use:
237   *
238   * 1. looks for jest-environment-<name> relative to project.
239   * 1. looks for jest-environment-<name> relative to Jest.
240   * 1. looks for <name> relative to project.
241   * 1. looks for <name> relative to Jest.
242   */
243  
244  exports.resolveWithPrefix = resolveWithPrefix;
245  
246  const getTestEnvironment = ({rootDir, testEnvironment: filePath}) =>
247    resolveWithPrefix(undefined, {
248      filePath,
249      humanOptionName: 'Test environment',
250      optionName: 'testEnvironment',
251      prefix: 'jest-environment-',
252      rootDir
253    });
254  /**
255   * Finds the watch plugins to use:
256   *
257   * 1. looks for jest-watch-<name> relative to project.
258   * 1. looks for jest-watch-<name> relative to Jest.
259   * 1. looks for <name> relative to project.
260   * 1. looks for <name> relative to Jest.
261   */
262  
263  exports.getTestEnvironment = getTestEnvironment;
264  
265  const getWatchPlugin = (resolver, {filePath, rootDir}) =>
266    resolveWithPrefix(resolver, {
267      filePath,
268      humanOptionName: 'Watch plugin',
269      optionName: 'watchPlugins',
270      prefix: 'jest-watch-',
271      rootDir
272    });
273  /**
274   * Finds the runner to use:
275   *
276   * 1. looks for jest-runner-<name> relative to project.
277   * 1. looks for jest-runner-<name> relative to Jest.
278   * 1. looks for <name> relative to project.
279   * 1. looks for <name> relative to Jest.
280   */
281  
282  exports.getWatchPlugin = getWatchPlugin;
283  
284  const getRunner = (resolver, {filePath, rootDir}) =>
285    resolveWithPrefix(resolver, {
286      filePath,
287      humanOptionName: 'Jest Runner',
288      optionName: 'runner',
289      prefix: 'jest-runner-',
290      rootDir
291    });
292  
293  exports.getRunner = getRunner;
294  
295  // newtype
296  const isJSONString = text =>
297    text != null &&
298    typeof text === 'string' &&
299    text.startsWith('{') &&
300    text.endsWith('}');
301  
302  exports.isJSONString = isJSONString;
303  
304  const getSequencer = (resolver, {filePath, rootDir}) =>
305    resolveWithPrefix(resolver, {
306      filePath,
307      humanOptionName: 'Jest Sequencer',
308      optionName: 'testSequencer',
309      prefix: 'jest-sequencer-',
310      rootDir
311    });
312  
313  exports.getSequencer = getSequencer;