1
1
import { posix , sep } from 'path' ;
2
-
3
- const isWindowsPlatform = sep === '\\' ;
2
+ import { dirname } from '@sentry/utils' ;
4
3
5
4
/** normalizes Windows paths */
6
5
function normalizeWindowsPath ( path : string ) : string {
@@ -9,52 +8,62 @@ function normalizeWindowsPath(path: string): string {
9
8
. replace ( / \\ / g, '/' ) ; // replace all `\` instances with `/`
10
9
}
11
10
11
+ // We cache this so we don't have to recompute it
12
+ let basePath : string | undefined ;
13
+
14
+ function getBasePath ( ) : string {
15
+ if ( ! basePath ) {
16
+ const baseDir =
17
+ require && require . main && require . main . filename ? dirname ( require . main . filename ) : global . process . cwd ( ) ;
18
+ basePath = `${ baseDir } /` ;
19
+ }
20
+
21
+ return basePath ;
22
+ }
23
+
12
24
/** Gets the module from a filename */
13
25
export function getModuleFromFilename (
14
26
filename : string | undefined ,
15
- normalizeWindowsPathSeparator : boolean = isWindowsPlatform ,
27
+ basePath : string = getBasePath ( ) ,
28
+ isWindows : boolean = sep === '\\' ,
16
29
) : string | undefined {
17
30
if ( ! filename ) {
18
31
return ;
19
32
}
20
33
21
- const normalizedFilename = normalizeWindowsPathSeparator ? normalizeWindowsPath ( filename ) : filename ;
34
+ const normalizedBase = isWindows ? normalizeWindowsPath ( basePath ) : basePath ;
35
+ const normalizedFilename = isWindows ? normalizeWindowsPath ( filename ) : filename ;
22
36
23
37
// eslint-disable-next-line prefer-const
24
- let { root, dir, base : basename , ext } = posix . parse ( normalizedFilename ) ;
25
-
26
- const base = ( require && require . main && require . main . filename && dir ) || global . process . cwd ( ) ;
27
-
28
- const normalizedBase = `${ base } /` ;
29
-
30
- // It's specifically a module
31
- let file = basename ;
38
+ let { dir, base : file , ext } = posix . parse ( normalizedFilename ) ;
32
39
33
40
if ( ext === '.js' || ext === '.mjs' || ext === '.cjs' ) {
34
41
file = file . slice ( 0 , ext . length * - 1 ) ;
35
42
}
36
43
37
- if ( ! root && ! dir ) {
44
+ if ( ! dir ) {
38
45
// No dirname whatsoever
39
46
dir = '.' ;
40
47
}
41
48
42
- let n = dir . lastIndexOf ( '/node_modules/ ' ) ;
49
+ let n = dir . lastIndexOf ( '/node_modules' ) ;
43
50
if ( n > - 1 ) {
44
- // /node_modules/ is 14 chars
45
51
return `${ dir . slice ( n + 14 ) . replace ( / \/ / g, '.' ) } :${ file } ` ;
46
52
}
53
+
47
54
// Let's see if it's a part of the main module
48
55
// To be a part of main module, it has to share the same base
49
56
n = `${ dir } /` . lastIndexOf ( normalizedBase , 0 ) ;
50
-
51
57
if ( n === 0 ) {
52
58
let moduleName = dir . slice ( normalizedBase . length ) . replace ( / \/ / g, '.' ) ;
59
+
53
60
if ( moduleName ) {
54
61
moduleName += ':' ;
55
62
}
56
63
moduleName += file ;
64
+
57
65
return moduleName ;
58
66
}
67
+
59
68
return file ;
60
69
}
0 commit comments