Mirror: 馃帺 A tiny but capable push & pull stream library for TypeScript and Flow
at v3.2.0 2.1 kB view raw
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(/.\/src/g, '../src'); 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(['src/*.d.ts', 'src/**/*.d.ts'], { 44 gitignore: true 45 }); 46 47 if (input.length === 0) { 48 throw new Error('No input files passed as arguments.'); 49 } 50 51 console.log(`Compiling ${input.length} TS definitions to Flow...`); 52 53 const defs = input.map(filename => { 54 const fullpath = path.resolve(cwd, filename); 55 const flowdef = beautify(compiler.compileDefinitionFile(fullpath)); 56 return { fullpath, flowdef }; 57 }); 58 59 const write = defs.map(({ fullpath, flowdef }) => { 60 const basename = path.basename(fullpath, '.d.ts'); 61 const filepath = path.dirname(fullpath); 62 const newpath = path.join(filepath, basename + '.js.flow'); 63 64 // Fix incorrect imports 65 const fixedFlowdef = flowdef.replace(/^import \{/g, 'import type {'); 66 67 return writeFile(newpath, preamble + fixedFlowdef, { 68 encoding: 'utf8' 69 }); 70 }); 71 72 return Promise.all([...write, genEntry()]); 73}; 74 75gen() 76 .then(() => { 77 process.exit(0); 78 }) 79 .catch(err => { 80 console.error(err.message); 81 process.exit(1); 82 });