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