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