1#!/usr/bin/env node
2
3// This CLI generates .js.flow definitions from .d.ts
4// TS definitions.
5// It accepts files to generate definitions for via
6// argv;
7
8const path = require('path');
9const fs = require('fs');
10const globby = require('globby');
11
12const { promisify } = require('util');
13const { compiler, beautify } = require('flowgen');
14
15const cwd = process.cwd();
16const writeFile = promisify(fs.writeFile);
17const readFile = promisify(fs.readFile);
18const preamble = '// @flow\n\n';
19
20const genEntry = async () => {
21 try {
22 fs.mkdirSync(path.resolve(cwd, 'dist'));
23 } catch (err) {
24 if (err.code !== 'EEXIST') {
25 throw err;
26 }
27 }
28
29 let entry = await readFile(path.resolve(cwd, 'index.js.flow'), { encoding: 'utf8' });
30
31 entry = entry.replace(/.\/dist\//g, './');
32
33 const outputCJS = path.resolve(cwd, 'dist/wonka.js.flow');
34 const outputES = path.resolve(cwd, 'dist/wonka.es.js.flow');
35
36 return Promise.all([
37 writeFile(outputCJS, entry, { encoding: 'utf8' }),
38 writeFile(outputES, entry, { encoding: 'utf8' })
39 ]);
40};
41
42const gen = async () => {
43 const input = await globby('dist/types/**/*.d.ts');
44 console.log(`Compiling ${input.length} TS definitions to Flow...`);
45
46 const defs = input.map(filename => {
47 const fullpath = path.resolve(cwd, filename);
48 const flowdef = beautify(compiler.compileDefinitionFile(fullpath));
49 return { fullpath, flowdef };
50 });
51
52 const write = defs.map(({ fullpath, flowdef }) => {
53 const basename = path.basename(fullpath, '.d.ts');
54 const filepath = path.dirname(fullpath);
55 const newpath = path.join(filepath, basename + '.js.flow');
56 return writeFile(newpath, preamble + flowdef);
57 });
58
59 return Promise.all([...write, genEntry()]);
60};
61
62gen()
63 .then(() => {
64 process.exit(0);
65 })
66 .catch(err => {
67 console.error(err.message);
68 process.exit(1);
69 });