-
Notifications
You must be signed in to change notification settings - Fork 453
/
ts-jest-transformer.ts
189 lines (167 loc) · 6.54 KB
/
ts-jest-transformer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { CacheKeyOptions, TransformOptions, TransformedSource, Transformer } from '@jest/transform'
import { Config } from '@jest/types'
import { Logger } from 'bs-logger'
import { inspect } from 'util'
import { ConfigSet } from './config/config-set'
import { JS_JSX_REGEX, TS_TSX_REGEX } from './constants'
import { TsJestGlobalOptions } from './types'
import { stringify } from './util/json'
import { JsonableValue } from './util/jsonable-value'
import { rootLogger } from './util/logger'
import { Errors, interpolate } from './util/messages'
import { sha1 } from './util/sha1'
const INSPECT_CUSTOM = inspect.custom || 'inspect'
interface ConfigSetIndexItem {
configSet: ConfigSet
jestConfig: JsonableValue<Config.ProjectConfig>
}
export class TsJestTransformer implements Transformer {
/**
* @internal
*/
private static readonly _configSetsIndex: ConfigSetIndexItem[] = []
/**
* @internal
*/
private static _lastTransformerId = 0
/**
* @internal
*/
private static get _nextTransformerId() {
return ++TsJestTransformer._lastTransformerId
}
private readonly logger: Logger
private readonly id: number
private readonly options: TsJestGlobalOptions
constructor(baseOptions: TsJestGlobalOptions = {}) {
this.options = { ...baseOptions }
this.id = TsJestTransformer._nextTransformerId
this.logger = rootLogger.child({
transformerId: this.id,
namespace: 'jest-transformer',
})
this.logger.debug({ baseOptions }, 'created new transformer')
}
/**
* @internal
*/
/* istanbul ignore next */
[INSPECT_CUSTOM]() {
return `[object TsJestTransformer<#${this.id}>]`
}
/**
* Use by e2e, don't mark as internal
*/
configsFor(jestConfig: Config.ProjectConfig): ConfigSet {
let csi: ConfigSetIndexItem | undefined = TsJestTransformer._configSetsIndex.find(
cs => cs.jestConfig.value === jestConfig,
)
if (csi) return csi.configSet
// try to look-it up by stringified version
const serialized = stringify(jestConfig)
csi = TsJestTransformer._configSetsIndex.find(cs => cs.jestConfig.serialized === serialized)
if (csi) {
// update the object so that we can find it later
// this happens because jest first calls getCacheKey with stringified version of
// the config, and then it calls the transformer with the proper object
csi.jestConfig.value = jestConfig
return csi.configSet
}
const jestConfigObj: Config.ProjectConfig = jestConfig
// create the new record in the index
this.logger.info(`no matching config-set found, creating a new one`)
const configSet = new ConfigSet(jestConfigObj, this.options, this.logger)
TsJestTransformer._configSetsIndex.push({
jestConfig: new JsonableValue(jestConfigObj),
configSet,
})
return configSet
}
process(
input: string,
filePath: Config.Path,
jestConfig: Config.ProjectConfig,
transformOptions?: TransformOptions,
): TransformedSource | string {
this.logger.debug({ fileName: filePath, transformOptions }, 'processing', filePath)
let result: string | TransformedSource
const source: string = input
const configs = this.configsFor(jestConfig)
const { hooks } = configs
const stringify = configs.shouldStringifyContent(filePath)
const babelJest = stringify ? undefined : configs.babelJestTransformer
const isDefinitionFile = filePath.endsWith('.d.ts')
const isJsFile = JS_JSX_REGEX.test(filePath)
const isTsFile = !isDefinitionFile && TS_TSX_REGEX.test(filePath)
if (stringify) {
// handles here what we should simply stringify
result = `module.exports=${JSON.stringify(source)}`
} else if (isDefinitionFile) {
// do not try to compile declaration files
result = ''
} else if (!configs.typescript.options.allowJs && isJsFile) {
// we've got a '.js' but the compiler option `allowJs` is not set or set to false
this.logger.warn({ fileName: filePath }, interpolate(Errors.GotJsFileButAllowJsFalse, { path: filePath }))
result = source
} else if (isJsFile || isTsFile) {
// transpile TS code (source maps are included)
/* istanbul ignore if */
result = configs.tsCompiler.compile(source, filePath)
} else {
// we should not get called for files with other extension than js[x], ts[x] and d.ts,
// TypeScript will bail if we try to compile, and if it was to call babel, users can
// define the transform value with `babel-jest` for this extension instead
const message = babelJest ? Errors.GotUnknownFileTypeWithBabel : Errors.GotUnknownFileTypeWithoutBabel
this.logger.warn({ fileName: filePath }, interpolate(message, { path: filePath }))
result = source
}
// calling babel-jest transformer
if (babelJest) {
this.logger.debug({ fileName: filePath }, 'calling babel-jest processor')
// do not instrument here, jest will do it anyway afterwards
result = babelJest.process(result, filePath, jestConfig, { ...transformOptions, instrument: false })
}
// allows hooks (useful for testing)
if (hooks.afterProcess) {
this.logger.debug({ fileName: filePath, hookName: 'afterProcess' }, 'calling afterProcess hook')
const newResult = hooks.afterProcess([input, filePath, jestConfig, transformOptions], result)
if (newResult !== undefined) {
return newResult
}
}
return result
}
/**
* Jest uses this to cache the compiled version of a file
*
* @see https://github.com/facebook/jest/blob/v23.5.0/packages/jest-runtime/src/script_transformer.js#L61-L90
* @param fileContent The content of the file
* @param filePath The full path to the file
* @param _jestConfigStr The JSON-encoded version of jest config
* @param transformOptions
* @param transformOptions.instrument Whether the content will be instrumented by our transformer (always false)
* @param transformOptions.rootDir Jest current rootDir
*/
getCacheKey(
fileContent: string,
filePath: string,
_jestConfigStr: string,
transformOptions: CacheKeyOptions,
): string {
this.logger.debug({ fileName: filePath, transformOptions }, 'computing cache key for', filePath)
const configs = this.configsFor(transformOptions.config)
// we do not instrument, ensure it is false all the time
const { instrument = false, rootDir = configs.rootDir } = transformOptions
return sha1(
configs.cacheKey,
'\x00',
rootDir,
'\x00',
`instrument:${instrument ? 'on' : 'off'}`,
'\x00',
fileContent,
'\x00',
filePath,
)
}
}