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