/
paths-to-module-name-mapper.ts
48 lines (41 loc) · 1.78 KB
/
paths-to-module-name-mapper.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
import { Config } from '@jest/types'
import { LogContexts } from 'bs-logger'
import { CompilerOptions } from 'typescript'
import { rootLogger } from '../util/logger'
import { Errors, interpolate } from '../util/messages'
type TsPathMapping = Exclude<CompilerOptions['paths'], undefined>
type JestPathMapping = Config.InitialOptions['moduleNameMapper']
// we don't need to escape all chars, so commented out is the real one
// const escapeRegex = (str: string) => str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
const escapeRegex = (str: string) => str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&')
const logger = rootLogger.child({ [LogContexts.namespace]: 'path-mapper' })
export const pathsToModuleNameMapper = (
mapping: TsPathMapping,
{ prefix = '' }: { prefix?: string } = {},
): JestPathMapping => {
const jestMap: JestPathMapping = {}
for (const fromPath of Object.keys(mapping)) {
let pattern: string
const toPaths = mapping[fromPath]
// check that we have only one target path
if (toPaths.length === 0) {
logger.warn(interpolate(Errors.NotMappingPathWithEmptyMap, { path: fromPath }))
continue
}
// split with '*'
const segments = fromPath.split(/\*/g)
if (segments.length === 1) {
const paths = toPaths.map((target) => `${prefix}${target}`)
pattern = `^${escapeRegex(fromPath)}$`
jestMap[pattern] = paths.length === 1 ? paths[0] : paths
} else if (segments.length === 2) {
const paths = toPaths.map((target) => `${prefix}${target.replace(/\*/g, '$1')}`)
pattern = `^${escapeRegex(segments[0])}(.*)${escapeRegex(segments[1])}$`
jestMap[pattern] = paths.length === 1 ? paths[0] : paths
} else {
logger.warn(interpolate(Errors.NotMappingMultiStarPath, { path: fromPath }))
continue
}
}
return jestMap
}