import * as babel from "@babel/core" ; import dynamicImport from "@babel/plugin-syntax-dynamic-import" ; import recast from "recast" ; import { writeFileSync } from "fs" ; import plugin from "babel-plugin-flow-to-typescript" ; import { asyncForEach } from "./util" ; import prettierFormat from "./prettierFormat" ; import { stripComments } from "./stripComments" ; function recastParse ( code , options , parse ) { return recast . parse ( code , { parser : { parse : ( code ) => { return parse ( code , { ... options , tokens : true } ) ; } } } ) ; } function buildRecastGenerate ( rootDir = global . process . cwd ( ) ) { return function recastGenerate ( ast ) : { code : string ; map ? : object ; } { const file = recast . print ( ast ) ; file . code = prettierFormat ( file . code , rootDir ) ; return file ; } ; } const recastPlugin = function ( rootDir ) { return { parserOverride : recastParse , generatorOverride : buildRecastGenerate ( rootDir ) } ; } ; export const babelOptions = ( rootDir ) : babel . TransformOptions => ( { plugins : [ recastPlugin ( rootDir ) , plugin , dynamicImport ] } ) ; const successFiles = [ ] ; const errorFiles = [ ] ; export default async function convert ( files , rootDir ) { await asyncForEach ( files , async ( path , i ) => { console . log ( `${ i } of ${ files . length }: Converting ${ path }` ) ; let res ; try { res = await babel . transformFileAsync ( path , babelOptions ( rootDir ) ) ; res ! . code = stripComments ( res ! . code ! , [ "// @flow" , "// @noflow" ] ) [ 0 ] ; } catch ( err ) { console . log ( err ) ; errorFiles . push ( path ) ; return ; } writeFileSync ( path , res ! . code ) ; successFiles . push ( path ) ; } ) ; return { successFiles , errorFiles } ; }