ts-jest 29.0.1 → 29.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/.ts-jest-digest +1 -1
  2. package/CHANGELOG.md +19 -0
  3. package/dist/cli/config/init.d.ts +5 -0
  4. package/dist/cli/config/init.js +62 -20
  5. package/dist/cli/config/migrate.js +50 -10
  6. package/dist/cli/help.js +7 -1
  7. package/dist/cli/helpers/presets.js +12 -5
  8. package/dist/cli/index.js +9 -5
  9. package/dist/config/paths-to-module-name-mapper.js +6 -2
  10. package/dist/constants.js +5 -0
  11. package/dist/legacy/compiler/compiler-utils.d.ts +6 -0
  12. package/dist/legacy/compiler/compiler-utils.js +10 -0
  13. package/dist/legacy/compiler/ts-compiler.d.ts +6 -0
  14. package/dist/legacy/compiler/ts-compiler.js +76 -7
  15. package/dist/legacy/compiler/ts-jest-compiler.js +2 -1
  16. package/dist/legacy/config/config-set.d.ts +7 -0
  17. package/dist/legacy/config/config-set.js +91 -12
  18. package/dist/legacy/ts-jest-transformer.d.ts +13 -0
  19. package/dist/legacy/ts-jest-transformer.js +57 -10
  20. package/dist/raw-compiler-options.d.ts +297 -0
  21. package/dist/transformers/hoist-jest.d.ts +4 -0
  22. package/dist/transformers/hoist-jest.js +24 -0
  23. package/dist/types.d.ts +101 -6
  24. package/dist/utils/backports.js +13 -4
  25. package/dist/utils/get-package-version.js +3 -0
  26. package/dist/utils/importer.js +31 -4
  27. package/dist/utils/json.js +9 -0
  28. package/dist/utils/jsonable-value.js +2 -1
  29. package/dist/utils/logger.js +1 -0
  30. package/dist/utils/memoize.js +20 -1
  31. package/dist/utils/messages.js +5 -0
  32. package/dist/utils/normalize-slashes.js +3 -0
  33. package/dist/utils/sha1.js +10 -0
  34. package/dist/utils/ts-error.js +12 -2
  35. package/dist/utils/version-checkers.js +9 -5
  36. package/package.json +4 -4
@@ -58,12 +58,15 @@ var constants_1 = require("../../constants");
58
58
  var utils_1 = require("../../utils");
59
59
  var messages_1 = require("../../utils/messages");
60
60
  var compiler_utils_1 = require("./compiler-utils");
61
- var TsCompiler = (function () {
61
+ var TsCompiler = /** @class */ (function () {
62
62
  function TsCompiler(configSet, runtimeCacheFS) {
63
63
  var _a;
64
64
  var _this = this;
65
65
  this.configSet = configSet;
66
66
  this.runtimeCacheFS = runtimeCacheFS;
67
+ /**
68
+ * @internal
69
+ */
67
70
  this._projectVersion = 1;
68
71
  this._ts = configSet.compilerModule;
69
72
  this._logger = utils_1.rootLogger.child({ namespace: 'ts-compiler' });
@@ -80,6 +83,7 @@ var TsCompiler = (function () {
80
83
  },
81
84
  _a[bs_logger_1.LogContexts.logLevel] = bs_logger_1.LogLevels.trace,
82
85
  _a), 'readFile', (0, lodash_memoize_1.default)(this._ts.sys.readFile));
86
+ /* istanbul ignore next */
83
87
  this._moduleResolutionHost = {
84
88
  fileExists: (0, lodash_memoize_1.default)(this._ts.sys.fileExists),
85
89
  readFile: this._cachedReadFile,
@@ -95,6 +99,7 @@ var TsCompiler = (function () {
95
99
  }
96
100
  TsCompiler.prototype.getResolvedModules = function (fileContent, fileName, runtimeCacheFS) {
97
101
  var _this = this;
102
+ // In watch mode, it is possible that the initial cacheFS becomes empty
98
103
  if (!this.runtimeCacheFS.size) {
99
104
  this._runtimeCacheFS = runtimeCacheFS;
100
105
  }
@@ -122,6 +127,7 @@ var TsCompiler = (function () {
122
127
  ![this._ts.ModuleKind.ES2015, this._ts.ModuleKind.ES2020, this._ts.ModuleKind.ESNext].includes(moduleKind))
123
128
  ? this._ts.ModuleKind.ESNext
124
129
  : moduleKind;
130
+ // Make sure `esModuleInterop` and `allowSyntheticDefaultImports` true to support import CJS into ESM
125
131
  esModuleInterop = true;
126
132
  allowSyntheticDefaultImports = true;
127
133
  }
@@ -131,6 +137,7 @@ var TsCompiler = (function () {
131
137
  this._compilerOptions = __assign(__assign({}, this._compilerOptions), { allowSyntheticDefaultImports: allowSyntheticDefaultImports, esModuleInterop: esModuleInterop, module: moduleKind });
132
138
  if (this._languageService) {
133
139
  this._logger.debug({ fileName: fileName }, 'getCompiledOutput(): compiling using language service');
140
+ // Must set memory cache before attempting to compile
134
141
  this._updateMemoryCache(fileContent, fileName, currentModuleKind === moduleKind);
135
142
  var output = this._languageService.getEmitOutput(fileName);
136
143
  var diagnostics = this.getDiagnostics(fileName);
@@ -147,6 +154,7 @@ var TsCompiler = (function () {
147
154
  this._logger.debug({ fileToReTypeCheck: fileToReTypeCheck }, '_doTypeChecking(): computing diagnostics using language service');
148
155
  this._updateMemoryCache(this._getFileContentFromCache(fileToReTypeCheck), fileToReTypeCheck);
149
156
  var importedModulesDiagnostics = __spreadArray(__spreadArray([], __read(this._languageService.getSemanticDiagnostics(fileToReTypeCheck)), false), __read(this._languageService.getSyntacticDiagnostics(fileToReTypeCheck)), false);
157
+ // will raise or just warn diagnostics depending on config
150
158
  this.configSet.raiseDiagnostics(importedModulesDiagnostics, fileName, this._logger);
151
159
  }
152
160
  }
@@ -162,17 +170,18 @@ var TsCompiler = (function () {
162
170
  }
163
171
  if (output.emitSkipped) {
164
172
  if (constants_1.TS_TSX_REGEX.test(fileName)) {
165
- throw new Error((0, messages_1.interpolate)("Unable to process '{{file}}', please make sure that `outDir` in your tsconfig is neither `''` or `'.'`. You can also configure Jest config option `transformIgnorePatterns` to inform `ts-jest` to transform {{file}}", { file: fileName }));
173
+ throw new Error((0, messages_1.interpolate)("Unable to process '{{file}}', please make sure that `outDir` in your tsconfig is neither `''` or `'.'`. You can also configure Jest config option `transformIgnorePatterns` to inform `ts-jest` to transform {{file}}" /* Errors.CannotProcessFile */, { file: fileName }));
166
174
  }
167
175
  else {
168
- this._logger.warn((0, messages_1.interpolate)("Unable to process '{{file}}', falling back to original file content. You can also configure Jest config option `transformIgnorePatterns` to ignore {{file}} from transformation or make sure that `outDir` in your tsconfig is neither `''` or `'.'`", { file: fileName }));
176
+ this._logger.warn((0, messages_1.interpolate)("Unable to process '{{file}}', falling back to original file content. You can also configure Jest config option `transformIgnorePatterns` to ignore {{file}} from transformation or make sure that `outDir` in your tsconfig is neither `''` or `'.'`" /* Errors.CannotProcessFileReturnOriginal */, { file: fileName }));
169
177
  return {
170
178
  code: fileContent,
171
179
  };
172
180
  }
173
181
  }
182
+ // Throw an error when requiring `.d.ts` files.
174
183
  if (!output.outputFiles.length) {
175
- throw new TypeError((0, messages_1.interpolate)("Unable to require `.d.ts` file for file: {{file}}.\nThis is usually the result of a faulty configuration or import. Make sure there is a `.js`, `.json` or another executable extension available alongside `{{file}}`.", {
184
+ throw new TypeError((0, messages_1.interpolate)("Unable to require `.d.ts` file for file: {{file}}.\nThis is usually the result of a faulty configuration or import. Make sure there is a `.js`, `.json` or another executable extension available alongside `{{file}}`." /* Errors.UnableToRequireDefinitionFile */, {
176
185
  file: (0, path_1.basename)(fileName),
177
186
  }));
178
187
  }
@@ -220,19 +229,33 @@ var TsCompiler = (function () {
220
229
  }),
221
230
  };
222
231
  };
232
+ /**
233
+ * @internal
234
+ */
223
235
  TsCompiler.prototype._createLanguageService = function () {
224
236
  var _this = this;
225
237
  var _a;
238
+ // Initialize memory cache for typescript compiler
226
239
  this._parsedTsConfig.fileNames
227
240
  .filter(function (fileName) { return constants_1.TS_TSX_REGEX.test(fileName) && !_this.configSet.isTestFile(fileName); })
241
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
228
242
  .forEach(function (fileName) { return _this._fileVersionCache.set(fileName, 0); });
243
+ /* istanbul ignore next */
229
244
  var serviceHost = {
230
245
  useCaseSensitiveFileNames: function () { return _this._ts.sys.useCaseSensitiveFileNames; },
231
246
  getProjectVersion: function () { return String(_this._projectVersion); },
247
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
232
248
  getScriptFileNames: function () { return __spreadArray([], __read(_this._fileVersionCache.keys()), false); },
233
249
  getScriptVersion: function (fileName) {
234
250
  var normalizedFileName = (0, path_1.normalize)(fileName);
251
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
235
252
  var version = _this._fileVersionCache.get(normalizedFileName);
253
+ // We need to return `undefined` and not a string here because TypeScript will use
254
+ // `getScriptVersion` and compare against their own version - which can be `undefined`.
255
+ // If we don't return `undefined` it results in `undefined === "undefined"` and run
256
+ // `createProgram` again (which is very slow). Using a `string` assertion here to avoid
257
+ // TypeScript errors from the function signature (expects `(x: string) => string`).
258
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
236
259
  return version === undefined ? undefined : String(version);
237
260
  },
238
261
  getScriptSnapshot: function (fileName) {
@@ -240,13 +263,19 @@ var TsCompiler = (function () {
240
263
  var normalizedFileName = (0, path_1.normalize)(fileName);
241
264
  var hit = _this._isFileInCache(normalizedFileName);
242
265
  _this._logger.trace({ normalizedFileName: normalizedFileName, cacheHit: hit }, 'getScriptSnapshot():', 'cache', hit ? 'hit' : 'miss');
266
+ // Read file content from either memory cache or Jest runtime cache or fallback to file system read
243
267
  if (!hit) {
244
- var fileContent = (_d = (_b = (_a = _this._fileContentCache.get(normalizedFileName)) !== null && _a !== void 0 ? _a : _this._runtimeCacheFS.get(normalizedFileName)) !== null && _b !== void 0 ? _b : (_c = _this._cachedReadFile) === null || _c === void 0 ? void 0 : _c.call(_this, normalizedFileName)) !== null && _d !== void 0 ? _d : undefined;
268
+ var fileContent =
269
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
270
+ (_d = (_b = (_a = _this._fileContentCache.get(normalizedFileName)) !== null && _a !== void 0 ? _a : _this._runtimeCacheFS.get(normalizedFileName)) !== null && _b !== void 0 ? _b : (_c = _this._cachedReadFile) === null || _c === void 0 ? void 0 : _c.call(_this, normalizedFileName)) !== null && _d !== void 0 ? _d : undefined;
245
271
  if (fileContent !== undefined) {
272
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
246
273
  _this._fileContentCache.set(normalizedFileName, fileContent);
274
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
247
275
  _this._fileVersionCache.set(normalizedFileName, 1);
248
276
  }
249
277
  }
278
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
250
279
  var contents = _this._fileContentCache.get(normalizedFileName);
251
280
  if (contents === undefined)
252
281
  return;
@@ -271,51 +300,87 @@ var TsCompiler = (function () {
271
300
  this._languageService = this._ts.createLanguageService(serviceHost, this._ts.createDocumentRegistry(this._ts.sys.useCaseSensitiveFileNames, this.configSet.cwd));
272
301
  this.program = this._languageService.getProgram();
273
302
  };
303
+ /**
304
+ * @internal
305
+ */
274
306
  TsCompiler.prototype._getFileContentFromCache = function (filePath) {
275
307
  var normalizedFilePath = (0, path_1.normalize)(filePath);
276
308
  var resolvedFileContent = this._runtimeCacheFS.get(normalizedFilePath);
277
309
  if (!resolvedFileContent) {
310
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
278
311
  resolvedFileContent = this._moduleResolutionHost.readFile(normalizedFilePath);
279
312
  this._runtimeCacheFS.set(normalizedFilePath, resolvedFileContent);
280
313
  }
281
314
  return resolvedFileContent;
282
315
  };
316
+ /**
317
+ * @internal
318
+ */
283
319
  TsCompiler.prototype._getImportedModulePaths = function (resolvedFileContent, containingFile) {
284
320
  var _this = this;
285
321
  return this._ts
286
322
  .preProcessFile(resolvedFileContent, true, true)
287
323
  .importedFiles.map(function (importedFile) {
288
324
  var resolvedModule = _this._resolveModuleName(importedFile.fileName, containingFile).resolvedModule;
325
+ /* istanbul ignore next already covered */
289
326
  var resolvedFileName = resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.resolvedFileName;
327
+ /* istanbul ignore next already covered */
290
328
  return resolvedFileName && !(resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.isExternalLibraryImport) ? resolvedFileName : '';
291
329
  })
292
330
  .filter(function (resolveFileName) { return !!resolveFileName; });
293
331
  };
332
+ /**
333
+ * @internal
334
+ */
294
335
  TsCompiler.prototype._resolveModuleName = function (moduleNameToResolve, containingFile) {
295
- return this._ts.resolveModuleName(moduleNameToResolve, containingFile, this._compilerOptions, this._moduleResolutionHost, this._moduleResolutionCache);
336
+ return this._ts.resolveModuleName(moduleNameToResolve, containingFile, this._compilerOptions,
337
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
338
+ this._moduleResolutionHost,
339
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
340
+ this._moduleResolutionCache);
296
341
  };
342
+ /**
343
+ * @internal
344
+ */
297
345
  TsCompiler.prototype._isFileInCache = function (fileName) {
298
- return (this._fileContentCache.has(fileName) &&
346
+ return (
347
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
348
+ this._fileContentCache.has(fileName) &&
349
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
299
350
  this._fileVersionCache.has(fileName) &&
351
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
300
352
  this._fileVersionCache.get(fileName) !== 0);
301
353
  };
354
+ /**
355
+ * @internal
356
+ */
302
357
  TsCompiler.prototype._updateMemoryCache = function (contents, fileName, isModuleKindTheSame) {
303
358
  if (isModuleKindTheSame === void 0) { isModuleKindTheSame = true; }
304
359
  this._logger.debug({ fileName: fileName }, 'updateMemoryCache: update memory cache for language service');
305
360
  var shouldIncrementProjectVersion = false;
306
361
  var hit = this._isFileInCache(fileName);
307
362
  if (!hit) {
363
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
308
364
  this._fileVersionCache.set(fileName, 1);
309
365
  shouldIncrementProjectVersion = true;
310
366
  }
311
367
  else {
368
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
312
369
  var prevVersion = this._fileVersionCache.get(fileName);
370
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
313
371
  var previousContents = this._fileContentCache.get(fileName);
372
+ // Avoid incrementing cache when nothing has changed.
314
373
  if (previousContents !== contents) {
374
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
315
375
  this._fileVersionCache.set(fileName, prevVersion + 1);
376
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
316
377
  this._fileContentCache.set(fileName, contents);
317
378
  shouldIncrementProjectVersion = true;
318
379
  }
380
+ /**
381
+ * When a file is from node_modules or referenced to a referenced project and jest wants to transform it, we need
382
+ * to make sure that the Program is updated with this information
383
+ */
319
384
  if (!this._parsedTsConfig.fileNames.includes(fileName) || !isModuleKindTheSame) {
320
385
  shouldIncrementProjectVersion = true;
321
386
  }
@@ -323,10 +388,14 @@ var TsCompiler = (function () {
323
388
  if (shouldIncrementProjectVersion)
324
389
  this._projectVersion++;
325
390
  };
391
+ /**
392
+ * @internal
393
+ */
326
394
  TsCompiler.prototype.getDiagnostics = function (fileName) {
327
395
  var diagnostics = [];
328
396
  if (this.configSet.shouldReportDiagnostics(fileName)) {
329
397
  this._logger.debug({ fileName: fileName }, '_doTypeChecking(): computing diagnostics using language service');
398
+ // Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.
330
399
  diagnostics.push.apply(diagnostics, __spreadArray(__spreadArray([], __read(this._languageService.getSemanticDiagnostics(fileName)), false), __read(this._languageService.getSyntacticDiagnostics(fileName)), false));
331
400
  }
332
401
  return diagnostics;
@@ -2,8 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.TsJestCompiler = void 0;
4
4
  var ts_compiler_1 = require("./ts-compiler");
5
- var TsJestCompiler = (function () {
5
+ var TsJestCompiler = /** @class */ (function () {
6
6
  function TsJestCompiler(configSet, runtimeCacheFS) {
7
+ // Later we can add swc/esbuild or other typescript compiler instance here
7
8
  this._compilerInstance = new ts_compiler_1.TsCompiler(configSet, runtimeCacheFS);
8
9
  }
9
10
  TsJestCompiler.prototype.getResolvedModules = function (fileContent, fileName, runtimeCacheFS) {
@@ -4,6 +4,9 @@ import type { RawCompilerOptions } from '../../raw-compiler-options';
4
4
  import type { ProjectConfigTsJest, TsJestAstTransformer, TTypeScript } from '../../types';
5
5
  export declare class ConfigSet {
6
6
  readonly parentLogger?: Logger | undefined;
7
+ /**
8
+ * Use by e2e, don't mark as internal
9
+ */
7
10
  readonly tsJestDigest: string;
8
11
  readonly logger: Logger;
9
12
  readonly compilerModule: TTypeScript;
@@ -16,6 +19,10 @@ export declare class ConfigSet {
16
19
  resolvedTransformers: TsJestAstTransformer;
17
20
  useESM: boolean;
18
21
  constructor(jestConfig: ProjectConfigTsJest | undefined, parentLogger?: Logger | undefined);
22
+ /**
23
+ * Load TypeScript configuration. Returns the parsed TypeScript config and any `tsconfig` options specified in ts-jest
24
+ * Subclasses which extend `ConfigSet` can override the default behavior
25
+ */
19
26
  protected _resolveTsConfig(compilerOptions?: RawCompilerOptions, resolvedConfigFile?: string): Record<string, any>;
20
27
  isTestFile(fileName: string): boolean;
21
28
  shouldStringifyContent(filePath: string): boolean;
@@ -74,6 +74,16 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
74
74
  };
75
75
  Object.defineProperty(exports, "__esModule", { value: true });
76
76
  exports.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
+ */
77
87
  var fs_1 = require("fs");
78
88
  var module_1 = __importDefault(require("module"));
79
89
  var path_1 = require("path");
@@ -89,12 +99,21 @@ var messages_1 = require("../../utils/messages");
89
99
  var normalize_slashes_1 = require("../../utils/normalize-slashes");
90
100
  var sha1_1 = require("../../utils/sha1");
91
101
  var ts_error_1 = require("../../utils/ts-error");
102
+ /**
103
+ * @internal
104
+ */
92
105
  exports.MY_DIGEST = (0, fs_1.readFileSync)((0, path_1.resolve)(__dirname, '../../../.ts-jest-digest'), 'utf8');
106
+ /**
107
+ * @internal
108
+ */
93
109
  exports.IGNORE_DIAGNOSTIC_CODES = [
94
110
  6059,
95
111
  18002,
96
- 18003,
112
+ 18003, // "No inputs were found in config file."
97
113
  ];
114
+ /**
115
+ * @internal
116
+ */
98
117
  exports.TS_JEST_OUT_DIR = '$$ts-jest$$';
99
118
  var normalizeRegex = function (pattern) {
100
119
  return pattern ? (typeof pattern === 'string' ? pattern : pattern.source) : undefined;
@@ -131,21 +150,26 @@ var toDiagnosticCodeList = function (items, into) {
131
150
  return into;
132
151
  };
133
152
  var requireFromString = function (code, fileName) {
153
+ // @ts-expect-error `_nodeModulePaths` is not exposed in typing
134
154
  var paths = module_1.default._nodeModulePaths((0, path_1.dirname)(fileName));
135
155
  var parent = module.parent;
136
156
  var m = new module_1.default(fileName, parent);
137
157
  m.filename = fileName;
138
158
  m.paths = [].concat(paths);
159
+ // @ts-expect-error `_compile` is not exposed in typing
139
160
  m._compile(code, fileName);
140
161
  var exports = m.exports;
141
162
  parent && parent.children && parent.children.splice(parent.children.indexOf(m), 1);
142
163
  return exports;
143
164
  };
144
- var ConfigSet = (function () {
165
+ var ConfigSet = /** @class */ (function () {
145
166
  function ConfigSet(jestConfig, parentLogger) {
146
167
  var _a, _b;
147
168
  var _c, _d, _e, _f;
148
169
  this.parentLogger = parentLogger;
170
+ /**
171
+ * Use by e2e, don't mark as internal
172
+ */
149
173
  this.tsJestDigest = exports.MY_DIGEST;
150
174
  this.resolvedTransformers = {
151
175
  before: [],
@@ -153,11 +177,17 @@ var ConfigSet = (function () {
153
177
  afterDeclarations: [],
154
178
  };
155
179
  this.useESM = false;
180
+ /**
181
+ * @internal
182
+ */
156
183
  this._overriddenCompilerOptions = {
157
184
  inlineSourceMap: false,
185
+ // we don't want to create declaration files
158
186
  declaration: false,
159
187
  noEmit: false,
188
+ // else istanbul related will be dropped
160
189
  removeComments: false,
190
+ // to clear out else it's buggy
161
191
  out: undefined,
162
192
  outFile: undefined,
163
193
  composite: undefined,
@@ -175,12 +205,18 @@ var ConfigSet = (function () {
175
205
  this.rootDir = (0, path_1.normalize)((_d = this._jestCfg.rootDir) !== null && _d !== void 0 ? _d : this.cwd);
176
206
  var tsJestCfg = this._jestCfg.globals && this._jestCfg.globals['ts-jest'];
177
207
  var options = tsJestCfg !== null && tsJestCfg !== void 0 ? tsJestCfg : Object.create(null);
178
- this.compilerModule = importer_1.importer.typescript("Using \"ts-jest\" requires this package to be installed.", (_e = options.compiler) !== null && _e !== void 0 ? _e : 'typescript');
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
179
211
  this.isolatedModules = (_f = options.isolatedModules) !== null && _f !== void 0 ? _f : false;
180
212
  this.logger.debug({ compilerModule: this.compilerModule }, 'normalized compiler module config via ts-jest option');
181
213
  this._setupConfigSet(options);
182
214
  this._resolveTsCacheDir();
183
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
+ */
184
220
  return pattern instanceof RegExp || typeof pattern === 'string';
185
221
  });
186
222
  if (!this._matchablePatterns.length) {
@@ -188,16 +224,24 @@ var ConfigSet = (function () {
188
224
  }
189
225
  this._matchTestFilePath = (0, jest_util_1.globsToMatcher)(this._matchablePatterns.filter(function (pattern) { return typeof pattern === 'string'; }));
190
226
  }
227
+ /**
228
+ * @internal
229
+ */
191
230
  ConfigSet.prototype._backportJestCfg = function (jestCfg) {
192
231
  var _a, _b;
193
232
  var config = (0, backports_1.backportJestConfig)(this.logger, jestCfg);
194
233
  this.logger.debug({ jestConfig: config }, 'normalized jest config');
195
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 : [] });
196
235
  };
236
+ /**
237
+ * @internal
238
+ */
197
239
  ConfigSet.prototype._setupConfigSet = function (options) {
198
240
  var _this = this;
199
241
  var _a, _b, _c, _d, _e;
242
+ // useESM
200
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
201
245
  if (!options.babelConfig) {
202
246
  this.logger.debug('babel is disabled');
203
247
  }
@@ -221,10 +265,11 @@ var ConfigSet = (function () {
221
265
  }
222
266
  this.logger.debug({ babelConfig: this.babelConfig }, 'normalized babel config via ts-jest option');
223
267
  this.babelJestTransformer = importer_1.importer
224
- .babelJest("Using \"babel-jest\" requires this package to be installed.")
268
+ .babelJest("Using \"babel-jest\" requires this package to be installed." /* ImportReasons.BabelJest */)
225
269
  .createTransformer(this.babelConfig);
226
270
  this.logger.debug('created babel-jest transformer');
227
271
  }
272
+ // diagnostics
228
273
  var diagnosticsOpt = (_b = options.diagnostics) !== null && _b !== void 0 ? _b : true;
229
274
  var ignoreList = __spreadArray([], __read(exports.IGNORE_DIAGNOSTIC_CODES), false);
230
275
  if (typeof diagnosticsOpt === 'object') {
@@ -256,11 +301,14 @@ var ConfigSet = (function () {
256
301
  this._shouldIgnoreDiagnosticsForFile = function () { return true; };
257
302
  }
258
303
  this.logger.debug({ diagnostics: this._diagnostics }, 'normalized diagnostics config via ts-jest option');
304
+ // tsconfig
259
305
  var tsconfigOpt = options.tsconfig;
260
306
  var configFilePath = typeof tsconfigOpt === 'string' ? this.resolvePath(tsconfigOpt) : undefined;
261
307
  this.parsedTsConfig = this._getAndResolveTsConfig(typeof tsconfigOpt === 'object' ? tsconfigOpt : undefined, configFilePath);
308
+ // throw errors if any matching wanted diagnostics
262
309
  this.raiseDiagnostics(this.parsedTsConfig.errors, configFilePath);
263
310
  this.logger.debug({ tsconfig: this.parsedTsConfig }, 'normalized typescript config via ts-jest option');
311
+ // transformers
264
312
  this.resolvedTransformers.before = [
265
313
  {
266
314
  factory: hoistJestTransformer.factory,
@@ -274,7 +322,7 @@ var ConfigSet = (function () {
274
322
  var transformerFunc;
275
323
  if ((0, path_1.extname)(transformerPath) === '.ts') {
276
324
  var compiledTransformer = importer_1.importer
277
- .esBuild("Using \"esbuild\" requires this package to be installed.")
325
+ .esBuild("Using \"esbuild\" requires this package to be installed." /* ImportReasons.EsBuild */)
278
326
  .transformSync((0, fs_1.readFileSync)(transformerPath, 'utf-8'), {
279
327
  loader: 'ts',
280
328
  format: 'cjs',
@@ -286,10 +334,10 @@ var ConfigSet = (function () {
286
334
  transformerFunc = require(transformerPath);
287
335
  }
288
336
  if (!transformerFunc.version) {
289
- _this.logger.warn("The AST transformer {{file}} must have an `export const version = <your_transformer_version>`", { file: transformerPath });
337
+ _this.logger.warn("The AST transformer {{file}} must have an `export const version = <your_transformer_version>`" /* Errors.MissingTransformerVersion */, { file: transformerPath });
290
338
  }
291
339
  if (!transformerFunc.name) {
292
- _this.logger.warn("The AST transformer {{file}} must have an `export const name = <your_transformer_name>`", { file: transformerPath });
340
+ _this.logger.warn("The AST transformer {{file}} must have an `export const name = <your_transformer_name>`" /* Errors.MissingTransformerName */, { file: transformerPath });
293
341
  }
294
342
  return transformerFunc;
295
343
  };
@@ -304,6 +352,7 @@ var ConfigSet = (function () {
304
352
  });
305
353
  };
306
354
  if (astTransformers.before) {
355
+ /* istanbul ignore next (already covered in unit test) */
307
356
  (_e = this.resolvedTransformers.before) === null || _e === void 0 ? void 0 : _e.push.apply(_e, __spreadArray([], __read(resolveTransformers(astTransformers.before)), false));
308
357
  }
309
358
  if (astTransformers.after) {
@@ -314,14 +363,18 @@ var ConfigSet = (function () {
314
363
  }
315
364
  }
316
365
  this.logger.debug({ customTransformers: this.resolvedTransformers }, 'normalized custom AST transformers via ts-jest option');
366
+ // stringifyContentPathRegex
317
367
  if (options.stringifyContentPathRegex) {
318
368
  this._stringifyContentRegExp =
319
369
  typeof options.stringifyContentPathRegex === 'string'
320
- ? new RegExp(normalizeRegex(options.stringifyContentPathRegex))
370
+ ? new RegExp(normalizeRegex(options.stringifyContentPathRegex)) // eslint-disable-line @typescript-eslint/no-non-null-assertion
321
371
  : options.stringifyContentPathRegex;
322
372
  this.logger.debug({ stringifyContentPathRegex: this._stringifyContentRegExp }, 'normalized stringifyContentPathRegex config via ts-jest option');
323
373
  }
324
374
  };
375
+ /**
376
+ * @internal
377
+ */
325
378
  ConfigSet.prototype._resolveTsCacheDir = function () {
326
379
  this.cacheSuffix = (0, sha1_1.sha1)((0, utils_1.stringify)({
327
380
  version: this.compilerModule.version,
@@ -346,16 +399,22 @@ var ConfigSet = (function () {
346
399
  this.tsCacheDir = res;
347
400
  }
348
401
  };
402
+ /**
403
+ * @internal
404
+ */
349
405
  ConfigSet.prototype._getAndResolveTsConfig = function (compilerOptions, resolvedConfigFile) {
350
406
  var e_2, _a, _b;
351
407
  var _c, _d, _e;
352
408
  var result = this._resolveTsConfig(compilerOptions, resolvedConfigFile);
353
409
  var forcedOptions = this._overriddenCompilerOptions;
354
410
  var finalOptions = result.options;
411
+ // Target ES2015 output by default (instead of ES3).
355
412
  if (finalOptions.target === undefined) {
356
413
  finalOptions.target = this.compilerModule.ScriptTarget.ES2015;
357
414
  }
415
+ // check the module interoperability
358
416
  var target = finalOptions.target;
417
+ // compute the default if not set
359
418
  var defaultModule = [this.compilerModule.ScriptTarget.ES3, this.compilerModule.ScriptTarget.ES5].includes(target)
360
419
  ? this.compilerModule.ModuleKind.CommonJS
361
420
  : this.compilerModule.ModuleKind.ESNext;
@@ -364,21 +423,25 @@ var ConfigSet = (function () {
364
423
  moduleValue !== this.compilerModule.ModuleKind.CommonJS &&
365
424
  !(finalOptions.esModuleInterop || finalOptions.allowSyntheticDefaultImports)) {
366
425
  result.errors.push({
367
- code: 151001,
368
- 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.",
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 */,
369
428
  category: this.compilerModule.DiagnosticCategory.Message,
370
429
  file: undefined,
371
430
  start: undefined,
372
431
  length: undefined,
373
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) */
374
435
  if (!('allowSyntheticDefaultImports' in finalOptions)) {
375
436
  finalOptions.allowSyntheticDefaultImports = true;
376
437
  }
377
438
  }
439
+ // Make sure when allowJs is enabled, outDir is required to have when using allowJs: true
378
440
  if (finalOptions.allowJs && !finalOptions.outDir) {
379
441
  finalOptions.outDir = exports.TS_JEST_OUT_DIR;
380
442
  }
381
443
  try {
444
+ // ensure undefined are removed and other values are overridden
382
445
  for (var _f = __values(Object.keys(forcedOptions)), _g = _f.next(); !_g.done; _g = _f.next()) {
383
446
  var key = _g.value;
384
447
  var val = forcedOptions[key];
@@ -397,6 +460,10 @@ var ConfigSet = (function () {
397
460
  }
398
461
  finally { if (e_2) throw e_2.error; }
399
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
+ */
400
467
  var nodeJsVer = process.version;
401
468
  var compilationTarget = result.options.target;
402
469
  var TARGET_TO_VERSION_MAPPING = (_b = {},
@@ -405,11 +472,12 @@ var ConfigSet = (function () {
405
472
  _b[this.compilerModule.ScriptTarget.ES2020] = 'es2020',
406
473
  _b[this.compilerModule.ScriptTarget.ESNext] = 'ESNext',
407
474
  _b);
475
+ /* istanbul ignore next (cover by e2e) */
408
476
  if (compilationTarget &&
409
477
  !this.babelConfig &&
410
478
  nodeJsVer.startsWith('v12') &&
411
479
  compilationTarget > this.compilerModule.ScriptTarget.ES2019) {
412
- 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", {
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 */, {
413
481
  nodeJsVer: process.version,
414
482
  compilationTarget: TARGET_TO_VERSION_MAPPING[compilationTarget],
415
483
  });
@@ -419,23 +487,28 @@ var ConfigSet = (function () {
419
487
  var sourceMap = (_d = resultOptions.sourceMap) !== null && _d !== void 0 ? _d : true;
420
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 }) });
421
489
  };
490
+ // eslint-disable-next-line no-dupe-class-members
422
491
  ConfigSet.prototype._resolveTsConfig = function (compilerOptions, resolvedConfigFile) {
423
492
  var config = { compilerOptions: Object.create(null) };
424
493
  var basePath = (0, normalize_slashes_1.normalizeSlashes)(this.rootDir);
425
494
  var ts = this.compilerModule;
495
+ // Read project configuration when available.
426
496
  var configFileName = resolvedConfigFile
427
497
  ? (0, normalize_slashes_1.normalizeSlashes)(resolvedConfigFile)
428
498
  : ts.findConfigFile((0, normalize_slashes_1.normalizeSlashes)(this.rootDir), ts.sys.fileExists);
429
499
  if (configFileName) {
430
500
  this.logger.debug({ tsConfigFileName: configFileName }, 'readTsConfig(): reading', configFileName);
431
501
  var result = ts.readConfigFile(configFileName, ts.sys.readFile);
502
+ // Return diagnostics.
432
503
  if (result.error) {
433
504
  return { errors: [result.error], fileNames: [], options: {} };
434
505
  }
435
506
  config = result.config;
436
507
  basePath = (0, normalize_slashes_1.normalizeSlashes)((0, path_1.dirname)(configFileName));
437
508
  }
509
+ // Override default configuration options `ts-jest` requires.
438
510
  config.compilerOptions = __assign(__assign({}, config.compilerOptions), compilerOptions);
511
+ // parse json, merge config extending others, ...
439
512
  return ts.parseJsonConfigFileContent(config, ts.sys, basePath, undefined, configFileName);
440
513
  };
441
514
  ConfigSet.prototype.isTestFile = function (fileName) {
@@ -463,10 +536,12 @@ var ConfigSet = (function () {
463
536
  if (!filteredDiagnostics.length)
464
537
  return;
465
538
  var error = this.createTsError(filteredDiagnostics);
539
+ // only throw if `warnOnly` and it is a warning or error
466
540
  var importantCategories = [DiagnosticCategory.Warning, DiagnosticCategory.Error];
467
541
  if (this._diagnostics.throws && filteredDiagnostics.some(function (d) { return importantCategories.includes(d.category); })) {
468
542
  throw error;
469
543
  }
544
+ /* istanbul ignore next (already covered) */
470
545
  logger ? logger.warn({ error: error }, error.message) : this.logger.warn({ error: error }, error.message);
471
546
  };
472
547
  ConfigSet.prototype.shouldReportDiagnostics = function (filePath) {
@@ -475,11 +550,15 @@ var ConfigSet = (function () {
475
550
  ? this.parsedTsConfig.options.checkJs && !this._shouldIgnoreDiagnosticsForFile(filePath)
476
551
  : !this._shouldIgnoreDiagnosticsForFile(filePath);
477
552
  };
553
+ /**
554
+ * @internal
555
+ */
478
556
  ConfigSet.prototype.createTsError = function (diagnostics) {
479
557
  var _this = this;
480
558
  var formatDiagnostics = this._diagnostics.pretty
481
559
  ? this.compilerModule.formatDiagnosticsWithColorAndContext
482
560
  : this.compilerModule.formatDiagnostics;
561
+ /* istanbul ignore next (not possible to cover) */
483
562
  var diagnosticHost = {
484
563
  getNewLine: function () { return '\n'; },
485
564
  getCurrentDirectory: function () { return _this.cwd; },
@@ -516,7 +595,7 @@ var ConfigSet = (function () {
516
595
  catch (_) { }
517
596
  }
518
597
  if (throwIfMissing && !(0, fs_1.existsSync)(path)) {
519
- throw new Error((0, messages_1.interpolate)("File not found: {{inputPath}} (resolved as: {{resolvedPath}})", { inputPath: inputPath, resolvedPath: path }));
598
+ throw new Error((0, messages_1.interpolate)("File not found: {{inputPath}} (resolved as: {{resolvedPath}})" /* Errors.FileNotFound */, { inputPath: inputPath, resolvedPath: path }));
520
599
  }
521
600
  this.logger.debug({ fromPath: inputPath, toPath: path }, 'resolved path from', inputPath, 'to', path);
522
601
  return path;
@@ -13,11 +13,24 @@ export declare class TsJestTransformer implements SyncTransformer {
13
13
  private _configsFor;
14
14
  protected _createConfigSet(config: ProjectConfigTsJest | undefined): ConfigSet;
15
15
  protected _createCompiler(configSet: ConfigSet, cacheFS: Map<string, string>): void;
16
+ /**
17
+ * @public
18
+ */
16
19
  process(sourceText: string, sourcePath: string, transformOptions: TransformOptionsTsJest): TransformedSource;
17
20
  processAsync(sourceText: string, sourcePath: string, transformOptions: TransformOptionsTsJest): Promise<TransformedSource>;
18
21
  private processWithTs;
19
22
  private runTsJestHook;
23
+ /**
24
+ * Jest uses this to cache the compiled version of a file
25
+ *
26
+ * @see https://github.com/facebook/jest/blob/v23.5.0/packages/jest-runtime/src/script_transformer.js#L61-L90
27
+ *
28
+ * @public
29
+ */
20
30
  getCacheKey(fileContent: string, filePath: string, transformOptions: TransformOptionsTsJest): string;
21
31
  getCacheKeyAsync(sourceText: string, sourcePath: string, transformOptions: TransformOptionsTsJest): Promise<string>;
32
+ /**
33
+ * Subclasses extends `TsJestTransformer` can call this method to get resolved module disk cache
34
+ */
22
35
  private _getFsCachedResolvedModules;
23
36
  }