forked from TypeStrong/ts-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypescript-node.ts
More file actions
236 lines (196 loc) · 6.42 KB
/
typescript-node.ts
File metadata and controls
236 lines (196 loc) · 6.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
import * as TS from 'typescript'
import tsconfig = require('tsconfig')
import { resolve, relative, extname, basename, isAbsolute } from 'path'
import { readFileSync, statSync } from 'fs'
import { EOL } from 'os'
import { BaseError } from 'make-error'
import sourceMapSupport = require('source-map-support')
import extend = require('xtend')
import arrify = require('arrify')
import chalk = require('chalk')
/**
* Export the current version.
*/
export const VERSION = '0.1.3'
/**
* Extensions to compile using TypeScript.
*/
export const EXTENSIONS = ['.ts', '.tsx']
/**
* Registration options.
*/
export interface Options {
compiler?: string
configFile?: string
ignoreWarnings?: string[]
isEval?: boolean
ignoreAll?: boolean
getFile?: (fileName: string) => string
getVersion?: (fileName: string) => string
}
/**
* Load TypeScript configuration.
*/
function readConfig (fileName: string, ts: typeof TS) {
const config = fileName ? tsconfig.readFileSync(fileName) : {
files: [],
compilerOptions: {}
}
config.compilerOptions = extend({
target: 'es5'
}, config.compilerOptions, {
module: 'commonjs',
sourceMap: true,
inlineSourceMap: false,
inlineSources: false,
declaration: false
})
return ts.parseConfigFile(config, ts.sys, fileName)
}
/**
* Register TypeScript compiler.
*/
export function register (opts?: Options) {
const cwd = process.cwd()
const options = extend({ getFile, getVersion }, opts)
const files: { [fileName: string]: boolean } = {}
// Enable compiler overrides.
options.compiler = options.compiler || 'typescript'
options.ignoreWarnings = arrify(options.ignoreWarnings)
// Resolve configuration file options.
options.configFile = options.configFile ?
resolve(cwd, options.configFile) :
tsconfig.resolveSync(cwd)
const ts: typeof TS = require(options.compiler)
const config = readConfig(options.configFile, ts)
// Render the configuration errors and exit the script.
if (!options.ignoreAll && config.errors.length) {
console.error(formatDiagnostics(config.errors, ts))
process.exit(1)
}
const serviceHost: TS.LanguageServiceHost = {
getScriptFileNames: () => config.fileNames.concat(Object.keys(files)),
getScriptVersion: options.getVersion,
getScriptSnapshot (fileName): TS.IScriptSnapshot {
const contents = options.getFile(fileName)
return contents ? ts.ScriptSnapshot.fromString(contents) : undefined
},
getNewLine: () => EOL,
getCurrentDirectory: () => cwd,
getCompilationSettings: () => config.options,
getDefaultLibFileName: (options) => ts.getDefaultLibFilePath(config.options)
}
const service = ts.createLanguageService(serviceHost)
// Install source map support and read from cache.
sourceMapSupport.install({
retrieveFile (fileName) {
if (files[fileName]) {
return getOutput(fileName)
}
}
})
function getOutput (fileName: string) {
const output = service.getEmitOutput(fileName)
const result = output.outputFiles[1].text
const sourceText = service.getSourceFile(fileName).text
const sourceMapText = output.outputFiles[0].text
const sourceMapFileName = output.outputFiles[0].name
const sourceMap = getSourceMap(sourceMapText, fileName, sourceText)
const base64SourceMapText = new Buffer(sourceMap).toString('base64')
return result
.replace(
'//# sourceMappingURL=' + basename(sourceMapFileName),
`//# sourceMappingURL=data:application/json;base64,${base64SourceMapText}`
)
}
function compile (fileName: string) {
// Add to the `files` object before compiling - otherwise our file will
// not found (unless it's in our `tsconfig.json` file).
files[fileName] = true
const diagnostics = getDiagnostics(service, fileName, options)
if (!options.ignoreAll && diagnostics.length) {
const message = formatDiagnostics(diagnostics, ts)
if (options.isEval) {
throw new TypeScriptError(message)
}
console.error(message)
process.exit(1)
}
return getOutput(fileName)
}
function loader (m: any, fileName: string) {
return m._compile(compile(fileName), fileName)
}
// Attach the loader to each defined extension.
EXTENSIONS.forEach(function (extension) {
require.extensions[extension] = loader
})
return compile
}
/**
* Get the file version using the mod time.
*/
export function getVersion (fileName: string): string {
return String(statSync(fileName).mtime.getTime())
}
/**
* Get the file from the file system.
*/
export function getFile (fileName: string): string {
try {
return readFileSync(fileName, 'utf8')
} catch (err) {}
}
/**
* Get file diagnostics from a TypeScript language service.
*/
export function getDiagnostics (service: TS.LanguageService, fileName: string, options: Options) {
return service.getCompilerOptionsDiagnostics()
.concat(service.getSyntacticDiagnostics(fileName))
.concat(service.getSemanticDiagnostics(fileName))
.filter(function (diagnostic) {
return options.ignoreWarnings.indexOf(String(diagnostic.code)) === -1
})
}
/**
* Format a diagnostic object into a string.
*/
export function formatDiagnostic (diagnostic: TS.Diagnostic, ts: typeof TS, cwd: string = '.'): string {
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')
if (diagnostic.file) {
const path = relative(cwd, diagnostic.file.fileName)
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start)
return `${path} (${line + 1},${character + 1}): ${message} (${diagnostic.code})`
}
return `${message} (${diagnostic.code})`
}
/**
* Format diagnostics into friendlier errors.
*/
function formatDiagnostics (diagnostics: TS.Diagnostic[], ts: typeof TS) {
const boundary = chalk.grey('----------------------------------')
return [
boundary,
chalk.red.bold('⨯ Unable to compile TypeScript'),
'',
diagnostics.map(d => formatDiagnostic(d, ts)).join(EOL),
boundary
].join(EOL)
}
/**
* Sanitize the source map content.
*/
export function getSourceMap (map: string, fileName: string, code: string): string {
var sourceMap = JSON.parse(map)
sourceMap.file = fileName
sourceMap.sources = [fileName]
sourceMap.sourcesContent = [code]
delete sourceMap.sourceRoot
return JSON.stringify(sourceMap)
}
/**
* Extend errors with TypeScript error instances.
*/
export class TypeScriptError extends BaseError {
name = 'TypeScriptError'
}