From 47099cfd3187d4e21fe286ef5d25cf97e27af747 Mon Sep 17 00:00:00 2001 From: Pascal Hartig Date: Wed, 8 Sep 2021 08:43:18 -0700 Subject: [PATCH] Fix Flipper lints #16 Summary: Larger list of fixes. Adding another package to the flipper export is a bit nasty but it unblocks us for now and centralises `remote` access which seems like a win for FAAS. Reviewed By: mweststrate Differential Revision: D30785421 fbshipit-source-id: 931297e8566b5d8a213b69ae87d0cda7648b3ed4 --- desktop/app/src/index.tsx | 1 + desktop/app/src/utils/pathUtils.tsx | 3 + desktop/plugins/package.json | 17 +++-- desktop/plugins/postinstall.ts | 10 +-- desktop/plugins/public/cpu/index.tsx | 70 +++++++++-------- desktop/plugins/public/cpu/package.json | 3 + .../plugins/public/crash_reporter/index.tsx | 11 ++- .../public/crash_reporter/ios-crash-utils.tsx | 30 ++++---- .../public/crash_reporter/package.json | 2 + .../databases/DatabaseDetailSidebar.tsx | 9 --- desktop/plugins/public/databases/index.tsx | 26 ++++--- desktop/plugins/public/fresco/index.tsx | 16 ++-- .../plugins/public/hermesdebuggerrn/index.tsx | 76 +++++++++---------- desktop/plugins/public/layout/Inspector.tsx | 33 ++++---- desktop/plugins/public/layout/Search.tsx | 3 +- desktop/plugins/public/layout/index.tsx | 9 ++- desktop/plugins/public/navigation/plugin.tsx | 8 +- .../navigation/util/appMatchPatterns.tsx | 6 +- .../public/navigation/util/indexedDB.tsx | 4 +- desktop/plugins/public/network/index.tsx | 29 +++---- .../request-mocking/NetworkRouteManager.tsx | 65 +++++++++------- desktop/plugins/public/sandbox/index.tsx | 23 ++++-- desktop/plugins/public/yarn.lock | 35 +++++++++ desktop/plugins/yarn.lock | 5 ++ 24 files changed, 293 insertions(+), 201 deletions(-) diff --git a/desktop/app/src/index.tsx b/desktop/app/src/index.tsx index ce86c5ede..4341461d0 100644 --- a/desktop/app/src/index.tsx +++ b/desktop/app/src/index.tsx @@ -96,6 +96,7 @@ export {default as StatusIndicator} from './ui/components/StatusIndicator'; export {default as HorizontalRule} from './ui/components/HorizontalRule'; export {default as Label} from './ui/components/Label'; export {default as Heading} from './ui/components/Heading'; +export * from './utils/pathUtils'; export {Filter} from './ui/components/filter/types'; export {default as StackTrace} from './ui/components/StackTrace'; export { diff --git a/desktop/app/src/utils/pathUtils.tsx b/desktop/app/src/utils/pathUtils.tsx index 9c695774b..6807590e3 100644 --- a/desktop/app/src/utils/pathUtils.tsx +++ b/desktop/app/src/utils/pathUtils.tsx @@ -7,6 +7,9 @@ * @format */ +// We use sync access once per startup. +/* eslint-disable node/no-sync */ + import path from 'path'; import fs from 'fs'; // In utils this is fine when used with caching. diff --git a/desktop/plugins/package.json b/desktop/plugins/package.json index bbd6dacb6..b3761ca59 100644 --- a/desktop/plugins/package.json +++ b/desktop/plugins/package.json @@ -8,19 +8,20 @@ }, "devDependencies": { "fs-extra": "^9.0.1", - "p-map": "^4.0.0" + "p-map": "^4.0.0", + "promisify-child-process": "^4.1.1" }, "peerDependencies": { - "flipper": "*", - "flipper-plugin": "*", - "antd": "*", - "react": "*", - "react-dom": "*", - "@emotion/styled": "*", "@ant-design/icons": "*", + "@emotion/styled": "*", + "@types/node": "*", "@types/react": "*", "@types/react-dom": "*", - "@types/node": "*" + "antd": "*", + "flipper": "*", + "flipper-plugin": "*", + "react": "*", + "react-dom": "*" }, "scripts": { "postinstall": "../ts-node ./postinstall.ts" diff --git a/desktop/plugins/postinstall.ts b/desktop/plugins/postinstall.ts index fcc31b07d..e9e6b57fd 100644 --- a/desktop/plugins/postinstall.ts +++ b/desktop/plugins/postinstall.ts @@ -7,7 +7,9 @@ * @format */ -import {execSync} from 'child_process'; +/* eslint-disable flipper/no-console-error-without-context */ + +import {exec} from 'promisify-child-process'; import path from 'path'; import fs from 'fs-extra'; import pmap from 'p-map'; @@ -90,14 +92,12 @@ async function postinstall(): Promise { } return 1; } - execSync('yarn install --mutex network:30330', { + await exec('yarn install --mutex network:30330', { cwd: publicPluginsDir, - stdio: 'inherit', }); if (await fs.pathExists(fbPluginsDir)) { - execSync('yarn install --mutex network:30330', { + await exec('yarn install --mutex network:30330', { cwd: fbPluginsDir, - stdio: 'inherit', }); } const peerDependenciesArray = Object.keys(peerDependencies); diff --git a/desktop/plugins/public/cpu/index.tsx b/desktop/plugins/public/cpu/index.tsx index 85b3ebab4..210cb93f0 100644 --- a/desktop/plugins/public/cpu/index.tsx +++ b/desktop/plugins/public/cpu/index.tsx @@ -265,11 +265,15 @@ export function devicePlugin(client: PluginClient<{}, {}>) { }); for (let i = 0; i < cpuState.get().cpuCount; ++i) { - readAvailableGovernors(i).then((output) => { - cpuState.update((draft) => { - draft.cpuFreq[i].scaling_available_governors = output; + readAvailableGovernors(i) + .then((output) => { + cpuState.update((draft) => { + draft.cpuFreq[i].scaling_available_governors = output; + }); + }) + .catch((e) => { + console.error('Failed to read CPU governors:', e); }); - }); } const update = async () => { @@ -330,34 +334,38 @@ export function devicePlugin(client: PluginClient<{}, {}>) { }; // check how many cores we have on this device - executeShell('cat /sys/devices/system/cpu/possible').then((output) => { - const idx = output.indexOf('-'); - const cpuFreq = []; - const count = parseInt(output.substring(idx + 1), 10) + 1; - for (let i = 0; i < count; ++i) { - cpuFreq[i] = { - cpu_id: i, - scaling_cur_freq: -1, - scaling_min_freq: -1, - scaling_max_freq: -1, - cpuinfo_min_freq: -1, - cpuinfo_max_freq: -1, - scaling_available_freqs: [], - scaling_governor: 'N/A', - scaling_available_governors: [], - }; - } - cpuState.set({ - cpuCount: count, - cpuFreq: cpuFreq, - monitoring: false, - hardwareInfo: '', - temperatureMap: {}, - thermalAccessible: true, - displayThermalInfo: false, - displayCPUDetail: true, + executeShell('cat /sys/devices/system/cpu/possible') + .then((output) => { + const idx = output.indexOf('-'); + const cpuFreq = []; + const count = parseInt(output.substring(idx + 1), 10) + 1; + for (let i = 0; i < count; ++i) { + cpuFreq[i] = { + cpu_id: i, + scaling_cur_freq: -1, + scaling_min_freq: -1, + scaling_max_freq: -1, + cpuinfo_min_freq: -1, + cpuinfo_max_freq: -1, + scaling_available_freqs: [], + scaling_governor: 'N/A', + scaling_available_governors: [], + }; + } + cpuState.set({ + cpuCount: count, + cpuFreq: cpuFreq, + monitoring: false, + hardwareInfo: '', + temperatureMap: {}, + thermalAccessible: true, + displayThermalInfo: false, + displayCPUDetail: true, + }); + }) + .catch((e) => { + console.error('Failed to read CPU cores:', e); }); - }); client.onDeactivate(() => cleanup()); client.onActivate(() => { diff --git a/desktop/plugins/public/cpu/package.json b/desktop/plugins/public/cpu/package.json index 6f6c03ecd..da0f5d627 100644 --- a/desktop/plugins/public/cpu/package.json +++ b/desktop/plugins/public/cpu/package.json @@ -24,5 +24,8 @@ "icon": "underline", "bugs": { "url": "https://github.com/facebook/flipper/issues" + }, + "dependencies": { + "fs-extra": "^10.0.0" } } diff --git a/desktop/plugins/public/crash_reporter/index.tsx b/desktop/plugins/public/crash_reporter/index.tsx index cc94eac6a..48ea1f501 100644 --- a/desktop/plugins/public/crash_reporter/index.tsx +++ b/desktop/plugins/public/crash_reporter/index.tsx @@ -30,7 +30,7 @@ export type CrashLog = { export function devicePlugin(client: DevicePluginClient) { let notificationID = -1; - let watcher: FSWatcher | undefined; + let watcher: Promise; const crashes = createState([], {persist: 'crashes'}); const selectedCrash = createState(); @@ -70,7 +70,14 @@ export function devicePlugin(client: DevicePluginClient) { } client.onDestroy(() => { - watcher?.close(); + watcher + .then((watcher) => watcher?.close()) + .catch((e) => + console.error( + '[crash_reporter] FSWatcher failed resoving on destroy:', + e, + ), + ); }); return { diff --git a/desktop/plugins/public/crash_reporter/ios-crash-utils.tsx b/desktop/plugins/public/crash_reporter/ios-crash-utils.tsx index 322556ebb..fd3d3aa40 100644 --- a/desktop/plugins/public/crash_reporter/ios-crash-utils.tsx +++ b/desktop/plugins/public/crash_reporter/ios-crash-utils.tsx @@ -8,10 +8,9 @@ */ import type {CrashLog} from './index'; -import fs from 'fs'; +import fs from 'fs-extra'; import os from 'os'; import path from 'path'; -import {promisify} from 'util'; import {UNKNOWN_CRASH_REASON} from './crash-utils'; export function parseIosCrash(content: string) { @@ -64,35 +63,34 @@ export function parsePath(content: string): string | null { return path.trim(); } -export function addFileWatcherForiOSCrashLogs( +export async function addFileWatcherForiOSCrashLogs( serial: string, reportCrash: (payload: CrashLog) => void, ) { const dir = path.join(os.homedir(), 'Library', 'Logs', 'DiagnosticReports'); - if (!fs.existsSync(dir)) { + if (!(await fs.pathExists(dir))) { // Directory doesn't exist return; } - return fs.watch(dir, (_eventType, filename) => { + return fs.watch(dir, async (_eventType, filename) => { // We just parse the crash logs with extension `.crash` const checkFileExtension = /.crash$/.exec(filename); if (!filename || !checkFileExtension) { return; } const filepath = path.join(dir, filename); - promisify(fs.exists)(filepath).then((exists) => { - if (!exists) { + const exists = await fs.pathExists(filepath); + if (!exists) { + return; + } + fs.readFile(filepath, 'utf8', function (err, data) { + if (err) { + console.warn('Failed to read crash file', err); return; } - fs.readFile(filepath, 'utf8', function (err, data) { - if (err) { - console.warn('Failed to read crash file', err); - return; - } - if (shouldShowiOSCrashNotification(serial, data)) { - reportCrash(parseIosCrash(data)); - } - }); + if (shouldShowiOSCrashNotification(serial, data)) { + reportCrash(parseIosCrash(data)); + } }); }); } diff --git a/desktop/plugins/public/crash_reporter/package.json b/desktop/plugins/public/crash_reporter/package.json index abf349aac..287adabf8 100644 --- a/desktop/plugins/public/crash_reporter/package.json +++ b/desktop/plugins/public/crash_reporter/package.json @@ -32,6 +32,8 @@ "url": "https://fb.workplace.com/groups/220760072184928/" }, "dependencies": { + "@types/fs-extra": "^9.0.12", + "fs-extra": "^10.0.0", "unicode-substring": "^1.0.0" }, "peerDependencies": { diff --git a/desktop/plugins/public/databases/DatabaseDetailSidebar.tsx b/desktop/plugins/public/databases/DatabaseDetailSidebar.tsx index b09c82067..2c1b5966e 100644 --- a/desktop/plugins/public/databases/DatabaseDetailSidebar.tsx +++ b/desktop/plugins/public/databases/DatabaseDetailSidebar.tsx @@ -39,15 +39,6 @@ type DatabaseDetailSidebarProps = { onSave?: ((changes: {[key: string]: string | null}) => void) | undefined; }; -const EditTriggerSection = styled.div({ - display: 'flex', - justifyContent: 'flex-end', - width: '100%', - paddingTop: '3px', - paddingBottom: '3px', - paddingRight: '10px', -}); - const TableDetailRow = styled.div({ borderBottom: `1px solid ${theme.dividerColor}`, padding: 8, diff --git a/desktop/plugins/public/databases/index.tsx b/desktop/plugins/public/databases/index.tsx index fd4fe03fd..759ece53e 100644 --- a/desktop/plugins/public/databases/index.tsx +++ b/desktop/plugins/public/databases/index.tsx @@ -468,21 +468,27 @@ export function plugin(client: PluginClient) { !previousState.outdatedDatabaseList && newState.outdatedDatabaseList ) { - client.send('databaseList', {}).then((databases) => { - updateDatabases({ - databases, - }); - }); + client + .send('databaseList', {}) + .then((databases) => { + updateDatabases({ + databases, + }); + }) + .catch((e) => console.error('databaseList request failed:', e)); } }, ); client.onConnect(() => { - client.send('databaseList', {}).then((databases) => { - updateDatabases({ - databases, - }); - }); + client + .send('databaseList', {}) + .then((databases) => { + updateDatabases({ + databases, + }); + }) + .catch((e) => console.error('initial databaseList request failed:', e)); const loadedFavoritesJson = localStorage.getItem( FAVORITES_LOCAL_STORAGE_KEY, ); diff --git a/desktop/plugins/public/fresco/index.tsx b/desktop/plugins/public/fresco/index.tsx index 8753a69dd..173eb2134 100644 --- a/desktop/plugins/public/fresco/index.tsx +++ b/desktop/plugins/public/fresco/index.tsx @@ -162,7 +162,7 @@ export function plugin(client: PluginClient) { }); imageDataList.push(imageData); } catch (e) { - console.error(e); + console.error('[fresco] getImage failed:', e); } } @@ -232,10 +232,13 @@ export function plugin(client: PluginClient) { return; } debugLog('<- getImage requested for ' + imageId); - client.send('getImage', {imageId}).then((image: ImageData) => { - debugLog('-> getImage ' + imageId + ' returned'); - imagePool.get()?._fetchCompleted(image); - }); + client + .send('getImage', {imageId}) + .then((image: ImageData) => { + debugLog('-> getImage ' + imageId + ' returned'); + imagePool.get()?._fetchCompleted(image); + }) + .catch((e) => console.error('[fresco] getImage failed:', e)); } function onImageSelected(selectedImage: ImageId) { @@ -357,7 +360,8 @@ export function plugin(client: PluginClient) { selectedSurfaces.get(), coldStartFilter.get(), ); - }); + }) + .catch((e) => console.error('[fresco] listImages failed:', e)); } return { diff --git a/desktop/plugins/public/hermesdebuggerrn/index.tsx b/desktop/plugins/public/hermesdebuggerrn/index.tsx index 3aa954040..6834858ae 100644 --- a/desktop/plugins/public/hermesdebuggerrn/index.tsx +++ b/desktop/plugins/public/hermesdebuggerrn/index.tsx @@ -92,50 +92,48 @@ export default class extends FlipperDevicePlugin { checkDebugTargets = () => { fetch(`${METRO_URL.toString()}json`) .then((res) => res.json()) - .then( - (result) => { - // We only want to use the Chrome Reload targets. - const targets = result.filter( - (target: any) => - target.title === - 'React Native Experimental (Improved Chrome Reloads)', - ); + .then((result) => { + // We only want to use the Chrome Reload targets. + const targets = result.filter( + (target: any) => + target.title === + 'React Native Experimental (Improved Chrome Reloads)', + ); - // Find the currently selected target. - // If the current selectedTarget isn't returned, clear it. - let currentlySelected = null; - if (this.state.selectedTarget != null) { - for (const target of result) { - if ( - this.state.selectedTarget?.webSocketDebuggerUrl === - target.webSocketDebuggerUrl - ) { - currentlySelected = this.state.selectedTarget; - } + // Find the currently selected target. + // If the current selectedTarget isn't returned, clear it. + let currentlySelected = null; + if (this.state.selectedTarget != null) { + for (const target of result) { + if ( + this.state.selectedTarget?.webSocketDebuggerUrl === + target.webSocketDebuggerUrl + ) { + currentlySelected = this.state.selectedTarget; } } + } - // Auto-select the first target if there is one, - // but don't change the one that's already selected. - const selectedTarget = - currentlySelected == null && targets.length === 1 - ? targets[0] - : currentlySelected; + // Auto-select the first target if there is one, + // but don't change the one that's already selected. + const selectedTarget = + currentlySelected == null && targets.length === 1 + ? targets[0] + : currentlySelected; - this.setState({ - error: null, - targets, - selectedTarget, - }); - }, - (error) => { - this.setState({ - targets: null, - selectedTarget: null, - error, - }); - }, - ); + this.setState({ + error: null, + targets, + selectedTarget, + }); + }) + .catch((error) => { + this.setState({ + targets: null, + selectedTarget: null, + error, + }); + }); }; handleSelect = (selectedTarget: Target) => this.setState({selectedTarget}); diff --git a/desktop/plugins/public/layout/Inspector.tsx b/desktop/plugins/public/layout/Inspector.tsx index 7b49dde9a..1baf08171 100644 --- a/desktop/plugins/public/layout/Inspector.tsx +++ b/desktop/plugins/public/layout/Inspector.tsx @@ -119,13 +119,16 @@ export default class Inspector extends Component { if (!this.props.client.isConnected) { return; } - this.props.client.call(this.call().GET_ROOT).then((root: Element) => { - this.props.setPersistedState({ - [this.props.ax ? 'rootAXElement' : 'rootElement']: root.id, - }); - this.updateElement(root.id, {...root, expanded: true}); - this.performInitialExpand(root); - }); + this.props.client + .call(this.call().GET_ROOT) + .then((root: Element) => { + this.props.setPersistedState({ + [this.props.ax ? 'rootAXElement' : 'rootElement']: root.id, + }); + this.updateElement(root.id, {...root, expanded: true}); + this.performInitialExpand(root); + }) + .catch((e) => console.error('[layout] GET_ROOT failed:', e)); this.props.client.subscribe( this.call().INVALIDATE, @@ -419,13 +422,15 @@ export default class Inspector extends Component { if (shouldExpand) { this.updateElement(id, {expanded: shouldExpand}); } - this.getChildren(id, {}).then((children) => { - if (deep) { - children.forEach((child) => - this.onElementExpanded(child.id, deep, shouldExpand), - ); - } - }); + this.getChildren(id, {}) + .then((children) => { + if (deep) { + children.forEach((child) => + this.onElementExpanded(child.id, deep, shouldExpand), + ); + } + }) + .catch((e) => console.error('[layout] getChildren failed:', e)); if (!shouldExpand) { this.updateElement(id, {expanded: shouldExpand}); } diff --git a/desktop/plugins/public/layout/Search.tsx b/desktop/plugins/public/layout/Search.tsx index b1ed9d502..4a5478b42 100644 --- a/desktop/plugins/public/layout/Search.tsx +++ b/desktop/plugins/public/layout/Search.tsx @@ -101,7 +101,8 @@ export default class Search extends Component { .call('getSearchResults', {query, axEnabled: this.props.inAXMode}) .then((response) => this.displaySearchResults(response, this.props.inAXMode), - ); + ) + .catch((e) => console.log('[layout] getSearchResults failed:', e)); } } diff --git a/desktop/plugins/public/layout/index.tsx b/desktop/plugins/public/layout/index.tsx index bea230f00..03c416544 100644 --- a/desktop/plugins/public/layout/index.tsx +++ b/desktop/plugins/public/layout/index.tsx @@ -218,9 +218,12 @@ export default class LayoutPlugin extends FlipperPlugin< if (this.client.isConnected) { // persist searchActive state when moving between plugins to prevent multiple // TouchOverlayViews since we can't edit the view heirarchy in onDisconnect - this.client.call('isSearchActive').then(({isSearchActive}) => { - this.setState({inTargetMode: isSearchActive}); - }); + this.client + .call('isSearchActive') + .then(({isSearchActive}) => { + this.setState({inTargetMode: isSearchActive}); + }) + .catch((e) => console.error('[layout] isSearchActive call failed:', e)); // disable target mode after this.client.subscribe('select', () => { diff --git a/desktop/plugins/public/navigation/plugin.tsx b/desktop/plugins/public/navigation/plugin.tsx index 48b5e52dd..3d171198c 100644 --- a/desktop/plugins/public/navigation/plugin.tsx +++ b/desktop/plugins/public/navigation/plugin.tsx @@ -94,9 +94,11 @@ export function plugin(client: PluginClient) { console.error('[Navigation] Failed to find appMatchPatterns', e); }); - readBookmarksFromDB().then((bookmarksData) => { - bookmarks.set(bookmarksData); - }); + readBookmarksFromDB() + .then((bookmarksData) => { + bookmarks.set(bookmarksData); + }) + .catch((e) => console.error('[navigation] readBookmarksFromDB failed:', e)); function navigateTo(query: string) { const filteredQuery = filterOptionalParameters(query); diff --git a/desktop/plugins/public/navigation/util/appMatchPatterns.tsx b/desktop/plugins/public/navigation/util/appMatchPatterns.tsx index 7b516b65c..770e39b5b 100644 --- a/desktop/plugins/public/navigation/util/appMatchPatterns.tsx +++ b/desktop/plugins/public/navigation/util/appMatchPatterns.tsx @@ -9,15 +9,13 @@ import fs from 'fs'; import path from 'path'; -import {BaseDevice, AndroidDevice, IOSDevice} from 'flipper'; +import {BaseDevice, AndroidDevice, IOSDevice, getAppPath} from 'flipper'; import {AppMatchPattern} from '../types'; -import {remote} from 'electron'; let patternsPath: string | undefined; function getPatternsBasePath() { - return (patternsPath = - patternsPath ?? path.join(remote.app.getAppPath(), 'facebook')); + return (patternsPath = patternsPath ?? path.join(getAppPath(), 'facebook')); } const extractAppNameFromSelectedApp = (selectedApp: string | null) => { diff --git a/desktop/plugins/public/navigation/util/indexedDB.tsx b/desktop/plugins/public/navigation/util/indexedDB.tsx index 070f7c896..38afa47fb 100644 --- a/desktop/plugins/public/navigation/util/indexedDB.tsx +++ b/desktop/plugins/public/navigation/util/indexedDB.tsx @@ -41,7 +41,9 @@ const openNavigationPluginDB: () => Promise = () => { ); openRequest.onupgradeneeded = () => { const db = openRequest.result; - initializeNavigationPluginDB(db).then(() => resolve(db)); + initializeNavigationPluginDB(db) + .then(() => resolve(db)) + .catch(reject); }; openRequest.onerror = () => reject(openRequest.error); openRequest.onsuccess = () => resolve(openRequest.result); diff --git a/desktop/plugins/public/network/index.tsx b/desktop/plugins/public/network/index.tsx index 7c579208c..fbf896e70 100644 --- a/desktop/plugins/public/network/index.tsx +++ b/desktop/plugins/public/network/index.tsx @@ -236,20 +236,23 @@ export function plugin(client: PluginClient) { } function init() { - supportsMocks(client.device).then((result) => { - const newRoutes = JSON.parse( - localStorage.getItem(LOCALSTORAGE_MOCK_ROUTE_LIST_KEY + client.appId) || - '{}', - ); - batch(() => { - routes.set(newRoutes); - isMockResponseSupported.set(result); - showMockResponseDialog.set(false); - nextRouteId.set(Object.keys(routes.get()).length); - }); + supportsMocks(client.device) + .then((result) => { + const newRoutes = JSON.parse( + localStorage.getItem( + LOCALSTORAGE_MOCK_ROUTE_LIST_KEY + client.appId, + ) || '{}', + ); + batch(() => { + routes.set(newRoutes); + isMockResponseSupported.set(result); + showMockResponseDialog.set(false); + nextRouteId.set(Object.keys(routes.get()).length); + }); - informClientMockChange(routes.get()); - }); + informClientMockChange(routes.get()); + }) + .catch((e) => console.error('[network] Failed to init mocks:', e)); // declare new variable to be called inside the interface networkRouteManager.set( diff --git a/desktop/plugins/public/network/request-mocking/NetworkRouteManager.tsx b/desktop/plugins/public/network/request-mocking/NetworkRouteManager.tsx index 7213b4cb2..57b76d662 100644 --- a/desktop/plugins/public/network/request-mocking/NetworkRouteManager.tsx +++ b/desktop/plugins/public/network/request-mocking/NetworkRouteManager.tsx @@ -13,7 +13,6 @@ import electron, {OpenDialogOptions, remote} from 'electron'; import {Atom, DataTableManager} from 'flipper-plugin'; import {createContext} from 'react'; import {Header, Request} from '../types'; -import {bodyAsString, decodeBody} from '../utils'; import {message} from 'antd'; export type Route = { @@ -142,35 +141,40 @@ export function createNetworkManager( properties: ['openFile'], filters: [{extensions: ['json'], name: 'Flipper Route Files'}], }; - remote.dialog.showOpenDialog(options).then((result) => { - const filePaths = result.filePaths; - if (filePaths.length > 0) { - fs.readFile(filePaths[0], 'utf8', (err, data) => { - if (err) { - message.error('Unable to import file'); - return; - } - const importedRoutes = JSON.parse(data); - importedRoutes?.forEach((importedRoute: Route) => { - if (importedRoute != null) { - const newNextRouteId = nextRouteId.get(); - routes.update((draft) => { - draft[newNextRouteId.toString()] = { - requestUrl: importedRoute.requestUrl, - requestMethod: importedRoute.requestMethod, - responseData: importedRoute.responseData as string, - responseHeaders: importedRoute.responseHeaders, - responseStatus: importedRoute.responseStatus, - enabled: true, - }; - }); - nextRouteId.set(newNextRouteId + 1); + remote.dialog + .showOpenDialog(options) + .then((result) => { + const filePaths = result.filePaths; + if (filePaths.length > 0) { + fs.readFile(filePaths[0], 'utf8', (err, data) => { + if (err) { + message.error('Unable to import file'); + return; } + const importedRoutes = JSON.parse(data); + importedRoutes?.forEach((importedRoute: Route) => { + if (importedRoute != null) { + const newNextRouteId = nextRouteId.get(); + routes.update((draft) => { + draft[newNextRouteId.toString()] = { + requestUrl: importedRoute.requestUrl, + requestMethod: importedRoute.requestMethod, + responseData: importedRoute.responseData as string, + responseHeaders: importedRoute.responseHeaders, + responseStatus: importedRoute.responseStatus, + enabled: true, + }; + }); + nextRouteId.set(newNextRouteId + 1); + } + }); + informClientMockChange(routes.get()); }); - informClientMockChange(routes.get()); - }); - } - }); + } + }) + .catch((e) => + console.error('[network] importRoutes dialogue failed:', e), + ); }, exportRoutes() { remote.dialog @@ -199,7 +203,10 @@ export function createNetworkManager( } }, ); - }); + }) + .catch((e) => + console.error('[network] exportRoutes saving failed:', e), + ); }, clearRoutes() { routes.set({}); diff --git a/desktop/plugins/public/sandbox/index.tsx b/desktop/plugins/public/sandbox/index.tsx index 8670d96ae..48368727a 100644 --- a/desktop/plugins/public/sandbox/index.tsx +++ b/desktop/plugins/public/sandbox/index.tsx @@ -7,9 +7,14 @@ * @format */ -import {FlipperPlugin} from 'flipper'; -import {FlexColumn} from 'flipper'; -import {ButtonGroup, Button, styled, colors} from 'flipper'; +import { + FlipperPlugin, + FlexColumn, + ButtonGroup, + Button, + styled, + colors, +} from 'flipper'; import React, {ChangeEvent} from 'react'; export type Sandbox = { @@ -75,9 +80,12 @@ export default class SandboxView extends FlipperPlugin< if (!this.client.isConnected) { return; } - this.client.call('getSandbox', {}).then((results: Array) => { - this.setState({sandboxes: results}); - }); + this.client + .call('getSandbox', {}) + .then((results: Array) => { + this.setState({sandboxes: results}); + }) + .catch((e) => console.error('[sandbox] getSandbox call failed:', e)); } onSendSandboxEnvironment = (sandbox: string) => { @@ -90,7 +98,8 @@ export default class SandboxView extends FlipperPlugin< this.setState({showFeedback: false}); }, 3000); this.setState({showFeedback: result.result}); - }); + }) + .catch((e) => console.error('[sandbox] setSandbox call failed:', e)); }; onChangeSandbox = (e: ChangeEvent) => { diff --git a/desktop/plugins/public/yarn.lock b/desktop/plugins/public/yarn.lock index ca4421033..55941118c 100644 --- a/desktop/plugins/public/yarn.lock +++ b/desktop/plugins/public/yarn.lock @@ -165,6 +165,13 @@ resolved "https://registry.yarnpkg.com/@types/dateformat/-/dateformat-3.0.1.tgz#98d747a2e5e9a56070c6bf14e27bff56204e34cc" integrity sha512-KlPPdikagvL6ELjWsljbyDIPzNCeliYkqRpI+zea99vBBbCIA5JNshZAwQKTON139c87y9qvTFVgkFd14rtS4g== +"@types/fs-extra@^9.0.12": + version "9.0.12" + resolved "https://registry.yarnpkg.com/@types/fs-extra/-/fs-extra-9.0.12.tgz#9b8f27973df8a7a3920e8461517ebf8a7d4fdfaf" + integrity sha512-I+bsBr67CurCGnSenZZ7v94gd3tc3+Aj2taxMT4yu4ABLuOgOjeFxX3dokG24ztSRg5tnT00sL8BszO7gSMoIw== + dependencies: + "@types/node" "*" + "@types/hoist-non-react-statics@^3.3.0": version "3.3.1" resolved "https://registry.yarnpkg.com/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz#1124aafe5118cb591977aeb1ceaaed1070eb039f" @@ -709,6 +716,15 @@ fragment-cache@^0.2.1: dependencies: map-cache "^0.2.2" +fs-extra@^10.0.0: + version "10.0.0" + resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-10.0.0.tgz#9ff61b655dde53fb34a82df84bb214ce802e17c1" + integrity sha512-C5owb14u9eJwizKGdchcDUQeFtlSHHthBk8pbX9Vc1PFZrLombudjDnNns88aYslCyF6IY5SUw3Roz6xShcEIQ== + dependencies: + graceful-fs "^4.2.0" + jsonfile "^6.0.1" + universalify "^2.0.0" + fs-extra@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-4.0.3.tgz#0d852122e5bc5beb453fb028e9c0c9bf36340c94" @@ -759,6 +775,11 @@ graceful-fs@^4.1.11, graceful-fs@^4.1.2, graceful-fs@^4.1.6: resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== +graceful-fs@^4.2.0: + version "4.2.8" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.8.tgz#e412b8d33f5e006593cbd3cee6df9f2cebbe802a" + integrity sha512-qkIilPUYcNhJpd33n0GBXTB1MMPp14TxEsEs0pTrsSVucApsYzW5V+Q8Qxhik6KU3evy+qkAAowTByymK0avdg== + has-flag@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" @@ -956,6 +977,15 @@ jsonfile@^4.0.0: optionalDependencies: graceful-fs "^4.1.6" +jsonfile@^6.0.1: + version "6.1.0" + resolved "https://registry.yarnpkg.com/jsonfile/-/jsonfile-6.1.0.tgz#bc55b2634793c679ec6403094eb13698a6ec0aae" + integrity sha512-5dgndWOriYSm5cnYaJNhalLNDKOqFwyDB/rr1E9ZsGciGvKPs8R2xYGCacuf3z6K1YKDz182fd+fY3cn3pMqXQ== + dependencies: + universalify "^2.0.0" + optionalDependencies: + graceful-fs "^4.1.6" + kind-of@^3.0.2, kind-of@^3.0.3, kind-of@^3.2.0: version "3.2.2" resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-3.2.2.tgz#31ea21a734bab9bbb0f32466d893aea51e4a3c64" @@ -1611,6 +1641,11 @@ universalify@^0.1.0: resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66" integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg== +universalify@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/universalify/-/universalify-2.0.0.tgz#75a4984efedc4b08975c5aeb73f530d02df25717" + integrity sha512-hAZsKq7Yy11Zu1DE0OzWjw7nnLZmJZYTDZZyEFHZdUhV8FkH5MCfoU1XMaxXovpyW5nq5scPqq0ZDP9Zyl04oQ== + unset-value@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/unset-value/-/unset-value-1.0.0.tgz#8376873f7d2335179ffb1e6fc3a8ed0dfc8ab559" diff --git a/desktop/plugins/yarn.lock b/desktop/plugins/yarn.lock index 97e51c0a0..0991cc6a7 100644 --- a/desktop/plugins/yarn.lock +++ b/desktop/plugins/yarn.lock @@ -56,6 +56,11 @@ p-map@^4.0.0: dependencies: aggregate-error "^3.0.0" +promisify-child-process@^4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/promisify-child-process/-/promisify-child-process-4.1.1.tgz#290659e079f9c7bd46708404d4488a1a6b802686" + integrity sha512-/sRjHZwoXf1rJ+8s4oWjYjGRVKNK1DUnqfRC1Zek18pl0cN6k3yJ1cCbqd0tWNe4h0Gr+SY4vR42N33+T82WkA== + universalify@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/universalify/-/universalify-1.0.0.tgz#b61a1da173e8435b2fe3c67d29b9adf8594bd16d"