UNPKG

2.89 kBJavaScriptView Raw
1(function() {
2 var fs = require('fs');
3 var path = require('path');
4 var _ = require('underscore');
5
6 var tsDir = path.join(__dirname, '/node_modules/typescript/');
7 var tsBinDir = path.join(tsDir, 'bin');
8 var version = JSON.parse(fs.readFileSync(path.join(tsDir, 'package.json'))).version;
9 var targetFile = path.join(__dirname, '/tsc-' + version + '-wrapped.tmp');
10
11 if (!fs.existsSync(targetFile)) {
12 var srcFile = path.join(tsBinDir, 'tsc.js');
13 var tscSource = fs.readFileSync(srcFile, 'utf8');
14
15 // Remove all the "executable" lines at the end of the file
16 // eg. var batchCompiler = new BatchCompiler(IO);
17 // batchCompiler.batchCompile();
18 var lines = tscSource.split(/[\n\r]+/);
19 var i = lines.length - 1;
20 while (lines[i].indexOf('}') !== 0) {
21 i--;
22 }
23 var tscSourceWithoutLastLines = lines.slice(0, i + 1).join('\n');
24
25 // Create a new file, wrapping the original in a closure
26 var content = "(function() { \n";
27 content += tscSourceWithoutLastLines;
28 content += "\n\n";
29
30 // Export the base TypeScript module and
31 // IO and BatchCompiler to expose the command line
32 // compiler
33 content += 'module.exports = TypeScript;\n\n';
34 content += 'module.exports.IO = IO;\n\n';
35 content += 'module.exports.BatchCompiler = TypeScript.BatchCompiler;\n\n';
36 content += '})();\n';
37
38 fs.writeFileSync(targetFile, content, 'utf8');
39 }
40
41 module.exports = require(targetFile);
42 module.exports.libdPath = path.join(tsBinDir, 'lib.d.ts');
43
44 var IO = module.exports.IO;
45 var BatchCompiler = module.exports.BatchCompiler;
46
47 module.exports.compile = function (files, tscArgs, onError) {
48 var newArgs;
49 var noLib = '--noLib';
50
51 if(typeof tscArgs == "string")
52 newArgs = tscArgs.split(' ');
53 else
54 newArgs = tscArgs || [];
55
56 if (newArgs.indexOf(noLib) < 0) {
57 newArgs.push(noLib);
58 newArgs.push(module.exports.libdPath);
59 }
60
61 newArgs = newArgs.concat(files);
62
63 var io = _.extend({}, IO, { arguments: newArgs });
64
65 var exitCode;
66
67 io.quit = function(code) {
68 exitCode = code;
69 };
70
71 if (onError) {
72 function wrapWithCallback(fn, includesNewline) {
73 var original = fn;
74 return function (str) {
75 if (onError(str) !== false) {
76 original(str);
77 }
78 };
79 }
80
81 io.stderr.Write = wrapWithCallback(io.stderr.Write);
82 io.stderr.WriteLine = wrapWithCallback(io.stderr.WriteLine);
83 }
84
85 new BatchCompiler(io).batchCompile();
86 return exitCode;
87 };
88})();
\No newline at end of file