-
-
Notifications
You must be signed in to change notification settings - Fork 431
/
utils.ts
352 lines (326 loc) · 9.8 KB
/
utils.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
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
import { Chalk } from 'chalk';
import * as fs from 'fs';
import * as micromatch from 'micromatch';
import * as path from 'path';
import * as webpack from 'webpack';
import type * as typescript from 'typescript';
import constants = require('./constants');
import {
ErrorInfo,
FileLocation,
FilePathKey,
LoaderOptions,
ResolvedModule,
ReverseDependencyGraph,
Severity,
TSInstance,
} from './interfaces';
import { getInputFileNameFromOutput } from './instances';
/**
* The default error formatter.
*/
function defaultErrorFormatter(error: ErrorInfo, colors: Chalk) {
const messageColor =
error.severity === 'warning' ? colors.bold.yellow : colors.bold.red;
return (
colors.grey('[tsl] ') +
messageColor(error.severity.toUpperCase()) +
(error.file === ''
? ''
: messageColor(' in ') +
colors.bold.cyan(`${error.file}(${error.line},${error.character})`)) +
constants.EOL +
messageColor(` TS${error.code}: ${error.content}`)
);
}
/**
* Take TypeScript errors, parse them and format to webpack errors
* Optionally adds a file name
*/
export function formatErrors(
diagnostics: ReadonlyArray<typescript.Diagnostic> | undefined,
loaderOptions: LoaderOptions,
colors: Chalk,
compiler: typeof typescript,
merge: { file?: string; module?: webpack.Module },
context: string
): webpack.WebpackError[] {
return diagnostics === undefined
? []
: diagnostics
.filter(diagnostic => {
if (loaderOptions.ignoreDiagnostics.indexOf(diagnostic.code) !== -1) {
return false;
}
if (
loaderOptions.reportFiles.length > 0 &&
diagnostic.file !== undefined
) {
const relativeFileName = path.relative(
context,
diagnostic.file.fileName
);
const matchResult = micromatch(
[relativeFileName],
loaderOptions.reportFiles
);
if (matchResult.length === 0) {
return false;
}
}
return true;
})
.map<webpack.WebpackError>(diagnostic => {
const file = diagnostic.file;
const { start, end } =
file === undefined || diagnostic.start === undefined
? { start: undefined, end: undefined }
: getFileLocations(file, diagnostic.start, diagnostic.length);
const errorInfo: ErrorInfo = {
code: diagnostic.code,
severity: compiler.DiagnosticCategory[
diagnostic.category
].toLowerCase() as Severity,
content: compiler.flattenDiagnosticMessageText(
diagnostic.messageText,
constants.EOL
),
file: file === undefined ? '' : path.normalize(file.fileName),
line: start === undefined ? 0 : start.line,
character: start === undefined ? 0 : start.character,
context,
};
const message =
loaderOptions.errorFormatter === undefined
? defaultErrorFormatter(errorInfo, colors)
: loaderOptions.errorFormatter(errorInfo, colors);
const error = makeError(
loaderOptions,
message,
merge.file === undefined ? errorInfo.file : merge.file,
start,
end
);
return Object.assign(error, merge) as webpack.WebpackError;
});
}
function getFileLocations(
file: typescript.SourceFile,
position: number,
length = 0
) {
const startLC = file.getLineAndCharacterOfPosition(position);
const start: FileLocation = {
line: startLC.line + 1,
character: startLC.character + 1,
};
const endLC =
length > 0
? file.getLineAndCharacterOfPosition(position + length)
: undefined;
const end: FileLocation | undefined =
endLC === undefined
? undefined
: { line: endLC.line + 1, character: endLC.character + 1 };
return { start, end };
}
export function fsReadFile(
fileName: string,
encoding: BufferEncoding | undefined = 'utf8'
) {
fileName = path.normalize(fileName);
try {
return fs.readFileSync(fileName, encoding);
} catch (e) {
return undefined;
}
}
export function makeError(
loaderOptions: LoaderOptions,
message: string,
file: string,
location?: FileLocation,
endLocation?: FileLocation
): webpack.WebpackError {
const error = new webpack.WebpackError(message);
error.file = file;
error.loc =
location === undefined
? { name: file }
: makeWebpackLocation(location, endLocation);
error.details = tsLoaderSource(loaderOptions);
return error;
// return {
// message,
// file,
// loc:
// location === undefined
// ? { name: file }
// : makeWebpackLocation(location, endLocation),
// details: tsLoaderSource(loaderOptions),
// };
}
/** Not exported from webpack so declared locally */
interface WebpackSourcePosition {
line: number;
column?: number;
}
function makeWebpackLocation(
location: FileLocation,
endLocation?: FileLocation
) {
const start: WebpackSourcePosition = {
line: location.line,
column: location.character - 1,
};
const end: WebpackSourcePosition | undefined =
endLocation === undefined
? undefined
: { line: endLocation.line, column: endLocation.character - 1 };
return { start, end };
}
export function tsLoaderSource(loaderOptions: LoaderOptions) {
return `ts-loader-${loaderOptions.instance}`;
}
export function appendSuffixIfMatch(
patterns: (RegExp | string)[],
filePath: string,
suffix: string
): string {
if (patterns.length > 0) {
for (const regexp of patterns) {
if (filePath.match(regexp) !== null) {
return filePath + suffix;
}
}
}
return filePath;
}
export function appendSuffixesIfMatch(
suffixDict: { [suffix: string]: (RegExp | string)[] },
filePath: string
): string {
let amendedPath = filePath;
for (const suffix in suffixDict) {
amendedPath = appendSuffixIfMatch(suffixDict[suffix], amendedPath, suffix);
}
return amendedPath;
}
export function unorderedRemoveItem<T>(array: T[], item: T): boolean {
for (let i = 0; i < array.length; i++) {
if (array[i] === item) {
// Fill in the "hole" left at `index`.
array[i] = array[array.length - 1];
array.pop();
return true;
}
}
return false;
}
export function populateDependencyGraph(
resolvedModules: ResolvedModule[],
instance: TSInstance,
containingFile: string
) {
resolvedModules = resolvedModules.filter(
mod => mod !== null && mod !== undefined
);
if (resolvedModules.length) {
const containingFileKey = instance.filePathKeyMapper(containingFile);
instance.dependencyGraph.set(containingFileKey, resolvedModules);
}
}
export function populateReverseDependencyGraph(instance: TSInstance) {
const reverseDependencyGraph: ReverseDependencyGraph = new Map();
for (const [fileKey, resolvedModules] of instance.dependencyGraph.entries()) {
const inputFileName =
instance.solutionBuilderHost &&
getInputFileNameFromOutput(instance, fileKey);
const containingFileKey = inputFileName
? instance.filePathKeyMapper(inputFileName)
: fileKey;
resolvedModules.forEach(({ resolvedFileName }) => {
const key = instance.filePathKeyMapper(
instance.solutionBuilderHost
? getInputFileNameFromOutput(instance, resolvedFileName) ||
resolvedFileName
: resolvedFileName
);
let map = reverseDependencyGraph.get(key);
if (!map) {
map = new Map();
reverseDependencyGraph.set(key, map);
}
map.set(containingFileKey, true);
});
}
return reverseDependencyGraph;
}
/**
* Recursively collect all possible dependants of passed file
*/
export function collectAllDependants(
reverseDependencyGraph: ReverseDependencyGraph,
fileName: FilePathKey,
result: Map<FilePathKey, true> = new Map()
): Map<FilePathKey, true> {
result.set(fileName, true);
const dependants = reverseDependencyGraph.get(fileName);
if (dependants !== undefined) {
for (const dependantFileName of dependants.keys()) {
if (!result.has(dependantFileName)) {
collectAllDependants(reverseDependencyGraph, dependantFileName, result);
}
}
}
return result;
}
export function arrify<T>(val: T | T[]) {
if (val === null || val === undefined) {
return [];
}
return Array.isArray(val) ? val : [val];
}
export function ensureProgram(instance: TSInstance) {
if (instance && instance.watchHost) {
if (instance.hasUnaccountedModifiedFiles) {
if (instance.changedFilesList) {
instance.watchHost.updateRootFileNames();
}
if (instance.watchOfFilesAndCompilerOptions) {
instance.builderProgram = instance.watchOfFilesAndCompilerOptions.getProgram();
instance.program = instance.builderProgram.getProgram();
}
instance.hasUnaccountedModifiedFiles = false;
}
return instance.program;
}
if (instance.languageService) {
return instance.languageService.getProgram();
}
return instance.program;
}
export function supportsSolutionBuild(instance: TSInstance) {
return (
!!instance.configFilePath &&
!!instance.loaderOptions.projectReferences &&
!!instance.configParseResult.projectReferences &&
!!instance.configParseResult.projectReferences.length
);
}
export function isReferencedFile(instance: TSInstance, filePath: string) {
return (
!!instance.solutionBuilderHost &&
!!instance.solutionBuilderHost.watchedFiles.get(
instance.filePathKeyMapper(filePath)
)
);
}
export function useCaseSensitiveFileNames(
compiler: typeof typescript,
loaderOptions: LoaderOptions
) {
return loaderOptions.useCaseSensitiveFileNames !== undefined
? loaderOptions.useCaseSensitiveFileNames
: compiler.sys.useCaseSensitiveFileNames;
}