xref: /expo/tools/src/Codegen.ts (revision 5bd7a65d)
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' | 'all';
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  // java package name
31  javaPackageName?: 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  await fs.ensureDir(params.outputDir);
46
47  // generate schema.json from js & flow types
48  await spawnAsync('node', [genSchemaScript, schemaOutputPath, params.jsSrcsDir]);
49
50  // generate code from schema.json
51  const genCodeArgs = [
52    genCodeScript,
53    '--platform',
54    params.platform,
55    '--schemaPath',
56    schemaOutputPath,
57    '--outputDir',
58    params.outputDir,
59    '--libraryName',
60    params.name,
61    '--libraryType',
62    params.type,
63  ];
64  if (params.javaPackageName) {
65    genCodeArgs.push('--javaPackageName', params.javaPackageName);
66  }
67  await spawnAsync('node', genCodeArgs);
68
69  const keepIntermediateSchema = params.keepIntermediateSchema ?? false;
70  if (!keepIntermediateSchema) {
71    await fs.remove(schemaOutputPath);
72  }
73}
74