UNPKG

1.91 kBPlain TextView Raw
1/**
2 * @license
3 * Copyright (c) 2018 The Polymer Project Authors. All rights reserved. This
4 * code may only be used under the BSD style license found at
5 * http://polymer.github.io/LICENSE.txt The complete set of authors may be
6 * found at http://polymer.github.io/AUTHORS.txt The complete set of
7 * contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code
8 * distributed by Google as part of the polymer project is also subject to an
9 * additional IP rights grant found at http://polymer.github.io/PATENTS.txt
10 */
11
12import * as ts from 'typescript';
13
14/**
15 * The result of calling verifyTypings.
16 */
17export interface VerifyTypingsResult {
18 success: boolean;
19 errorLog: string;
20}
21
22const compilerOptions = {
23 target: ts.ScriptTarget.ES2015,
24 module: ts.ModuleKind.ES2015,
25 moduleResolution: ts.ModuleResolutionKind.NodeJs,
26 strict: true,
27 noUnusedLocals: true,
28 noUnusedParameters: true,
29 declaration: true,
30 lib: [
31 'lib.dom.d.ts',
32 'lib.esnext.d.ts',
33 ],
34};
35
36const diagnosticsHost = {
37 getNewLine: () => '\n',
38 getCurrentDirectory: () => process.cwd(),
39 getCanonicalFileName: (fileName: string) => fileName,
40};
41
42/**
43 * Compile the given declaration file paths with TypeScript and return whether
44 * compilation succeeded or failed, and a "pretty" formatted error log string.
45 *
46 * Uses a TypeScript compiler configuration suitable for web development, and
47 * strict type checking.
48 */
49export function verifyTypings(filePaths: string[]): VerifyTypingsResult {
50 const program = ts.createProgram(filePaths, compilerOptions);
51 const emitResult = program.emit();
52 const diagnostics =
53 ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
54 if (diagnostics.length > 0) {
55 return {
56 success: false,
57 errorLog:
58 ts.formatDiagnosticsWithColorAndContext(diagnostics, diagnosticsHost)
59 };
60 }
61 return {success: true, errorLog: ''};
62}