ts-jest 26.3.0 → 26.4.0

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 (63) hide show
  1. package/.ts-jest-digest +1 -1
  2. package/CHANGELOG.md +22 -0
  3. package/dist/cli/config/init.d.ts +0 -5
  4. package/dist/cli/config/init.js +3 -18
  5. package/dist/cli/config/migrate.js +11 -41
  6. package/dist/cli/help.js +1 -7
  7. package/dist/cli/helpers/presets.js +5 -11
  8. package/dist/cli/index.js +11 -12
  9. package/dist/compiler/instance.js +2 -22
  10. package/dist/compiler/language-service.js +6 -47
  11. package/dist/compiler/transpiler.js +2 -7
  12. package/dist/config/config-set.d.ts +0 -19
  13. package/dist/config/config-set.js +118 -246
  14. package/dist/config/paths-to-module-name-mapper.js +8 -11
  15. package/dist/constants.js +0 -19
  16. package/dist/index.d.ts +2 -5
  17. package/dist/index.js +6 -33
  18. package/dist/{config → presets}/create-jest-preset.d.ts +2 -1
  19. package/dist/{config → presets}/create-jest-preset.js +1 -1
  20. package/dist/presets/index.d.ts +339 -0
  21. package/dist/presets/index.js +18 -0
  22. package/dist/transformers/hoist-jest.js +48 -73
  23. package/dist/transformers/index.js +20 -4
  24. package/dist/transformers/path-mapping.d.ts +3 -0
  25. package/dist/transformers/path-mapping.js +121 -0
  26. package/dist/ts-jest-transformer.d.ts +0 -14
  27. package/dist/ts-jest-transformer.js +8 -52
  28. package/dist/types.d.ts +7 -90
  29. package/dist/{util → utils}/backports.d.ts +0 -0
  30. package/dist/{util → utils}/backports.js +4 -11
  31. package/dist/{util → utils}/get-package-version.d.ts +0 -0
  32. package/dist/{util → utils}/get-package-version.js +0 -3
  33. package/dist/{util → utils}/importer.d.ts +0 -0
  34. package/dist/{util → utils}/importer.js +4 -29
  35. package/dist/{util → utils}/index.d.ts +1 -1
  36. package/dist/{util → utils}/index.js +1 -1
  37. package/dist/{util → utils}/json.d.ts +0 -0
  38. package/dist/{util → utils}/json.js +0 -14
  39. package/dist/{util → utils}/jsonable-value.d.ts +0 -0
  40. package/dist/{util → utils}/jsonable-value.js +1 -4
  41. package/dist/{util → utils}/logger.d.ts +0 -0
  42. package/dist/{util → utils}/logger.js +0 -4
  43. package/dist/{util → utils}/memoize.d.ts +0 -0
  44. package/dist/{util → utils}/memoize.js +0 -8
  45. package/dist/{util → utils}/messages.d.ts +0 -0
  46. package/dist/{util → utils}/messages.js +0 -4
  47. package/dist/{util → utils}/normalize-slashes.d.ts +0 -0
  48. package/dist/{util → utils}/normalize-slashes.js +0 -3
  49. package/dist/{util → utils}/sha1.d.ts +0 -0
  50. package/dist/{util → utils}/sha1.js +0 -10
  51. package/dist/{util → utils}/testing.d.ts +0 -0
  52. package/dist/{util → utils}/testing.js +0 -0
  53. package/dist/{util → utils}/ts-error.d.ts +0 -0
  54. package/dist/{util → utils}/ts-error.js +2 -12
  55. package/dist/{util → utils}/version-checkers.d.ts +0 -0
  56. package/dist/{util → utils}/version-checkers.js +5 -8
  57. package/jest-preset.js +1 -1
  58. package/package.json +7 -7
  59. package/presets/index.js +1 -20
  60. package/utils/index.d.ts +1 -1
  61. package/utils/index.js +1 -1
  62. package/presets/create.js +0 -1
  63. package/presets/index.d.ts +0 -5
package/.ts-jest-digest CHANGED
@@ -1 +1 @@
1
- c0f7b076fbdbbcb07384ff15394a4e997771ae49
1
+ 19be30d21d2602243c1d945aa28bbcafd047e1fb
package/CHANGELOG.md CHANGED
@@ -1,3 +1,25 @@
1
+ # [26.4.0](https://github.com/kulshekhar/ts-jest/compare/v26.3.0...v26.4.0) (2020-09-20)
2
+
3
+
4
+ ### Bug Fixes
5
+
6
+ * **utils:** `pathsToModuleNameMapper` resolve path mapping with `path.join` ([#1969](https://github.com/kulshekhar/ts-jest/issues/1969)) ([81fce4c](https://github.com/kulshekhar/ts-jest/commit/81fce4c090811a1cc071579a99dc193fb976b117)), closes [#1968](https://github.com/kulshekhar/ts-jest/issues/1968)
7
+ * set minimum `jest-util` version at 26.1.0 ([#1914](https://github.com/kulshekhar/ts-jest/issues/1914)) ([f00414c](https://github.com/kulshekhar/ts-jest/commit/f00414c6fbf8fc5413fd33d0a271c4a164c50d45)), closes [#1913](https://github.com/kulshekhar/ts-jest/issues/1913)
8
+
9
+
10
+ ### Features
11
+
12
+ * **config:** allow custom options in custom transformers ([#1966](https://github.com/kulshekhar/ts-jest/issues/1966)) ([1452ce4](https://github.com/kulshekhar/ts-jest/commit/1452ce4afcd36049cddd0db0861f1ac26b66f8c1)), closes [#1942](https://github.com/kulshekhar/ts-jest/issues/1942)
13
+ * **transformers:** support hoisting when using `@jest/globals` ([#1937](https://github.com/kulshekhar/ts-jest/issues/1937)) ([0e5be15](https://github.com/kulshekhar/ts-jest/commit/0e5be1597d755fed11869f67df05eeea54b3106f)), closes [#1593](https://github.com/kulshekhar/ts-jest/issues/1593)
14
+ * **transformers:** add `path-mapping` custom AST transformer ([#1927](https://github.com/kulshekhar/ts-jest/issues/1927)) ([3325186](https://github.com/kulshekhar/ts-jest/commit/3325186b6e55f41eb9bf7d81e092a358fc402b13))
15
+
16
+
17
+ ### Performance Improvements
18
+
19
+ * **compiler:** remove `createProgram` for `isolatedModules: true` to boost startup speed ([#1941](https://github.com/kulshekhar/ts-jest/issues/1941)) ([dd84534](https://github.com/kulshekhar/ts-jest/commit/dd8453401840862186f991e2d514e0d328a67987))
20
+
21
+
22
+
1
23
  # [26.3.0](https://github.com/kulshekhar/ts-jest/compare/v26.2.0...v26.3.0) (2020-08-25)
2
24
 
3
25
 
@@ -1,6 +1 @@
1
- /**
2
- * This has been written quickly. While trying to improve I realised it'd be better to have it in Jest...
3
- * ...and I saw a merged PR with `jest --init` tool!
4
- * TODO: see what's the best path for this
5
- */
6
1
  export {};
@@ -1,9 +1,4 @@
1
1
  "use strict";
2
- /**
3
- * This has been written quickly. While trying to improve I realised it'd be better to have it in Jest...
4
- * ...and I saw a merged PR with `jest --init` tool!
5
- * TODO: see what's the best path for this
6
- */
7
2
  var __assign = (this && this.__assign) || function () {
8
3
  __assign = Object.assign || function(t) {
9
4
  for (var s, i = 1, n = arguments.length; i < n; i++) {
@@ -57,10 +52,7 @@ var fs_1 = require("fs");
57
52
  var json5_1 = require("json5");
58
53
  var path_1 = require("path");
59
54
  var presets_1 = require("../helpers/presets");
60
- /**
61
- * @internal
62
- */
63
- exports.run = function (args /* , logger: Logger */) { return __awaiter(void 0, void 0, void 0, function () {
55
+ exports.run = function (args) { return __awaiter(void 0, void 0, void 0, function () {
64
56
  var file, filePath, name, isPackage, exists, pkgFile, hasPackage, _a, jestPreset, askedTsconfig, force, jsdom, tsconfig, pkgJson, jsFilesProcessor, shouldPostProcessWithBabel, preset, body, base, tsJestConf, content;
65
57
  return __generator(this, function (_b) {
66
58
  file = args._[0] || 'jest.config.js';
@@ -74,13 +66,10 @@ exports.run = function (args /* , logger: Logger */) { return __awaiter(void 0,
74
66
  tsconfig = askedTsconfig === 'tsconfig.json' ? undefined : askedTsconfig;
75
67
  pkgJson = hasPackage ? JSON.parse(fs_1.readFileSync(pkgFile, 'utf8')) : {};
76
68
  jsFilesProcessor = args.js, shouldPostProcessWithBabel = args.babel;
77
- // set defaults for missing options
78
69
  if (jsFilesProcessor == null) {
79
- // set default js files processor depending on whether the user wants to post-process with babel
80
70
  jsFilesProcessor = shouldPostProcessWithBabel ? 'babel' : undefined;
81
71
  }
82
72
  else if (shouldPostProcessWithBabel == null) {
83
- // auto enables babel post-processing if the user wants babel to process js files
84
73
  shouldPostProcessWithBabel = jsFilesProcessor === 'babel';
85
74
  }
86
75
  if (jsFilesProcessor === 'babel') {
@@ -149,20 +138,16 @@ exports.run = function (args /* , logger: Logger */) { return __awaiter(void 0,
149
138
  content.push(' },');
150
139
  }
151
140
  content.push('};');
152
- // join all together
153
141
  body = content.join('\n');
154
142
  }
155
143
  fs_1.writeFileSync(filePath, body);
156
144
  process.stderr.write("\nJest configuration written to \"" + filePath + "\".\n");
157
- return [2 /*return*/];
145
+ return [2];
158
146
  });
159
147
  }); };
160
- /**
161
- * @internal
162
- */
163
148
  exports.help = function () { return __awaiter(void 0, void 0, void 0, function () {
164
149
  return __generator(this, function (_a) {
165
150
  process.stdout.write("\nUsage:\n ts-jest config:init [options] [<config-file>]\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n Default: jest.config.js\n\nOptions:\n --force Discard any existing Jest config\n --js ts|babel Process .js files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n --tsconfig <file> Path to the tsconfig.json file\n --babel Pipe babel-jest after ts-jest\n --jsdom Use jsdom as test environment instead of node\n");
166
- return [2 /*return*/];
151
+ return [2];
167
152
  });
168
153
  }); };
@@ -62,12 +62,9 @@ var stableStringify = require("fast-json-stable-stringify");
62
62
  var fs_1 = require("fs");
63
63
  var json5_1 = require("json5");
64
64
  var path_1 = require("path");
65
- var backports_1 = require("../../util/backports");
65
+ var backports_1 = require("../../utils/backports");
66
66
  var presets_1 = require("../helpers/presets");
67
- /**
68
- * @internal
69
- */
70
- exports.run = function (args /* , logger: Logger*/) { return __awaiter(void 0, void 0, void 0, function () {
67
+ exports.run = function (args) { return __awaiter(void 0, void 0, void 0, function () {
71
68
  var nullLogger, file, filePath, footNotes, name, isPackage, actualConfig, migratedConfig, presetName, preset, jsTransformers, jsWithTs, jsWithBabel, presetValue, migratedValue, presetValue, migratedValue, before, after, stringify, prefix;
72
69
  return __generator(this, function (_a) {
73
70
  nullLogger = bs_logger_1.createLogger({ targets: [] });
@@ -89,11 +86,9 @@ exports.run = function (args /* , logger: Logger*/) { return __awaiter(void 0, v
89
86
  if (!actualConfig)
90
87
  actualConfig = {};
91
88
  migratedConfig = backports_1.backportJestConfig(nullLogger, actualConfig);
92
- // then we check if we can use `preset`
93
89
  if (!migratedConfig.preset && args.jestPreset) {
94
- // find the best preset
95
90
  if (args.js) {
96
- presetName = args.js === 'babel' ? "ts-jest/presets/js-with-babel" /* jsWIthBabel */ : "ts-jest/presets/js-with-ts" /* jsWithTs */;
91
+ presetName = args.js === 'babel' ? "ts-jest/presets/js-with-babel" : "ts-jest/presets/js-with-ts";
97
92
  }
98
93
  else {
99
94
  jsTransformers = Object.keys(migratedConfig.transform || {}).reduce(function (list, pattern) {
@@ -110,18 +105,16 @@ exports.run = function (args /* , logger: Logger*/) { return __awaiter(void 0, v
110
105
  jsWithTs = jsTransformers.includes('ts-jest');
111
106
  jsWithBabel = jsTransformers.includes('babel-jest');
112
107
  if (jsWithBabel && !jsWithTs) {
113
- presetName = "ts-jest/presets/js-with-babel" /* jsWIthBabel */;
108
+ presetName = "ts-jest/presets/js-with-babel";
114
109
  }
115
110
  else if (jsWithTs && !jsWithBabel) {
116
- presetName = "ts-jest/presets/js-with-ts" /* jsWithTs */;
111
+ presetName = "ts-jest/presets/js-with-ts";
117
112
  }
118
113
  else {
119
- // sounds like js files are NOT handled, or handled with a unknown transformer, so we do not need to handle it
120
- presetName = "ts-jest/presets/default" /* default */;
114
+ presetName = "ts-jest/presets/default";
121
115
  }
122
116
  }
123
- // ensure we are using a preset
124
- presetName = presetName || "ts-jest/presets/default" /* default */;
117
+ presetName = presetName || "ts-jest/presets/default";
125
118
  preset = presets_1.allPresets[presetName];
126
119
  footNotes.push("Detected preset '" + preset.label + "' as the best matching preset for your configuration.\nVisit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more information about presets.\n");
127
120
  }
@@ -133,10 +126,8 @@ exports.run = function (args /* , logger: Logger*/) { return __awaiter(void 0, v
133
126
  preset = presets_1.allPresets[migratedConfig.preset] || presets_1.defaults;
134
127
  }
135
128
  }
136
- // enforce the correct name
137
129
  if (preset)
138
130
  migratedConfig.preset = preset.name;
139
- // check the extensions
140
131
  if (migratedConfig.moduleFileExtensions && migratedConfig.moduleFileExtensions.length && preset) {
141
132
  presetValue = dedupSort(preset.value.moduleFileExtensions || []).join('::');
142
133
  migratedValue = dedupSort(migratedConfig.moduleFileExtensions).join('::');
@@ -144,11 +135,9 @@ exports.run = function (args /* , logger: Logger*/) { return __awaiter(void 0, v
144
135
  delete migratedConfig.moduleFileExtensions;
145
136
  }
146
137
  }
147
- // there is a testRegex, remove our testMatch
148
138
  if (migratedConfig.testRegex && preset) {
149
139
  migratedConfig.testMatch = null;
150
140
  }
151
- // check the testMatch
152
141
  else if (migratedConfig.testMatch && migratedConfig.testMatch.length && preset) {
153
142
  presetValue = dedupSort(preset.value.testMatch || []).join('::');
154
143
  migratedValue = dedupSort(migratedConfig.testMatch).join('::');
@@ -156,7 +145,6 @@ exports.run = function (args /* , logger: Logger*/) { return __awaiter(void 0, v
156
145
  delete migratedConfig.testMatch;
157
146
  }
158
147
  }
159
- // migrate the transform
160
148
  if (migratedConfig.transform) {
161
149
  Object.keys(migratedConfig.transform).forEach(function (key) {
162
150
  var val = migratedConfig.transform[key];
@@ -166,45 +154,30 @@ exports.run = function (args /* , logger: Logger*/) { return __awaiter(void 0, v
166
154
  }
167
155
  });
168
156
  }
169
- // check if it's the same as the preset's one
170
157
  if (preset &&
171
158
  migratedConfig.transform &&
172
159
  stableStringify(migratedConfig.transform) === stableStringify(preset.value.transform)) {
173
160
  delete migratedConfig.transform;
174
161
  }
175
- // cleanup
176
162
  cleanupConfig(actualConfig);
177
163
  cleanupConfig(migratedConfig);
178
164
  before = stableStringify(actualConfig);
179
165
  after = stableStringify(migratedConfig);
180
166
  if (after === before) {
181
167
  process.stderr.write("\nNo migration needed for given Jest configuration\n ");
182
- return [2 /*return*/];
168
+ return [2];
183
169
  }
184
170
  stringify = file.endsWith('.json') ? JSON.stringify : json5_1.stringify;
185
171
  prefix = file.endsWith('.json') ? '"jest": ' : 'module.exports = ';
186
- // if we are using preset, inform the user that he might be able to remove some section(s)
187
- // we couldn't check for equality
188
- // if (usesPreset && migratedConfig.testMatch) {
189
- // footNotes.push(`
190
- // I couldn't check if your "testMatch" value is the same as mine which is: ${stringify(
191
- // presets.testMatch,
192
- // undefined,
193
- // ' ',
194
- // )}
195
- // If it is the case, you can safely remove the "testMatch" from what I've migrated.
196
- // `)
197
- // }
198
172
  if (preset && migratedConfig.transform) {
199
173
  footNotes.push("\nI couldn't check if your \"transform\" value is the same as mine which is: " + stringify(preset.value.transform, undefined, ' ') + "\nIf it is the case, you can safely remove the \"transform\" from what I've migrated.\n");
200
174
  }
201
- // output new config
202
175
  process.stderr.write("\nMigrated Jest configuration:\n");
203
176
  process.stdout.write("" + prefix + stringify(migratedConfig, undefined, ' ') + "\n");
204
177
  if (footNotes.length) {
205
178
  process.stderr.write("\n" + footNotes.join('\n') + "\n");
206
179
  }
207
- return [2 /*return*/];
180
+ return [2];
208
181
  });
209
182
  }); };
210
183
  function cleanupConfig(config) {
@@ -229,7 +202,7 @@ function cleanupConfig(config) {
229
202
  if (config.testMatch.length === 0)
230
203
  delete config.testMatch;
231
204
  }
232
- if (config.preset === "ts-jest/presets/default" /* default */)
205
+ if (config.preset === "ts-jest/presets/default")
233
206
  config.preset = presets_1.defaults.name;
234
207
  }
235
208
  function dedupSort(arr) {
@@ -237,12 +210,9 @@ function dedupSort(arr) {
237
210
  .filter(function (s, i, a) { return a.findIndex(function (e) { return s.toString() === e.toString(); }) === i; })
238
211
  .sort(function (a, b) { return (a.toString() > b.toString() ? 1 : a.toString() < b.toString() ? -1 : 0); });
239
212
  }
240
- /**
241
- * @internal
242
- */
243
213
  exports.help = function () { return __awaiter(void 0, void 0, void 0, function () {
244
214
  return __generator(this, function (_a) {
245
215
  process.stdout.write("\nUsage:\n ts-jest config:migrate [options] <config-file>\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n\nOptions:\n --js ts|babel Process .js files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n");
246
- return [2 /*return*/];
216
+ return [2];
247
217
  });
248
218
  }); };
package/dist/cli/help.js CHANGED
@@ -37,16 +37,10 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
39
  exports.help = exports.run = void 0;
40
- /**
41
- * @internal
42
- */
43
40
  exports.run = function (_) { return __awaiter(void 0, void 0, void 0, function () {
44
41
  return __generator(this, function (_a) {
45
42
  process.stdout.write("\nUsage:\n ts-jest command [options] [...args]\n\nCommands:\n config:init Creates initial Jest configuration\n config:migrate Migrates a given Jest configuration\n help [command] Show this help, or help about a command\n\nExample:\n ts-jest help config:migrate\n");
46
- return [2 /*return*/];
43
+ return [2];
47
44
  });
48
45
  }); };
49
- /**
50
- * @internal
51
- */
52
46
  exports.help = exports.run;
@@ -7,17 +7,15 @@ var definePreset = function (fullName) { return ({
7
7
  return this.isDefault ? 'ts-jest' : fullName;
8
8
  },
9
9
  get label() {
10
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
11
10
  return fullName.split('/').pop();
12
11
  },
13
12
  get jsVarName() {
14
13
  return this.isDefault
15
14
  ? 'defaults'
16
- : // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
15
+ :
17
16
  fullName
18
17
  .split('/')
19
18
  .pop()
20
- // eslint-disable-next-line no-useless-escape
21
19
  .replace(/\-([a-z])/g, function (_, l) { return l.toUpperCase(); });
22
20
  },
23
21
  get value() {
@@ -28,14 +26,10 @@ var definePreset = function (fullName) { return ({
28
26
  return "const { " + this.jsVarName + ": " + varName + " } = require('ts-jest/presets')";
29
27
  },
30
28
  get isDefault() {
31
- return fullName === "ts-jest/presets/default" /* default */;
29
+ return fullName === "ts-jest/presets/default";
32
30
  },
33
31
  }); };
34
- /** @internal */
35
32
  exports.allPresets = {};
36
- /** @internal */
37
- exports.defaults = (exports.allPresets["ts-jest/presets/default" /* default */] = definePreset("ts-jest/presets/default" /* default */));
38
- /** @internal */
39
- exports.jsWithTs = (exports.allPresets["ts-jest/presets/js-with-ts" /* jsWithTs */] = definePreset("ts-jest/presets/js-with-ts" /* jsWithTs */));
40
- /** @internal */
41
- exports.jsWIthBabel = (exports.allPresets["ts-jest/presets/js-with-babel" /* jsWIthBabel */] = definePreset("ts-jest/presets/js-with-babel" /* jsWIthBabel */));
33
+ exports.defaults = (exports.allPresets["ts-jest/presets/default"] = definePreset("ts-jest/presets/default"));
34
+ exports.jsWithTs = (exports.allPresets["ts-jest/presets/js-with-ts"] = definePreset("ts-jest/presets/js-with-ts"));
35
+ exports.jsWIthBabel = (exports.allPresets["ts-jest/presets/js-with-babel"] = definePreset("ts-jest/presets/js-with-babel"));
package/dist/cli/index.js CHANGED
@@ -35,19 +35,22 @@ var __generator = (this && this.__generator) || function (thisArg, body) {
35
35
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
36
  }
37
37
  };
38
+ var __importDefault = (this && this.__importDefault) || function (mod) {
39
+ return (mod && mod.__esModule) ? mod : { "default": mod };
40
+ };
38
41
  var _a;
39
42
  Object.defineProperty(exports, "__esModule", { value: true });
40
43
  exports.processArgv = void 0;
41
44
  var bs_logger_1 = require("bs-logger");
42
- var yargsParser = require("yargs-parser");
43
- var logger_1 = require("../util/logger");
45
+ var yargs_parser_1 = __importDefault(require("yargs-parser"));
46
+ var logger_1 = require("../utils/logger");
44
47
  var VALID_COMMANDS = ['help', 'config:migrate', 'config:init'];
45
48
  var logger = logger_1.rootLogger.child((_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'cli', _a[bs_logger_1.LogContexts.application] = 'ts-jest', _a));
46
49
  function cli(args) {
47
50
  return __awaiter(this, void 0, void 0, function () {
48
51
  var parsedArgv, command, isHelp, _a, run, help, cmd;
49
52
  return __generator(this, function (_b) {
50
- parsedArgv = yargsParser(args, {
53
+ parsedArgv = yargs_parser_1.default(args, {
51
54
  boolean: ['dry-run', 'jest-preset', 'allow-js', 'diff', 'babel', 'force', 'jsdom'],
52
55
  string: ['tsconfig', 'js'],
53
56
  count: ['verbose'],
@@ -62,7 +65,6 @@ function cli(args) {
62
65
  },
63
66
  },
64
67
  });
65
- // deprecated
66
68
  if (parsedArgv.allowJs != null) {
67
69
  if (parsedArgv.js)
68
70
  throw new Error("The 'allowJs' and 'js' options cannot be set together.");
@@ -76,13 +78,10 @@ function cli(args) {
76
78
  command = 'help';
77
79
  _a = require("./" + command.replace(/:/g, '/')), run = _a.run, help = _a.help;
78
80
  cmd = isHelp && command !== 'help' ? help : run;
79
- return [2 /*return*/, cmd(parsedArgv, logger)];
81
+ return [2, cmd(parsedArgv, logger)];
80
82
  });
81
83
  });
82
84
  }
83
- /**
84
- * @internal
85
- */
86
85
  function processArgv() {
87
86
  return __awaiter(this, void 0, void 0, function () {
88
87
  var err_1;
@@ -90,17 +89,17 @@ function processArgv() {
90
89
  switch (_a.label) {
91
90
  case 0:
92
91
  _a.trys.push([0, 2, , 3]);
93
- return [4 /*yield*/, cli(process.argv.slice(2))];
92
+ return [4, cli(process.argv.slice(2))];
94
93
  case 1:
95
94
  _a.sent();
96
95
  process.exit(0);
97
- return [3 /*break*/, 3];
96
+ return [3, 3];
98
97
  case 2:
99
98
  err_1 = _a.sent();
100
99
  logger.fatal(err_1.message);
101
100
  process.exit(1);
102
- return [3 /*break*/, 3];
103
- case 3: return [2 /*return*/];
101
+ return [3, 3];
102
+ case 3: return [2];
104
103
  }
105
104
  });
106
105
  });
@@ -19,23 +19,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
19
19
  exports.createCompilerInstance = void 0;
20
20
  var language_service_1 = require("./language-service");
21
21
  var transpiler_1 = require("./transpiler");
22
- var json_1 = require("../util/json");
23
- /**
24
- * Rely on TypeScript compiled output generation which contains this prefix to point to sourcemap location.
25
- */
22
+ var json_1 = require("../utils/json");
26
23
  var SOURCE_MAPPING_PREFIX = 'sourceMappingURL=';
27
- /**
28
- * Update the output remapping the source map.
29
- */
30
24
  function updateOutput(outputText, normalizedFileName, sourceMap) {
31
25
  var base64Map = Buffer.from(updateSourceMap(sourceMap, normalizedFileName), 'utf8').toString('base64');
32
26
  var sourceMapContent = "data:application/json;charset=utf-8;base64," + base64Map;
33
- // sourceMappingURL= prefix is always at the end of compiledOutput, using lastIndexOf should be the safest way to substring
34
27
  return (outputText.slice(0, outputText.lastIndexOf(SOURCE_MAPPING_PREFIX) + SOURCE_MAPPING_PREFIX.length) + sourceMapContent);
35
28
  }
36
- /**
37
- * Update the source map contents for improved output.
38
- */
39
29
  var updateSourceMap = function (sourceMapText, normalizedFileName) {
40
30
  var sourceMap = JSON.parse(sourceMapText);
41
31
  sourceMap.file = normalizedFileName;
@@ -43,31 +33,21 @@ var updateSourceMap = function (sourceMapText, normalizedFileName) {
43
33
  delete sourceMap.sourceRoot;
44
34
  return json_1.stringify(sourceMap);
45
35
  };
46
- /**
47
- * Compile files which are provided by jest via transform config and cache the result in file system if users run with
48
- * cache mode
49
- */
50
36
  var compileAndUpdateOutput = function (compileFn, logger) { return function (code, fileName, lineOffset) {
51
37
  logger.debug({ fileName: fileName }, 'compileAndUpdateOutput(): get compile output');
52
38
  var _a = __read(compileFn(code, fileName, lineOffset), 2), value = _a[0], sourceMap = _a[1];
53
39
  return updateOutput(value, fileName, sourceMap);
54
40
  }; };
55
- /**
56
- * Register TypeScript compiler instance.
57
- *
58
- * @internal
59
- */
60
41
  exports.createCompilerInstance = function (configs) {
61
42
  var logger = configs.logger.child({ namespace: 'ts-compiler' });
62
43
  var compilerOptions = configs.parsedTsConfig.options, tsJest = configs.tsJest;
63
44
  var extensions = ['.ts', '.tsx'];
64
- // Enable `allowJs` when flag is set.
65
45
  if (compilerOptions.allowJs) {
66
46
  extensions.push('.js');
67
47
  extensions.push('.jsx');
68
48
  }
69
49
  var compilerInstance = !tsJest.isolatedModules
70
- ? language_service_1.initializeLanguageServiceInstance(configs, logger) // Use language services by default
50
+ ? language_service_1.initializeLanguageServiceInstance(configs, logger)
71
51
  : transpiler_1.initializeTranspilerInstance(configs, logger);
72
52
  var compile = compileAndUpdateOutput(compilerInstance.compileFn, logger);
73
53
  return { cwd: configs.cwd, compile: compile, program: compilerInstance.program };
@@ -85,21 +85,16 @@ var path_1 = require("path");
85
85
  var memoize = require("lodash.memoize");
86
86
  var mkdirp = require("mkdirp");
87
87
  var constants_1 = require("../constants");
88
- var messages_1 = require("../util/messages");
89
- var json_1 = require("../util/json");
90
- var sha1_1 = require("../util/sha1");
88
+ var messages_1 = require("../utils/messages");
89
+ var json_1 = require("../utils/json");
90
+ var sha1_1 = require("../utils/sha1");
91
91
  function doTypeChecking(configs, diagnosedFiles, fileName, service, logger) {
92
92
  if (configs.shouldReportDiagnostic(fileName)) {
93
- // Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.
94
93
  var diagnostics = service.getSemanticDiagnostics(fileName).concat(service.getSyntacticDiagnostics(fileName));
95
94
  diagnosedFiles.push(fileName);
96
- // will raise or just warn diagnostics depending on config
97
95
  configs.raiseDiagnostics(diagnostics, fileName, logger);
98
96
  }
99
97
  }
100
- /**
101
- * @internal
102
- */
103
98
  exports.initializeLanguageServiceInstance = function (configs, logger) {
104
99
  var _a;
105
100
  logger.debug('initializeLanguageServiceInstance(): create typescript compiler');
@@ -120,28 +115,23 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
120
115
  };
121
116
  var tsResolvedModulesCachePath;
122
117
  if (cacheDir) {
123
- // Make sure the cache directory exists before continuing.
124
118
  mkdirp.sync(cacheDir);
125
119
  tsResolvedModulesCachePath = path_1.join(cacheDir, sha1_1.sha1('ts-jest-resolved-modules', '\x00'));
126
120
  try {
127
- /* istanbul ignore next (already covered with unit test) */
128
121
  var cachedTSResolvedModules = fs_1.readFileSync(tsResolvedModulesCachePath, 'utf-8');
129
122
  memoryCache.resolvedModules = new Map(json_1.parse(cachedTSResolvedModules));
130
123
  }
131
124
  catch (e) { }
132
125
  }
133
- // Initialize memory cache for typescript compiler
134
126
  configs.parsedTsConfig.fileNames.forEach(function (fileName) {
135
127
  memoryCache.files.set(fileName, {
136
128
  version: 0,
137
129
  });
138
130
  });
139
131
  function isFileInCache(fileName) {
140
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
141
132
  return memoryCache.files.has(fileName) && memoryCache.files.get(fileName).version !== 0;
142
133
  }
143
134
  var cacheReadFile = logger.wrap(serviceHostTraceCtx, 'readFile', memoize(ts.sys.readFile));
144
- /* istanbul ignore next */
145
135
  var moduleResolutionHost = {
146
136
  fileExists: memoize(ts.sys.fileExists),
147
137
  readFile: cacheReadFile,
@@ -169,8 +159,6 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
169
159
  });
170
160
  }
171
161
  var projectVersion = 1;
172
- // Set the file contents into cache.
173
- /* istanbul ignore next (cover by e2e) */
174
162
  var updateMemoryCache = function (contents, fileName) {
175
163
  logger.debug({ fileName: fileName }, 'updateMemoryCache(): update memory cache for language service');
176
164
  var shouldIncrementProjectVersion = false;
@@ -183,22 +171,15 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
183
171
  shouldIncrementProjectVersion = true;
184
172
  }
185
173
  else {
186
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
187
174
  var previousContents = memoryCache.files.get(fileName).text;
188
- // Avoid incrementing cache when nothing has changed.
189
175
  if (previousContents !== contents) {
190
176
  memoryCache.files.set(fileName, {
191
177
  text: contents,
192
178
  version: memoryCache.files.get(fileName).version + 1,
193
179
  });
194
- // Only bump project version when file is modified in cache, not when discovered for the first time
195
180
  if (hit)
196
181
  shouldIncrementProjectVersion = true;
197
182
  }
198
- /**
199
- * When a file is from node_modules or referenced to a referenced project and jest wants to transform it, we need
200
- * to make sure that the Program is updated with this information
201
- */
202
183
  if (!fileNames.includes(fileName)) {
203
184
  shouldIncrementProjectVersion = true;
204
185
  }
@@ -213,11 +194,6 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
213
194
  var _a;
214
195
  var normalizedFileName = path_1.normalize(fileName);
215
196
  var version = (_a = memoryCache.files.get(normalizedFileName)) === null || _a === void 0 ? void 0 : _a.version;
216
- // We need to return `undefined` and not a string here because TypeScript will use
217
- // `getScriptVersion` and compare against their own version - which can be `undefined`.
218
- // If we don't return `undefined` it results in `undefined === "undefined"` and run
219
- // `createProgram` again (which is very slow). Using a `string` assertion here to avoid
220
- // TypeScript errors from the function signature (expects `(x: string) => string`).
221
197
  return version === undefined ? undefined : String(version);
222
198
  },
223
199
  getScriptSnapshot: function (fileName) {
@@ -225,7 +201,6 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
225
201
  var normalizedFileName = path_1.normalize(fileName);
226
202
  var hit = isFileInCache(normalizedFileName);
227
203
  logger.trace({ normalizedFileName: normalizedFileName, cacheHit: hit }, 'getScriptSnapshot():', 'cache', hit ? 'hit' : 'miss');
228
- // Read contents from TypeScript memory cache.
229
204
  if (!hit) {
230
205
  memoryCache.files.set(normalizedFileName, {
231
206
  text: cacheReadFile(normalizedFileName),
@@ -257,47 +232,33 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
257
232
  var e_1, _a;
258
233
  var _b;
259
234
  logger.debug({ fileName: fileName }, 'compileFn(): compiling using language service');
260
- // Must set memory cache before attempting to compile
261
235
  updateMemoryCache(code, fileName);
262
236
  var output = service.getEmitOutput(fileName);
263
- /* istanbul ignore next */
264
237
  if (tsResolvedModulesCachePath) {
265
- // Cache resolved modules to disk so next run can reuse it
266
238
  void (function () { return __awaiter(void 0, void 0, void 0, function () {
267
239
  return __generator(this, function (_a) {
268
240
  switch (_a.label) {
269
- case 0:
270
- // eslint-disable-next-line @typescript-eslint/await-thenable
271
- return [4 /*yield*/, fs_1.writeFile(tsResolvedModulesCachePath, json_1.stringify(__spread(memoryCache.resolvedModules)), function () { })];
241
+ case 0: return [4, fs_1.writeFile(tsResolvedModulesCachePath, json_1.stringify(__spread(memoryCache.resolvedModules)), function () { })];
272
242
  case 1:
273
- // eslint-disable-next-line @typescript-eslint/await-thenable
274
243
  _a.sent();
275
- return [2 /*return*/];
244
+ return [2];
276
245
  }
277
246
  });
278
247
  }); })();
279
248
  }
280
- /**
281
- * There might be a chance that test files are type checked even before jest executes them, we don't need to do
282
- * type check again
283
- */
284
249
  if (!diagnosedFiles.includes(fileName)) {
285
250
  logger.debug({ fileName: fileName }, 'compileFn(): computing diagnostics using language service');
286
251
  doTypeChecking(configs, diagnosedFiles, fileName, service, logger);
287
252
  }
288
- /* istanbul ignore next (already covered with unit tests) */
289
253
  if (!configs.isTestFile(fileName)) {
290
254
  try {
291
255
  for (var _c = __values(memoryCache.resolvedModules.entries()), _d = _c.next(); !_d.done; _d = _c.next()) {
292
256
  var _e = __read(_d.value, 2), testFileName = _e[0], resolvedModules = _e[1];
293
- // Only do type checking for test files which haven't been type checked before as well as the file must exist
294
257
  if (resolvedModules.includes(fileName) &&
295
258
  !diagnosedFiles.includes(testFileName) &&
296
259
  fs_1.existsSync(testFileName)) {
297
260
  var testFileContent = (_b = memoryCache.files.get(testFileName)) === null || _b === void 0 ? void 0 : _b.text;
298
261
  if (!testFileContent) {
299
- // Must set memory cache before attempting to get diagnostics
300
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
301
262
  updateMemoryCache(cacheReadFile(testFileName), testFileName);
302
263
  }
303
264
  logger.debug({ testFileName: testFileName }, 'compileFn(): computing diagnostics using language service for test file which uses the module');
@@ -313,13 +274,11 @@ exports.initializeLanguageServiceInstance = function (configs, logger) {
313
274
  finally { if (e_1) throw e_1.error; }
314
275
  }
315
276
  }
316
- /* istanbul ignore next (this should never happen but is kept for security) */
317
277
  if (output.emitSkipped) {
318
278
  throw new TypeError(path_1.relative(cwd, fileName) + ": Emit skipped for language service");
319
279
  }
320
- // Throw an error when requiring `.d.ts` files.
321
280
  if (!output.outputFiles.length) {
322
- throw new TypeError(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}}`." /* UnableToRequireDefinitionFile */, {
281
+ throw new TypeError(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}}`.", {
323
282
  file: path_1.basename(fileName),
324
283
  }));
325
284
  }
@@ -1,14 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.initializeTranspilerInstance = void 0;
4
- /**
5
- * @internal
6
- */
7
4
  exports.initializeTranspilerInstance = function (configs, logger) {
8
5
  logger.debug('initializeTranspilerInstance(): create typescript compiler');
9
- var _a = configs.parsedTsConfig, options = _a.options, fileNames = _a.fileNames;
6
+ var options = configs.parsedTsConfig.options;
10
7
  var ts = configs.compilerModule;
11
- var program = ts.createProgram(fileNames, options);
12
8
  return {
13
9
  compileFn: function (code, fileName) {
14
10
  logger.debug({ fileName: fileName }, 'compileFn(): compiling as isolated module');
@@ -21,9 +17,8 @@ exports.initializeTranspilerInstance = function (configs, logger) {
21
17
  if (result.diagnostics && configs.shouldReportDiagnostic(fileName)) {
22
18
  configs.raiseDiagnostics(result.diagnostics, fileName, logger);
23
19
  }
24
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
25
20
  return [result.outputText, result.sourceMapText];
26
21
  },
27
- program: program,
22
+ program: undefined,
28
23
  };
29
24
  };