Skip to content

Commit 768c401

Browse files
committed
Fix #1004
1 parent 5a316c9 commit 768c401

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

src/bin.ts

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import Module = require('module')
77
import arg = require('arg')
88
import { diffLines } from 'diff'
99
import { Script } from 'vm'
10-
import { readFileSync, statSync } from 'fs'
10+
import { readFileSync, statSync, realpathSync } from 'fs'
1111
import { homedir } from 'os'
1212
import { VERSION, TSError, parse, Register, register } from './index'
1313

@@ -154,6 +154,7 @@ export function main (argv: string[]) {
154154
}
155155

156156
const cwd = dir || process.cwd()
157+
/** Unresolved. May point to a symlink, not realpath. May be missing file extension */
157158
const scriptPath = args._.length ? resolve(cwd, args._[0]) : undefined
158159
const state = new EvalState(scriptPath || join(cwd, EVAL_FILENAME))
159160

@@ -251,7 +252,21 @@ function getCwd (dir?: string, scriptMode?: boolean, scriptPath?: string) {
251252
throw new TypeError('Script mode cannot be combined with `--dir`')
252253
}
253254

254-
return dirname(scriptPath)
255+
// Use node's own resolution behavior to ensure we follow symlinks
256+
// This may affect which tsconfig we discover
257+
// This happens before we are registered, so tell node's resolver to consider .ts and tsx files
258+
// TODO in extremely rare cases, if a foo.js and foo.ts both exist, we may follow the wrong one,
259+
// because we are not obeying `--prefer-ts-exts`
260+
const hadTsExt = hasOwnProperty(require.extensions, '.ts') // tslint:disable-line
261+
const hadTsxExt = hasOwnProperty(require.extensions, '.tsx') // tslint:disable-line
262+
try {
263+
if(!hadTsExt) require.extensions['.ts'] = function() {} // tslint:disable-line
264+
if(!hadTsxExt) require.extensions['.tsx'] = function() {} // tslint:disable-line
265+
return dirname(require.resolve(scriptPath))
266+
} finally {
267+
if(!hadTsExt) delete require.extensions['.ts'] // tslint:disable-line
268+
if(!hadTsxExt) delete require.extensions['.tsx'] // tslint:disable-line
269+
}
255270
}
256271

257272
return dir
@@ -481,6 +496,11 @@ function isRecoverable (error: TSError) {
481496
return error.diagnosticCodes.every(code => RECOVERY_CODES.has(code))
482497
}
483498

499+
/** Safe `hasOwnProperty` */
500+
function hasOwnProperty (object: any, property: string): boolean {
501+
return Object.prototype.hasOwnProperty.call(object, property)
502+
}
503+
484504
if (require.main === module) {
485505
main(process.argv.slice(2))
486506
}

0 commit comments

Comments
 (0)