1import spawnAsync from '@expo/spawn-async'; 2import fs from 'fs-extra'; 3import path from 'path'; 4 5export interface ReactNativeCodegenParameters { 6 // path to `react-native` package 7 reactNativeRoot: string; 8 9 // path to `react-native-codegen` package 10 codegenPkgRoot: string; 11 12 // output path for generated code 13 outputDir: string; 14 15 // library name 16 name: string; 17 18 // library type 19 type: 'components' | 'modules'; 20 21 // platform for generated code 22 platform: 'android' | 'ios'; 23 24 // absolute path to library's javascript code 25 jsSrcsDir: string; 26 27 // keep the intermediate schema.json (default is false) 28 keepIntermediateSchema?: boolean; 29 30 // the base dir name for output generated code (default is `name`) 31 outputDirBaseName?: string; 32} 33 34export async function runReactNativeCodegenAsync(params: ReactNativeCodegenParameters) { 35 const genSchemaScript = path.join( 36 params.codegenPkgRoot, 37 'lib', 38 'cli', 39 'combine', 40 'combine-js-to-schema-cli.js' 41 ); 42 const genCodeScript = path.join(params.reactNativeRoot, 'scripts', 'generate-specs-cli.js'); 43 44 const schemaOutputPath = path.join(params.outputDir, 'schema.json'); 45 const outputDirBaseName = params.outputDirBaseName ?? params.name; 46 const codegenOutputDir = 47 params.type === 'components' 48 ? path.join(params.outputDir, 'react', 'renderer', 'components', outputDirBaseName) 49 : path.join(params.outputDir, outputDirBaseName); 50 await fs.ensureDir(params.outputDir); 51 52 // generate schema.json from js & flow types 53 await spawnAsync('node', [genSchemaScript, schemaOutputPath, params.jsSrcsDir]); 54 55 // generate code from schema.json 56 await spawnAsync('node', [ 57 genCodeScript, 58 '--platform', 59 params.platform, 60 '--schemaPath', 61 schemaOutputPath, 62 '--outputDir', 63 codegenOutputDir, 64 '--libraryName', 65 params.name, 66 '--libraryType', 67 params.type, 68 ]); 69 70 const keepIntermediateSchema = params.keepIntermediateSchema ?? false; 71 if (!keepIntermediateSchema) { 72 await fs.remove(schemaOutputPath); 73 } 74} 75