8000 fix(node): Correctly handle Windows paths when resolving module name … · pulse00/sentry-javascript@1182e71 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1182e71

Browse files
authored
fix(node): Correctly handle Windows paths when resolving module name (getsentry#5476)
1 parent 7d44301 commit 1182e71

File tree

2 files changed

+44
-5
lines changed

2 files changed

+44
-5
lines changed

packages/node/src/module.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,29 @@
11
import { basename, dirname } from '@sentry/utils';
22

3+
/** normalizes Windows paths */
4+
function normalizePath(path: string): string {
5+
return path
6+
.replace(/^[A-Z]:/, '') // remove Windows-style prefix
7+
.replace(/\\/g, '/'); // replace all `\` instances with `/`
8+
}
9+
310
/** Gets the module from a filename */
411
export function getModule(filename: string | undefined): string | undefined {
512
if (!filename) {
613
return;
714
}
815

16+
const normalizedFilename = normalizePath(filename);
17+
918
// We could use optional chaining here but webpack does like that mixed with require
10-
const base = `${
11-
(require && require.main && require.main.filename && dirname(require.main.filename)) || global.process.cwd()
12-
}/`;
19+
const base = normalizePath(
20+
`${(require && require.main && require.main.filename && dirname(require.main.filename)) || global.process.cwd()}/`,
21+
);
1322

1423
// It's specifically a module
15-
const file = basename(filename, '.js');
24+
const file = basename(normalizedFilename, '.js');
1625

17-
const path = dirname(filename);
26+
const path = dirname(normalizedFilename);
1827
let n = path.lastIndexOf('/node_modules/');
1928
if (n > -1) {
2029
// /node_modules/ is 14 chars

packages/node/test/module.test.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { getModule } from '../src/module';
2+
3+
function withFilename(fn: () => void, filename: string) {
4+
const prevFilename = require.main?.filename;
5+
if (require.main?.filename) {
6+
require.main.filename = filename;
7+
}
8+
9+
try {
10+
fn();
11+
} finally {
12+
if (require.main && prevFilename) {
13+
require.main.filename = prevFilename;
14+
}
15+
}
16+
}
17+
18+
describe('getModule', () => {
19+
test('Windows', () => {
20+
withFilename(() => {
21+
expect(getModule('C:\\Users\\users\\Tim\\Desktop\\node_modules\\module.js')).toEqual('module');
22+
}, 'C:\\Users\\Tim\\app.js');
23+
});
24+
25+
test('POSIX', () => {
26+
withFilename(() => {
27+
expect(getModule('/Users/users/Tim/Desktop/node_modules/module.js')).toEqual('module');
28+
}, '/Users/Tim/app.js');
29+
});
30+
});

0 commit comments

Comments
 (0)
0