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