UNPKG

30.4 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
14 if (k2 === undefined) k2 = k;
15 var desc = Object.getOwnPropertyDescriptor(m, k);
16 if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
17 desc = { enumerable: true, get: function() { return m[k]; } };
18 }
19 Object.defineProperty(o, k2, desc);
20}) : (function(o, m, k, k2) {
21 if (k2 === undefined) k2 = k;
22 o[k2] = m[k];
23}));
24var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
25 Object.defineProperty(o, "default", { enumerable: true, value: v });
26}) : function(o, v) {
27 o["default"] = v;
28});
29var __importStar = (this && this.__importStar) || function (mod) {
30 if (mod && mod.__esModule) return mod;
31 var result = {};
32 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
33 __setModuleDefault(result, mod);
34 return result;
35};
36var __values = (this && this.__values) || function(o) {
37 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
38 if (m) return m.call(o);
39 if (o && typeof o.length === "number") return {
40 next: function () {
41 if (o && i >= o.length) o = void 0;
42 return { value: o && o[i++], done: !o };
43 }
44 };
45 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
46};
47var __read = (this && this.__read) || function (o, n) {
48 var m = typeof Symbol === "function" && o[Symbol.iterator];
49 if (!m) return o;
50 var i = m.call(o), r, ar = [], e;
51 try {
52 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
53 }
54 catch (error) { e = { error: error }; }
55 finally {
56 try {
57 if (r && !r.done && (m = i["return"])) m.call(i);
58 }
59 finally { if (e) throw e.error; }
60 }
61 return ar;
62};
63var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
64 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
65 if (ar || !(i in from)) {
66 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
67 ar[i] = from[i];
68 }
69 }
70 return to.concat(ar || Array.prototype.slice.call(from));
71};
72var __importDefault = (this && this.__importDefault) || function (mod) {
73 return (mod && mod.__esModule) ? mod : { "default": mod };
74};
75Object.defineProperty(exports, "__esModule", { value: true });
76exports.ConfigSet = exports.TS_JEST_OUT_DIR = exports.IGNORE_DIAGNOSTIC_CODES = exports.MY_DIGEST = void 0;
77/**
78 * This is the core of settings and so ts-jest.
79 * Since configuration are used to create a good cache key, everything
80 * depending on it is here. Fast jest relies on correct cache keys
81 * depending on all settings that could affect the generated output.
82 *
83 * The big issue is that jest calls first `getCacheKey()` with stringified
84 * version of the `jest.ProjectConfig`, and then later it calls `process()`
85 * with the complete, object version of it.
86 */
87var fs_1 = require("fs");
88var module_1 = __importDefault(require("module"));
89var path_1 = require("path");
90var bs_logger_1 = require("bs-logger");
91var jest_util_1 = require("jest-util");
92var json5_1 = __importDefault(require("json5"));
93var constants_1 = require("../../constants");
94var hoistJestTransformer = __importStar(require("../../transformers/hoist-jest"));
95var utils_1 = require("../../utils");
96var backports_1 = require("../../utils/backports");
97var importer_1 = require("../../utils/importer");
98var messages_1 = require("../../utils/messages");
99var normalize_slashes_1 = require("../../utils/normalize-slashes");
100var sha1_1 = require("../../utils/sha1");
101var ts_error_1 = require("../../utils/ts-error");
102/**
103 * @internal
104 */
105exports.MY_DIGEST = (0, fs_1.readFileSync)((0, path_1.resolve)(__dirname, '../../../.ts-jest-digest'), 'utf8');
106/**
107 * @internal
108 */
109exports.IGNORE_DIAGNOSTIC_CODES = [
110 6059,
111 18002,
112 18003, // "No inputs were found in config file."
113];
114/**
115 * @internal
116 */
117exports.TS_JEST_OUT_DIR = '$$ts-jest$$';
118var normalizeRegex = function (pattern) {
119 return pattern ? (typeof pattern === 'string' ? pattern : pattern.source) : undefined;
120};
121var toDiagnosticCode = function (code) { var _a; return code ? (_a = parseInt("".concat(code).trim().replace(/^TS/, ''), 10)) !== null && _a !== void 0 ? _a : undefined : undefined; };
122var toDiagnosticCodeList = function (items, into) {
123 var e_1, _a;
124 if (into === void 0) { into = []; }
125 try {
126 for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
127 var item = items_1_1.value;
128 if (typeof item === 'string') {
129 var children = item.trim().split(/\s*,\s*/g);
130 if (children.length > 1) {
131 toDiagnosticCodeList(children, into);
132 continue;
133 }
134 item = children[0];
135 }
136 if (!item)
137 continue;
138 var code = toDiagnosticCode(item);
139 if (code && !into.includes(code))
140 into.push(code);
141 }
142 }
143 catch (e_1_1) { e_1 = { error: e_1_1 }; }
144 finally {
145 try {
146 if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
147 }
148 finally { if (e_1) throw e_1.error; }
149 }
150 return into;
151};
152var requireFromString = function (code, fileName) {
153 // @ts-expect-error `_nodeModulePaths` is not exposed in typing
154 var paths = module_1.default._nodeModulePaths((0, path_1.dirname)(fileName));
155 var parent = module.parent;
156 var m = new module_1.default(fileName, parent);
157 m.filename = fileName;
158 m.paths = [].concat(paths);
159 // @ts-expect-error `_compile` is not exposed in typing
160 m._compile(code, fileName);
161 var exports = m.exports;
162 parent && parent.children && parent.children.splice(parent.children.indexOf(m), 1);
163 return exports;
164};
165var ConfigSet = /** @class */ (function () {
166 function ConfigSet(jestConfig, parentLogger) {
167 var _a, _b;
168 var _c, _d, _e, _f;
169 this.parentLogger = parentLogger;
170 /**
171 * Use by e2e, don't mark as internal
172 */
173 this.tsJestDigest = exports.MY_DIGEST;
174 this.resolvedTransformers = {
175 before: [],
176 after: [],
177 afterDeclarations: [],
178 };
179 this.useESM = false;
180 /**
181 * @internal
182 */
183 this._overriddenCompilerOptions = {
184 inlineSourceMap: false,
185 // we don't want to create declaration files
186 declaration: false,
187 noEmit: false,
188 // else istanbul related will be dropped
189 removeComments: false,
190 // to clear out else it's buggy
191 out: undefined,
192 outFile: undefined,
193 composite: undefined,
194 declarationDir: undefined,
195 declarationMap: undefined,
196 emitDeclarationOnly: undefined,
197 sourceRoot: undefined,
198 tsBuildInfoFile: undefined,
199 };
200 this.logger = this.parentLogger
201 ? this.parentLogger.child((_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'config', _a))
202 : utils_1.rootLogger.child({ namespace: 'config' });
203 this._backportJestCfg(jestConfig !== null && jestConfig !== void 0 ? jestConfig : Object.create(null));
204 this.cwd = (0, path_1.normalize)((_c = this._jestCfg.cwd) !== null && _c !== void 0 ? _c : process.cwd());
205 this.rootDir = (0, path_1.normalize)((_d = this._jestCfg.rootDir) !== null && _d !== void 0 ? _d : this.cwd);
206 var tsJestCfg = this._jestCfg.globals && this._jestCfg.globals['ts-jest'];
207 var options = tsJestCfg !== null && tsJestCfg !== void 0 ? tsJestCfg : Object.create(null);
208 // compiler module
209 this.compilerModule = importer_1.importer.typescript("Using \"ts-jest\" requires this package to be installed." /* ImportReasons.TsJest */, (_e = options.compiler) !== null && _e !== void 0 ? _e : 'typescript');
210 // isolatedModules
211 this.isolatedModules = (_f = options.isolatedModules) !== null && _f !== void 0 ? _f : false;
212 this.logger.debug({ compilerModule: this.compilerModule }, 'normalized compiler module config via ts-jest option');
213 this._setupConfigSet(options);
214 this._resolveTsCacheDir();
215 this._matchablePatterns = __spreadArray(__spreadArray([], __read(this._jestCfg.testMatch), false), __read(this._jestCfg.testRegex), false).filter(function (pattern) {
216 /**
217 * jest config testRegex doesn't always deliver the correct RegExp object
218 * See https://github.com/facebook/jest/issues/9778
219 */
220 return pattern instanceof RegExp || typeof pattern === 'string';
221 });
222 if (!this._matchablePatterns.length) {
223 (_b = this._matchablePatterns).push.apply(_b, __spreadArray([], __read(constants_1.DEFAULT_JEST_TEST_MATCH), false));
224 }
225 this._matchTestFilePath = (0, jest_util_1.globsToMatcher)(this._matchablePatterns.filter(function (pattern) { return typeof pattern === 'string'; }));
226 }
227 /**
228 * @internal
229 */
230 ConfigSet.prototype._backportJestCfg = function (jestCfg) {
231 var _a, _b;
232 var config = (0, backports_1.backportJestConfig)(this.logger, jestCfg);
233 this.logger.debug({ jestConfig: config }, 'normalized jest config');
234 this._jestCfg = __assign(__assign({}, config), { testMatch: (_a = config.testMatch) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_JEST_TEST_MATCH, testRegex: (_b = config.testRegex) !== null && _b !== void 0 ? _b : [] });
235 };
236 /**
237 * @internal
238 */
239 ConfigSet.prototype._setupConfigSet = function (options) {
240 var _this = this;
241 var _a, _b, _c, _d, _e;
242 // useESM
243 this.useESM = (_a = options.useESM) !== null && _a !== void 0 ? _a : false;
244 // babel config (for babel-jest) default is undefined so we don't need to have fallback like tsConfig
245 if (!options.babelConfig) {
246 this.logger.debug('babel is disabled');
247 }
248 else {
249 var baseBabelCfg = { cwd: this.cwd };
250 if (typeof options.babelConfig === 'string') {
251 var babelCfgPath = this.resolvePath(options.babelConfig);
252 var babelFileExtName = (0, path_1.extname)(options.babelConfig);
253 if (babelFileExtName === '.js' || babelFileExtName === '.cjs') {
254 this.babelConfig = __assign(__assign({}, baseBabelCfg), require(babelCfgPath));
255 }
256 else {
257 this.babelConfig = __assign(__assign({}, baseBabelCfg), json5_1.default.parse((0, fs_1.readFileSync)(babelCfgPath, 'utf-8')));
258 }
259 }
260 else if (typeof options.babelConfig === 'object') {
261 this.babelConfig = __assign(__assign({}, baseBabelCfg), options.babelConfig);
262 }
263 else {
264 this.babelConfig = baseBabelCfg;
265 }
266 this.logger.debug({ babelConfig: this.babelConfig }, 'normalized babel config via ts-jest option');
267 this.babelJestTransformer = importer_1.importer
268 .babelJest("Using \"babel-jest\" requires this package to be installed." /* ImportReasons.BabelJest */)
269 .createTransformer(this.babelConfig);
270 this.logger.debug('created babel-jest transformer');
271 }
272 // diagnostics
273 var diagnosticsOpt = (_b = options.diagnostics) !== null && _b !== void 0 ? _b : true;
274 var ignoreList = __spreadArray([], __read(exports.IGNORE_DIAGNOSTIC_CODES), false);
275 if (typeof diagnosticsOpt === 'object') {
276 var ignoreCodes = diagnosticsOpt.ignoreCodes;
277 if (ignoreCodes) {
278 Array.isArray(ignoreCodes) ? ignoreList.push.apply(ignoreList, __spreadArray([], __read(ignoreCodes), false)) : ignoreList.push(ignoreCodes);
279 }
280 this._diagnostics = {
281 pretty: (_c = diagnosticsOpt.pretty) !== null && _c !== void 0 ? _c : true,
282 exclude: (_d = diagnosticsOpt.exclude) !== null && _d !== void 0 ? _d : [],
283 ignoreCodes: toDiagnosticCodeList(ignoreList),
284 throws: !diagnosticsOpt.warnOnly,
285 };
286 }
287 else {
288 this._diagnostics = {
289 ignoreCodes: diagnosticsOpt ? toDiagnosticCodeList(ignoreList) : [],
290 exclude: [],
291 pretty: true,
292 throws: diagnosticsOpt,
293 };
294 }
295 if (diagnosticsOpt) {
296 this._shouldIgnoreDiagnosticsForFile = this._diagnostics.exclude.length
297 ? (0, jest_util_1.globsToMatcher)(this._diagnostics.exclude)
298 : function () { return false; };
299 }
300 else {
301 this._shouldIgnoreDiagnosticsForFile = function () { return true; };
302 }
303 this.logger.debug({ diagnostics: this._diagnostics }, 'normalized diagnostics config via ts-jest option');
304 // tsconfig
305 var tsconfigOpt = options.tsconfig;
306 var configFilePath = typeof tsconfigOpt === 'string' ? this.resolvePath(tsconfigOpt) : undefined;
307 this.parsedTsConfig = this._getAndResolveTsConfig(typeof tsconfigOpt === 'object' ? tsconfigOpt : undefined, configFilePath);
308 // throw errors if any matching wanted diagnostics
309 this.raiseDiagnostics(this.parsedTsConfig.errors, configFilePath);
310 this.logger.debug({ tsconfig: this.parsedTsConfig }, 'normalized typescript config via ts-jest option');
311 // transformers
312 this.resolvedTransformers.before = [
313 {
314 factory: hoistJestTransformer.factory,
315 name: hoistJestTransformer.name,
316 version: hoistJestTransformer.version,
317 },
318 ];
319 var astTransformers = options.astTransformers;
320 if (astTransformers) {
321 var resolveTransformerFunc_1 = function (transformerPath) {
322 var transformerFunc;
323 if ((0, path_1.extname)(transformerPath) === '.ts') {
324 var compiledTransformer = importer_1.importer
325 .esBuild("Using \"esbuild\" requires this package to be installed." /* ImportReasons.EsBuild */)
326 .transformSync((0, fs_1.readFileSync)(transformerPath, 'utf-8'), {
327 loader: 'ts',
328 format: 'cjs',
329 target: 'es2015',
330 }).code;
331 transformerFunc = requireFromString(compiledTransformer, transformerPath.replace('.ts', '.js'));
332 }
333 else {
334 transformerFunc = require(transformerPath);
335 }
336 if (!transformerFunc.version) {
337 _this.logger.warn("The AST transformer {{file}} must have an `export const version = <your_transformer_version>`" /* Errors.MissingTransformerVersion */, { file: transformerPath });
338 }
339 if (!transformerFunc.name) {
340 _this.logger.warn("The AST transformer {{file}} must have an `export const name = <your_transformer_name>`" /* Errors.MissingTransformerName */, { file: transformerPath });
341 }
342 return transformerFunc;
343 };
344 var resolveTransformers = function (transformers) {
345 return transformers.map(function (transformer) {
346 if (typeof transformer === 'string') {
347 return resolveTransformerFunc_1(_this.resolvePath(transformer, { nodeResolve: true }));
348 }
349 else {
350 return __assign(__assign({}, resolveTransformerFunc_1(_this.resolvePath(transformer.path, { nodeResolve: true }))), { options: transformer.options });
351 }
352 });
353 };
354 if (astTransformers.before) {
355 /* istanbul ignore next (already covered in unit test) */
356 (_e = this.resolvedTransformers.before) === null || _e === void 0 ? void 0 : _e.push.apply(_e, __spreadArray([], __read(resolveTransformers(astTransformers.before)), false));
357 }
358 if (astTransformers.after) {
359 this.resolvedTransformers = __assign(__assign({}, this.resolvedTransformers), { after: resolveTransformers(astTransformers.after) });
360 }
361 if (astTransformers.afterDeclarations) {
362 this.resolvedTransformers = __assign(__assign({}, this.resolvedTransformers), { afterDeclarations: resolveTransformers(astTransformers.afterDeclarations) });
363 }
364 }
365 this.logger.debug({ customTransformers: this.resolvedTransformers }, 'normalized custom AST transformers via ts-jest option');
366 // stringifyContentPathRegex
367 if (options.stringifyContentPathRegex) {
368 this._stringifyContentRegExp =
369 typeof options.stringifyContentPathRegex === 'string'
370 ? new RegExp(normalizeRegex(options.stringifyContentPathRegex)) // eslint-disable-line @typescript-eslint/no-non-null-assertion
371 : options.stringifyContentPathRegex;
372 this.logger.debug({ stringifyContentPathRegex: this._stringifyContentRegExp }, 'normalized stringifyContentPathRegex config via ts-jest option');
373 }
374 };
375 /**
376 * @internal
377 */
378 ConfigSet.prototype._resolveTsCacheDir = function () {
379 this.cacheSuffix = (0, sha1_1.sha1)((0, utils_1.stringify)({
380 version: this.compilerModule.version,
381 digest: this.tsJestDigest,
382 babelConfig: this.babelConfig,
383 tsconfig: {
384 options: this.parsedTsConfig.options,
385 raw: this.parsedTsConfig.raw,
386 },
387 isolatedModules: this.isolatedModules,
388 diagnostics: this._diagnostics,
389 transformers: Object.values(this.resolvedTransformers)
390 .reduce(function (prevVal, currentVal) { return __spreadArray(__spreadArray([], __read(prevVal), false), [currentVal], false); })
391 .map(function (transformer) { return "".concat(transformer.name, "-").concat(transformer.version); }),
392 }));
393 if (!this._jestCfg.cache) {
394 this.logger.debug('file caching disabled');
395 }
396 else {
397 var res = (0, path_1.join)(this._jestCfg.cacheDirectory, 'ts-jest', this.cacheSuffix.substr(0, 2), this.cacheSuffix.substr(2));
398 this.logger.debug({ cacheDirectory: res }, 'will use file caching');
399 this.tsCacheDir = res;
400 }
401 };
402 /**
403 * @internal
404 */
405 ConfigSet.prototype._getAndResolveTsConfig = function (compilerOptions, resolvedConfigFile) {
406 var e_2, _a, _b;
407 var _c, _d, _e;
408 var result = this._resolveTsConfig(compilerOptions, resolvedConfigFile);
409 var forcedOptions = this._overriddenCompilerOptions;
410 var finalOptions = result.options;
411 // Target ES2015 output by default (instead of ES3).
412 if (finalOptions.target === undefined) {
413 finalOptions.target = this.compilerModule.ScriptTarget.ES2015;
414 }
415 // check the module interoperability
416 var target = finalOptions.target;
417 // compute the default if not set
418 var defaultModule = [this.compilerModule.ScriptTarget.ES3, this.compilerModule.ScriptTarget.ES5].includes(target)
419 ? this.compilerModule.ModuleKind.CommonJS
420 : this.compilerModule.ModuleKind.ESNext;
421 var moduleValue = (_c = finalOptions.module) !== null && _c !== void 0 ? _c : defaultModule;
422 if (!this.babelConfig &&
423 moduleValue !== this.compilerModule.ModuleKind.CommonJS &&
424 !(finalOptions.esModuleInterop || finalOptions.allowSyntheticDefaultImports)) {
425 result.errors.push({
426 code: 151001 /* DiagnosticCodes.ConfigModuleOption */,
427 messageText: "If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information." /* Errors.ConfigNoModuleInterop */,
428 category: this.compilerModule.DiagnosticCategory.Message,
429 file: undefined,
430 start: undefined,
431 length: undefined,
432 });
433 // at least enable synthetic default imports (except if it's set in the input config)
434 /* istanbul ignore next (already covered in unit test) */
435 if (!('allowSyntheticDefaultImports' in finalOptions)) {
436 finalOptions.allowSyntheticDefaultImports = true;
437 }
438 }
439 // Make sure when allowJs is enabled, outDir is required to have when using allowJs: true
440 if (finalOptions.allowJs && !finalOptions.outDir) {
441 finalOptions.outDir = exports.TS_JEST_OUT_DIR;
442 }
443 try {
444 // ensure undefined are removed and other values are overridden
445 for (var _f = __values(Object.keys(forcedOptions)), _g = _f.next(); !_g.done; _g = _f.next()) {
446 var key = _g.value;
447 var val = forcedOptions[key];
448 if (val === undefined) {
449 delete finalOptions[key];
450 }
451 else {
452 finalOptions[key] = val;
453 }
454 }
455 }
456 catch (e_2_1) { e_2 = { error: e_2_1 }; }
457 finally {
458 try {
459 if (_g && !_g.done && (_a = _f.return)) _a.call(_f);
460 }
461 finally { if (e_2) throw e_2.error; }
462 }
463 /**
464 * See https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping
465 * Every time this page is updated, we also need to update here. Here we only show warning message for Node LTS versions
466 */
467 var nodeJsVer = process.version;
468 var compilationTarget = result.options.target;
469 var TARGET_TO_VERSION_MAPPING = (_b = {},
470 _b[this.compilerModule.ScriptTarget.ES2018] = 'es2018',
471 _b[this.compilerModule.ScriptTarget.ES2019] = 'es2019',
472 _b[this.compilerModule.ScriptTarget.ES2020] = 'es2020',
473 _b[this.compilerModule.ScriptTarget.ESNext] = 'ESNext',
474 _b);
475 /* istanbul ignore next (cover by e2e) */
476 if (compilationTarget &&
477 !this.babelConfig &&
478 nodeJsVer.startsWith('v12') &&
479 compilationTarget > this.compilerModule.ScriptTarget.ES2019) {
480 var message = (0, messages_1.interpolate)("There is a mismatch between your NodeJs version {{nodeJsVer}} and your TypeScript target {{compilationTarget}}. This might lead to some unexpected errors when running tests with `ts-jest`. To fix this, you can check https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping" /* Errors.MismatchNodeTargetMapping */, {
481 nodeJsVer: process.version,
482 compilationTarget: TARGET_TO_VERSION_MAPPING[compilationTarget],
483 });
484 this.logger.warn(message);
485 }
486 var resultOptions = result.options;
487 var sourceMap = (_d = resultOptions.sourceMap) !== null && _d !== void 0 ? _d : true;
488 return __assign(__assign({}, result), { options: __assign(__assign({}, resultOptions), { sourceMap: sourceMap, inlineSources: sourceMap, module: (_e = resultOptions.module) !== null && _e !== void 0 ? _e : this.compilerModule.ModuleKind.CommonJS }) });
489 };
490 // eslint-disable-next-line no-dupe-class-members
491 ConfigSet.prototype._resolveTsConfig = function (compilerOptions, resolvedConfigFile) {
492 var config = { compilerOptions: Object.create(null) };
493 var basePath = (0, normalize_slashes_1.normalizeSlashes)(this.rootDir);
494 var ts = this.compilerModule;
495 // Read project configuration when available.
496 var configFileName = resolvedConfigFile
497 ? (0, normalize_slashes_1.normalizeSlashes)(resolvedConfigFile)
498 : ts.findConfigFile((0, normalize_slashes_1.normalizeSlashes)(this.rootDir), ts.sys.fileExists);
499 if (configFileName) {
500 this.logger.debug({ tsConfigFileName: configFileName }, 'readTsConfig(): reading', configFileName);
501 var result = ts.readConfigFile(configFileName, ts.sys.readFile);
502 // Return diagnostics.
503 if (result.error) {
504 return { errors: [result.error], fileNames: [], options: {} };
505 }
506 config = result.config;
507 basePath = (0, normalize_slashes_1.normalizeSlashes)((0, path_1.dirname)(configFileName));
508 }
509 // Override default configuration options `ts-jest` requires.
510 config.compilerOptions = __assign(__assign({}, config.compilerOptions), compilerOptions);
511 // parse json, merge config extending others, ...
512 return ts.parseJsonConfigFileContent(config, ts.sys, basePath, undefined, configFileName);
513 };
514 ConfigSet.prototype.isTestFile = function (fileName) {
515 var _this = this;
516 return this._matchablePatterns.some(function (pattern) {
517 return typeof pattern === 'string' ? _this._matchTestFilePath(fileName) : pattern.test(fileName);
518 });
519 };
520 ConfigSet.prototype.shouldStringifyContent = function (filePath) {
521 return this._stringifyContentRegExp ? this._stringifyContentRegExp.test(filePath) : false;
522 };
523 ConfigSet.prototype.raiseDiagnostics = function (diagnostics, filePath, logger) {
524 var _this = this;
525 var ignoreCodes = this._diagnostics.ignoreCodes;
526 var DiagnosticCategory = this.compilerModule.DiagnosticCategory;
527 var filteredDiagnostics = filePath && !this.shouldReportDiagnostics(filePath)
528 ? []
529 : diagnostics.filter(function (diagnostic) {
530 var _a;
531 if (((_a = diagnostic.file) === null || _a === void 0 ? void 0 : _a.fileName) && !_this.shouldReportDiagnostics(diagnostic.file.fileName)) {
532 return false;
533 }
534 return !ignoreCodes.includes(diagnostic.code);
535 });
536 if (!filteredDiagnostics.length)
537 return;
538 var error = this.createTsError(filteredDiagnostics);
539 // only throw if `warnOnly` and it is a warning or error
540 var importantCategories = [DiagnosticCategory.Warning, DiagnosticCategory.Error];
541 if (this._diagnostics.throws && filteredDiagnostics.some(function (d) { return importantCategories.includes(d.category); })) {
542 throw error;
543 }
544 /* istanbul ignore next (already covered) */
545 logger ? logger.warn({ error: error }, error.message) : this.logger.warn({ error: error }, error.message);
546 };
547 ConfigSet.prototype.shouldReportDiagnostics = function (filePath) {
548 var fileExtension = (0, path_1.extname)(filePath);
549 return constants_1.JS_JSX_EXTENSIONS.includes(fileExtension)
550 ? this.parsedTsConfig.options.checkJs && !this._shouldIgnoreDiagnosticsForFile(filePath)
551 : !this._shouldIgnoreDiagnosticsForFile(filePath);
552 };
553 /**
554 * @internal
555 */
556 ConfigSet.prototype.createTsError = function (diagnostics) {
557 var _this = this;
558 var formatDiagnostics = this._diagnostics.pretty
559 ? this.compilerModule.formatDiagnosticsWithColorAndContext
560 : this.compilerModule.formatDiagnostics;
561 /* istanbul ignore next (not possible to cover) */
562 var diagnosticHost = {
563 getNewLine: function () { return '\n'; },
564 getCurrentDirectory: function () { return _this.cwd; },
565 getCanonicalFileName: function (path) { return path; },
566 };
567 var diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
568 var diagnosticCodes = diagnostics.map(function (x) { return x.code; });
569 return new ts_error_1.TSError(diagnosticText, diagnosticCodes);
570 };
571 ConfigSet.prototype.resolvePath = function (inputPath, _a) {
572 var _b = _a === void 0 ? {} : _a, _c = _b.throwIfMissing, throwIfMissing = _c === void 0 ? true : _c, _d = _b.nodeResolve, nodeResolve = _d === void 0 ? false : _d;
573 var path = inputPath;
574 var nodeResolved = false;
575 if (path.startsWith('<rootDir>')) {
576 path = (0, path_1.resolve)((0, path_1.join)(this.rootDir, path.substr(9)));
577 }
578 else if (!(0, path_1.isAbsolute)(path)) {
579 if (!path.startsWith('.') && nodeResolve) {
580 try {
581 path = require.resolve(path);
582 nodeResolved = true;
583 }
584 catch (_) { }
585 }
586 if (!nodeResolved) {
587 path = (0, path_1.resolve)(this.cwd, path);
588 }
589 }
590 if (!nodeResolved && nodeResolve) {
591 try {
592 path = require.resolve(path);
593 nodeResolved = true;
594 }
595 catch (_) { }
596 }
597 if (throwIfMissing && !(0, fs_1.existsSync)(path)) {
598 throw new Error((0, messages_1.interpolate)("File not found: {{inputPath}} (resolved as: {{resolvedPath}})" /* Errors.FileNotFound */, { inputPath: inputPath, resolvedPath: path }));
599 }
600 this.logger.debug({ fromPath: inputPath, toPath: path }, 'resolved path from', inputPath, 'to', path);
601 return path;
602 };
603 return ConfigSet;
604}());
605exports.ConfigSet = ConfigSet;