1import { Command } from '@expo/commander';
2import chalk from 'chalk';
3import { PromisyClass, TaskQueue } from 'cwait';
4import fs from 'fs-extra';
5import os from 'os';
6import path from 'path';
7import recursiveOmitBy from 'recursive-omit-by';
8import { Application, TSConfigReader, TypeDocReader } from 'typedoc';
9
10import { EXPO_DIR, PACKAGES_DIR } from '../Constants';
11import logger from '../Logger';
12
13type ActionOptions = {
14  packageName?: string;
15  sdk?: string;
16};
17
18type EntryPoint = string | string[];
19
20type CommandAdditionalParams = [entryPoint: EntryPoint, packageName?: string];
21
22const MINIFY_JSON = true;
23
24const PACKAGES_MAPPING: Record<string, CommandAdditionalParams> = {
25  'expo-accelerometer': [['Accelerometer.ts', 'DeviceSensor.ts'], 'expo-sensors'],
26  'expo-app-loading': ['index.ts'],
27  'expo-apple-authentication': ['index.ts'],
28  'expo-application': ['Application.ts'],
29  'expo-audio': [['Audio.ts', 'Audio.types.ts'], 'expo-av'],
30  'expo-auth-session': ['AuthSession.ts'],
31  'expo-av': [['AV.ts', 'AV.types.ts'], 'expo-av'],
32  'expo-asset': [['Asset.ts', 'AssetHooks.ts']],
33  'expo-background-fetch': ['BackgroundFetch.ts'],
34  'expo-battery': ['Battery.ts'],
35  'expo-barometer': [['Barometer.ts', 'DeviceSensor.ts'], 'expo-sensors'],
36  'expo-barcode-scanner': ['BarCodeScanner.tsx'],
37  'expo-blur': ['index.ts'],
38  'expo-brightness': ['Brightness.ts'],
39  'expo-build-properties': [['withBuildProperties.ts', 'pluginConfig.ts']],
40  'expo-calendar': ['Calendar.ts'],
41  'expo-camera': ['index.ts'],
42  'expo-cellular': ['Cellular.ts'],
43  'expo-checkbox': ['Checkbox.ts'],
44  'expo-clipboard': [['Clipboard.ts', 'Clipboard.types.ts']],
45  'expo-constants': [['Constants.ts', 'Constants.types.ts']],
46  'expo-crypto': ['Crypto.ts'],
47  'expo-device-motion': [['DeviceMotion.ts', 'DeviceSensor.ts'], 'expo-sensors'],
48  'expo-document-picker': ['index.ts'],
49  'expo-error-recovery': ['ErrorRecovery.ts'],
50  'expo-face-detector': ['FaceDetector.ts'],
51  'expo-file-system': ['index.ts'],
52  'expo-firebase-analytics': ['Analytics.ts'],
53  'expo-firebase-core': ['FirebaseCore.ts'],
54  'expo-font': ['index.ts'],
55  'expo-gl': ['index.ts'],
56  'expo-gyroscope': [['Gyroscope.ts', 'DeviceSensor.ts'], 'expo-sensors'],
57  'expo-haptics': ['Haptics.ts'],
58  'expo-image-manipulator': ['ImageManipulator.ts'],
59  'expo-image-picker': ['ImagePicker.ts'],
60  'expo-in-app-purchases': ['InAppPurchases.ts'],
61  'expo-intent-launcher': ['IntentLauncher.ts'],
62  'expo-keep-awake': ['index.ts'],
63  'expo-light-sensor': [['LightSensor.ts', 'DeviceSensor.ts'], 'expo-sensors'],
64  'expo-linking': ['Linking.ts'],
65  'expo-linear-gradient': ['LinearGradient.tsx'],
66  'expo-local-authentication': ['LocalAuthentication.ts'],
67  'expo-localization': ['Localization.ts'],
68  'expo-location': ['Location.ts'],
69  'expo-magnetometer': [['Magnetometer.ts', 'DeviceSensor.ts'], 'expo-sensors'],
70  'expo-mail-composer': ['MailComposer.ts'],
71  'expo-media-library': ['MediaLibrary.ts'],
72  'expo-navigation-bar': ['NavigationBar.ts'],
73  'expo-network': ['Network.ts'],
74  'expo-pedometer': ['Pedometer.ts', 'expo-sensors'],
75  'expo-print': ['Print.ts'],
76  'expo-random': ['Random.ts'],
77  'expo-screen-capture': ['ScreenCapture.ts'],
78  'expo-screen-orientation': ['ScreenOrientation.ts'],
79  'expo-secure-store': ['SecureStore.ts'],
80  'expo-sharing': ['Sharing.ts'],
81  'expo-sms': ['SMS.ts'],
82  'expo-speech': ['Speech/Speech.ts'],
83  'expo-splash-screen': ['SplashScreen.ts'],
84  'expo-sqlite': ['index.ts'],
85  'expo-status-bar': ['StatusBar.ts'],
86  'expo-store-review': ['StoreReview.ts'],
87  'expo-system-ui': ['SystemUI.ts'],
88  'expo-task-manager': ['TaskManager.ts'],
89  'expo-tracking-transparency': ['TrackingTransparency.ts'],
90  'expo-updates': ['index.ts'],
91  'expo-video': [['Video.tsx', 'Video.types.ts'], 'expo-av'],
92  'expo-video-thumbnails': ['VideoThumbnails.ts'],
93  'expo-web-browser': ['WebBrowser.ts'],
94};
95
96const executeCommand = async (
97  jsonFileName: string,
98  sdk?: string,
99  entryPoint: EntryPoint = 'index.ts',
100  packageName: string = jsonFileName
101) => {
102  const app = new Application();
103
104  app.options.addReader(new TSConfigReader());
105  app.options.addReader(new TypeDocReader());
106
107  const dataPath = path.join(
108    EXPO_DIR,
109    'docs',
110    'public',
111    'static',
112    'data',
113    sdk ? `v${sdk}.0.0` : `unversioned`
114  );
115
116  if (!fs.existsSync(dataPath)) {
117    throw new Error(
118      `�� The path for given SDK version do not exist!
119       Check if you have provided the correct major SDK version to the '--sdk' parameter.
120       Path: '${dataPath}'`
121    );
122  }
123
124  const basePath = path.join(PACKAGES_DIR, packageName);
125  const entriesPath = path.join(basePath, 'src');
126  const tsConfigPath = path.join(basePath, 'tsconfig.json');
127  const jsonOutputPath = path.join(dataPath, `${jsonFileName}.json`);
128
129  const entryPoints = Array.isArray(entryPoint)
130    ? entryPoint.map((entry) => path.join(entriesPath, entry))
131    : [path.join(entriesPath, entryPoint)];
132
133  app.bootstrap({
134    entryPoints,
135    tsconfig: tsConfigPath,
136    disableSources: true,
137    hideGenerator: true,
138    excludePrivate: true,
139    excludeProtected: true,
140  });
141
142  const project = app.convert();
143
144  if (project) {
145    await app.generateJson(project, jsonOutputPath);
146    const output = await fs.readJson(jsonOutputPath);
147    output.name = jsonFileName;
148
149    if (Array.isArray(entryPoint)) {
150      const filterEntries = entryPoint.map((entry) => entry.substring(0, entry.lastIndexOf('.')));
151      output.children = output.children
152        .filter((entry) => filterEntries.includes(entry.name))
153        .map((entry) => entry.children)
154        .flat()
155        .sort((a, b) => a.name.localeCompare(b.name));
156    }
157
158    if (MINIFY_JSON) {
159      const minifiedJson = recursiveOmitBy(
160        output,
161        ({ key, node }) =>
162          ['id', 'groups', 'target'].includes(key) || (key === 'flags' && !Object.keys(node).length)
163      );
164      await fs.writeFile(jsonOutputPath, JSON.stringify(minifiedJson, null, 0));
165    } else {
166      await fs.writeFile(jsonOutputPath, JSON.stringify(output));
167    }
168  } else {
169    throw new Error(`�� Failed to extract API data from source code for '${packageName}' package.`);
170  }
171};
172
173async function action({ packageName, sdk }: ActionOptions) {
174  const taskQueue = new TaskQueue(Promise as PromisyClass, os.cpus().length);
175
176  try {
177    if (packageName) {
178      const packagesEntries = Object.entries(PACKAGES_MAPPING)
179        .filter(([key, value]) => key === packageName || value.includes(packageName))
180        .map(([key, value]) => taskQueue.add(() => executeCommand(key, sdk, ...value)));
181      if (packagesEntries.length) {
182        await Promise.all(packagesEntries);
183        logger.log(
184          chalk.green(`\n�� Successful extraction of docs API data for the selected package!`)
185        );
186      } else {
187        logger.warn(`�� Package '${packageName}' API data generation is not supported yet!`);
188      }
189    } else {
190      const packagesEntries = Object.entries(PACKAGES_MAPPING).map(([key, value]) =>
191        taskQueue.add(() => executeCommand(key, sdk, ...value))
192      );
193      await Promise.all(packagesEntries);
194      logger.log(
195        chalk.green(`\n�� Successful extraction of docs API data for all available packages!`)
196      );
197    }
198  } catch (error) {
199    logger.error(error);
200  }
201}
202
203export default (program: Command) => {
204  program
205    .command('generate-docs-api-data')
206    .alias('gdad')
207    .description(`Extract API data JSON files for docs using TypeDoc.`)
208    .option('-p, --packageName <packageName>', 'Extract API data only for the specific package.')
209    .option('-s, --sdk <version>', 'Set the data output path to the specific SDK version.')
210    .asyncAction(action);
211};
212