1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const fs = require("fs");
|
4 | const path = require("path");
|
5 | const debug_1 = require("./debug");
|
6 | const util_1 = require("./util");
|
7 | const tsconfigs = {};
|
8 | const rootDirs = [];
|
9 | const typeRoots = [`${__dirname}/../node_modules/@types`];
|
10 | const debug = debug_1.default();
|
11 | function registerTSNode(root) {
|
12 | if (tsconfigs[root])
|
13 | return;
|
14 | const tsconfig = loadTSConfig(root);
|
15 | if (!tsconfig)
|
16 | return;
|
17 | debug('registering ts-node at', root);
|
18 | const tsNodePath = require.resolve('ts-node', { paths: [root, __dirname] });
|
19 | const tsNode = require(tsNodePath);
|
20 | tsconfigs[root] = tsconfig;
|
21 | typeRoots.push(`${root}/node_modules/@types`);
|
22 | if (tsconfig.compilerOptions.rootDirs) {
|
23 | rootDirs.push(...tsconfig.compilerOptions.rootDirs.map(r => path.join(root, r)));
|
24 | }
|
25 | else {
|
26 | rootDirs.push(`${root}/src`);
|
27 | }
|
28 | const cwd = process.cwd();
|
29 | try {
|
30 | process.chdir(root);
|
31 | tsNode.register({
|
32 | skipProject: true,
|
33 | transpileOnly: true,
|
34 |
|
35 |
|
36 | compilerOptions: {
|
37 | target: tsconfig.compilerOptions.target || 'es2017',
|
38 | module: 'commonjs',
|
39 | sourceMap: true,
|
40 | rootDirs,
|
41 | typeRoots,
|
42 | }
|
43 | });
|
44 | }
|
45 | finally {
|
46 | process.chdir(cwd);
|
47 | }
|
48 | }
|
49 | function loadTSConfig(root) {
|
50 | try {
|
51 |
|
52 |
|
53 | const tsconfigPath = path.join(root, 'tsconfig.json');
|
54 | const tsconfig = util_1.loadJSONSync(tsconfigPath);
|
55 | if (!tsconfig || !tsconfig.compilerOptions)
|
56 | return;
|
57 | return tsconfig;
|
58 | }
|
59 | catch (err) {
|
60 | if (err.code !== 'ENOENT')
|
61 | throw err;
|
62 | }
|
63 | }
|
64 | function tsPath(root, orig) {
|
65 | if (!orig)
|
66 | return orig;
|
67 | orig = path.join(root, orig);
|
68 | try {
|
69 | registerTSNode(root);
|
70 | const tsconfig = tsconfigs[root];
|
71 | if (!tsconfig)
|
72 | return orig;
|
73 | const { rootDir, rootDirs, outDir } = tsconfig.compilerOptions;
|
74 | const rootDirPath = rootDir || (rootDirs || [])[0];
|
75 | if (!rootDirPath || !outDir)
|
76 | return orig;
|
77 |
|
78 | const lib = path.join(root, outDir);
|
79 | const src = path.join(root, rootDirPath);
|
80 | const relative = path.relative(lib, orig);
|
81 | const out = path.join(src, relative);
|
82 |
|
83 |
|
84 |
|
85 |
|
86 |
|
87 | if (fs.existsSync(out) || fs.existsSync(out + '.ts'))
|
88 | return out;
|
89 | else
|
90 | return orig;
|
91 | }
|
92 | catch (err) {
|
93 | debug(err);
|
94 | return orig;
|
95 | }
|
96 | }
|
97 | exports.tsPath = tsPath;
|