UNPKG

9.1 kBJavaScriptView Raw
1#!/usr/bin/env node
2"use strict";
3Object.defineProperty(exports, "__esModule", { value: true });
4var path = require("path");
5var ts = require("typescript");
6var yargs = require("yargs");
7var load_config_file_1 = require("../config-file/load-config-file");
8var bundle_generator_1 = require("../bundle-generator");
9var check_diagnostics_errors_1 = require("../helpers/check-diagnostics-errors");
10var get_compiler_options_1 = require("../get-compiler-options");
11var fix_path_1 = require("../helpers/fix-path");
12var measure_time_1 = require("../helpers/measure-time");
13var logger_1 = require("../logger");
14// tslint:disable-next-line:no-any
15function toStringsArray(data) {
16 if (!Array.isArray(data)) {
17 throw new Error(data + " is not a array");
18 }
19 return data.map(String);
20}
21function parseArgs() {
22 return yargs
23 .parserConfiguration({
24 'boolean-negation': false,
25 'camel-case-expansion': false,
26 'dot-notation': false,
27 'short-option-groups': false,
28 })
29 .usage('Usage: $0 [options] <file(s)>')
30 .demandCommand(0)
31 .option('out-file', {
32 alias: 'o',
33 type: 'string',
34 description: 'File name of generated d.ts',
35 })
36 .option('verbose', {
37 type: 'boolean',
38 default: false,
39 description: 'Enable verbose logging',
40 })
41 .option('silent', {
42 type: 'boolean',
43 default: false,
44 description: 'Disable any logging except errors',
45 })
46 .option('no-check', {
47 type: 'boolean',
48 default: false,
49 description: 'Skip validation of generated d.ts file',
50 })
51 .option('fail-on-class', {
52 type: 'boolean',
53 default: false,
54 description: 'Fail if generated dts contains class declaration',
55 })
56 .option('external-inlines', {
57 type: 'array',
58 description: 'Array of package names from node_modules to inline typings from.\n' +
59 'Used types will be inlined into the output file',
60 coerce: toStringsArray,
61 })
62 .option('external-imports', {
63 type: 'array',
64 description: 'Array of package names from node_modules to import typings from.\n' +
65 'Used types will be imported using "import { First, Second } from \'library-name\';".\n' +
66 'By default all libraries will be imported (except inlined libraries and libraries from @types)',
67 coerce: toStringsArray,
68 })
69 .option('external-types', {
70 type: 'array',
71 description: 'Array of package names from @types to import typings from via the triple-slash reference directive.\n' +
72 'By default all packages are allowed and will be used according to their usages',
73 coerce: toStringsArray,
74 })
75 .option('umd-module-name', {
76 type: 'string',
77 description: 'Name of the UMD module. If specified then `export as namespace ModuleName;` will be emitted',
78 })
79 .option('project', {
80 type: 'string',
81 description: 'Path to the tsconfig.json file that will be used for the compilation',
82 })
83 .option('sort', {
84 type: 'boolean',
85 default: false,
86 description: 'Sort output nodes',
87 })
88 .option('inline-declare-global', {
89 type: 'boolean',
90 default: false,
91 description: 'Enables inlining of `declare global` statements contained in files which should be inlined (all local files and packages from `--external-inlines`)',
92 })
93 .option('inline-declare-externals', {
94 type: 'boolean',
95 default: false,
96 description: 'Enables inlining of `declare module` statements of the global modules (e.g. `declare module \'external-module\' {}`, but NOT `declare module \'./internal-module\' {}`) contained in files which should be inlined (all local files and packages from inlined libraries)',
97 })
98 .option('disable-symlinks-following', {
99 type: 'boolean',
100 default: false,
101 description: '(EXPERIMENTAL) Disables resolving of symlinks to the original path. See https://github.com/timocov/dts-bundle-generator/issues/39 for more information',
102 })
103 .option('respect-preserve-const-enum', {
104 type: 'boolean',
105 default: false,
106 description: 'Enables stripping the `const` keyword from every direct-exported (or re-exported) from entry file `const enum`. See https://github.com/timocov/dts-bundle-generator/issues/110 for more information',
107 })
108 .option('config', {
109 type: 'string',
110 description: 'File path to the generator config file',
111 })
112 .option('no-banner', {
113 type: 'boolean',
114 default: false,
115 description: 'Allows remove "Generated by dts-bundle-generator" comment from the output',
116 })
117 .version()
118 .strict()
119 .example('$0 path/to/your/entry-file.ts', '')
120 .example('$0 path/to/your/entry-file.ts path/to/your/entry-file-2.ts', '')
121 .example('$0 --external-types jquery react -- entry-file.ts', '')
122 .wrap(Math.min(100, yargs.terminalWidth()))
123 .argv;
124}
125function generateOutFileName(inputFilePath) {
126 var inputFileName = path.parse(inputFilePath).name;
127 return fix_path_1.fixPath(path.join(inputFilePath, '..', inputFileName + '.d.ts'));
128}
129// tslint:disable-next-line:cyclomatic-complexity
130function main() {
131 var args = parseArgs();
132 if (args.silent && args.verbose) {
133 throw new Error('Cannot use both silent and verbose options at the same time');
134 }
135 else if (args.verbose) {
136 logger_1.enableVerbose();
137 }
138 else if (!args.silent) {
139 logger_1.enableNormalLog();
140 }
141 var bundlerConfig;
142 if (args.config !== undefined) {
143 logger_1.verboseLog("Trying to load config from " + args.config + " file...");
144 bundlerConfig = load_config_file_1.loadConfigFile(args.config);
145 }
146 else {
147 if (args._.length < 1) {
148 throw new Error('No input files specified');
149 }
150 if (args._.length > 1 && args['out-file']) {
151 throw new Error('Cannot use outFile with multiple entries');
152 }
153 bundlerConfig = {
154 entries: args._.map(function (path) {
155 return {
156 filePath: path,
157 outFile: args['out-file'],
158 noCheck: args['no-check'],
159 libraries: {
160 allowedTypesLibraries: args['external-types'],
161 importedLibraries: args['external-imports'],
162 inlinedLibraries: args['external-inlines'],
163 },
164 output: {
165 inlineDeclareExternals: args['inline-declare-externals'],
166 inlineDeclareGlobals: args['inline-declare-global'],
167 umdModuleName: args['umd-module-name'],
168 sortNodes: args.sort,
169 noBanner: args['no-banner'],
170 respectPreserveConstEnum: args['respect-preserve-const-enum'],
171 },
172 failOnClass: args['fail-on-class'],
173 };
174 }),
175 compilationOptions: {
176 preferredConfigPath: args.project,
177 followSymlinks: !args['disable-symlinks-following'],
178 },
179 };
180 }
181 logger_1.verboseLog("Total entries count=" + bundlerConfig.entries.length);
182 var generatedDts = bundle_generator_1.generateDtsBundle(bundlerConfig.entries, bundlerConfig.compilationOptions);
183 var outFilesToCheck = [];
184 for (var i = 0; i < bundlerConfig.entries.length; ++i) {
185 var entry = bundlerConfig.entries[i];
186 var outFile = entry.outFile !== undefined ? entry.outFile : generateOutFileName(entry.filePath);
187 logger_1.normalLog("Writing " + entry.filePath + " -> " + outFile);
188 ts.sys.writeFile(outFile, generatedDts[i]);
189 if (!entry.noCheck) {
190 outFilesToCheck.push(outFile);
191 }
192 }
193 if (outFilesToCheck.length === 0) {
194 logger_1.normalLog('File checking is skipped (due nothing to check)');
195 return;
196 }
197 logger_1.normalLog('Checking generated files...');
198 var preferredConfigFile = bundlerConfig.compilationOptions !== undefined ? bundlerConfig.compilationOptions.preferredConfigPath : undefined;
199 var compilerOptions = get_compiler_options_1.getCompilerOptions(outFilesToCheck, preferredConfigFile);
200 if (compilerOptions.skipLibCheck) {
201 compilerOptions.skipLibCheck = false;
202 logger_1.warnLog('Compiler option "skipLibCheck" is disabled to properly check generated output');
203 }
204 var program = ts.createProgram(outFilesToCheck, compilerOptions);
205 check_diagnostics_errors_1.checkProgramDiagnosticsErrors(program);
206}
207try {
208 var executionTime = measure_time_1.measureTime(main);
209 logger_1.normalLog("Done in " + (executionTime / 1000).toFixed(2) + "s");
210}
211catch (ex) {
212 logger_1.normalLog('');
213 logger_1.errorLog("Error: " + ex.message);
214 process.exit(1);
215}