This repository has been archived by the owner on Jul 21, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtranspiler.ts
190 lines (171 loc) · 6.17 KB
/
transpiler.ts
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
import * as md5 from 'md5';
import * as path from 'path';
import * as ts from 'typescript';
import { mapJsx, mapTarget, mapModule } from './options';
import { DependencyMap } from './types';
import * as utils from './utils';
export interface TranspileOptions {
compilerOptions?: ts.CompilerOptions;
fileName?: string;
reportDiagnostics?: boolean;
moduleName?: string;
renamedDependencies?: ts.MapLike<string>;
}
export interface TranspileOutput {
status: number;
outputText: string;
declarationText?: string;
diagnostics?: ts.Diagnostic[];
sourceMapText?: string;
}
interface CacheEntry {
status: number;
outputText: string;
declarationText: string;
sourceMapText: string;
}
const cache: {[hash: string]: CacheEntry} = {};
// tslint:disable cyclomatic-complexity
export function transpileModule(input: string, transpileOptions: TranspileOptions,
map: DependencyMap, patternRoot: string): TranspileOutput {
const hash = md5(input);
if (hash in cache) {
const { status, outputText, declarationText, sourceMapText } = cache[hash];
return {
status,
outputText,
declarationText,
diagnostics: undefined,
sourceMapText
};
}
const options: ts.CompilerOptions = transpileOptions.compilerOptions || ts.getDefaultCompilerOptions();
if (options.jsx) {
options.jsx = mapJsx(options.jsx);
}
if (options.target) {
options.target = mapTarget(options.target);
}
if (options.module) {
options.module = mapModule(options.module);
}
// if jsx is specified then treat file as .tsx
const inputFileName = utils.normalizePath(transpileOptions.fileName || (options.jsx ? 'module.tsx' : 'module.ts'));
const sourceFile = ts.createSourceFile(inputFileName, input, options.target || ts.ScriptTarget.ES5);
if (transpileOptions.moduleName) {
sourceFile.moduleName = transpileOptions.moduleName;
}
// output
let outputText = '';
let declarationText = '';
let sourceMapText = '';
// create a compilerHost object to allow the compiler to read and write files
const compilerHost: ts.CompilerHost = {
getSourceFile: (fileName) => {
if (fileName === inputFileName) {
return sourceFile;
}
try {
return ts.createSourceFile(fileName, ts.sys.readFile(fileName) || '', options.target || ts.ScriptTarget.ES5);
} catch (e) {
console.error('failed to read source-file', fileName);
return undefined!;
}
},
writeFile: (name, text) => {
// console.log('skip?', inputFileName.replace(/.tsx?/, ''), name.replace(/\.jsx?|\.d.ts|\.map/, ''));
if (inputFileName.replace(/\.tsx?/, '') !== name.replace(/\.jsx?|\.d\.ts|\.map/, '')) {
// console.warn('Skipping transitive dependency results', name, 'for', inputFileName);
return;
}
// console.log('writing', name, 'for', inputFileName);
if (name.endsWith('.map')) {
sourceMapText = text;
} else if (name.endsWith('.d.ts')) {
declarationText = text;
} else {
outputText = text;
}
},
getDefaultLibFileName: () => ts.getDefaultLibFilePath(options),
useCaseSensitiveFileNames: () => ts.sys.useCaseSensitiveFileNames,
getCanonicalFileName: fileName => ts.sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(),
getCurrentDirectory: () => ts.sys.getCurrentDirectory(),
getNewLine: () => ts.sys.newLine,
fileExists: (fileName): boolean => ts.sys.fileExists(fileName),
readFile: path => ts.sys.readFile(path),
directoryExists: path => ts.sys.directoryExists(path),
getDirectories: () => [],
resolveModuleNames(moduleNames: string[], containingFile: string): (ts.ResolvedModule)[] {
return moduleNames.map(moduleName =>
resolveDependency(moduleName, containingFile, map, patternRoot, options) as any);
}
};
const program = ts.createProgram([inputFileName], options, compilerHost);
const result = program.emit();
const allDiagnostics =
ts.getPreEmitDiagnostics(program)
.concat(
result.diagnostics,
getDeclarationDiagnostics(program),
program.getGlobalDiagnostics(),
program.getOptionsDiagnostics(),
program.getSemanticDiagnostics(),
program.getSyntacticDiagnostics()
);
allDiagnostics.forEach(diagnostic => {
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
if (diagnostic.file && typeof diagnostic.start === 'number') {
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
throw new Error(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
} else {
throw new Error(message);
}
});
const exitCode = result.emitSkipped ? 1 : 0;
cache[hash] = {
status: exitCode,
outputText,
declarationText,
sourceMapText
};
return {
status: exitCode,
outputText,
declarationText,
diagnostics: allDiagnostics,
sourceMapText
};
}
function getDeclarationDiagnostics(program: ts.Program): ReadonlyArray<ts.Diagnostic> {
try {
return program.getDeclarationDiagnostics();
} catch (e) {
return [];
}
}
export function resolveDependency(moduleName: string, containingFile: string, map: DependencyMap,
patternRoot: string, options: ts.CompilerOptions): ts.ResolvedModule | undefined {
// try patternplate demo Pattern dependency
if (moduleName === 'Pattern' && containingFile.endsWith('demo.tsx')) {
return { resolvedFileName: containingFile.replace('demo.tsx', 'index.tsx') };
}
if (containingFile in map) {
const patterns = map[containingFile].pattern.manifest.patterns || {};
const pattern = patterns[moduleName];
// try to resolve pattern.json defined pattern dependency
if (pattern) {
const resolvedFileName = path.join(patternRoot, pattern, 'index.tsx');
return { resolvedFileName };
}
}
if (!moduleName.startsWith('.') || containingFile.indexOf('node_modules') > -1) {
// try to use standard resolution
const result = ts.resolveModuleName(moduleName, containingFile, options,
{ fileExists: ts.sys.fileExists, readFile: ts.sys.readFile });
if (result && result.resolvedModule) {
return result.resolvedModule;
}
}
return undefined;
}