Typescriptify the main process code (2/N)

Summary: Converted main.js and setup.js to typescript

Reviewed By: mweststrate

Differential Revision: D19972273

fbshipit-source-id: f777be737da4233de4d7df3d549206efabfeeadf
This commit is contained in:
Anton Nikolaev
2020-02-24 05:17:16 -08:00
committed by Facebook Github Bot
parent 18c259dc22
commit 0c778af679
5 changed files with 51 additions and 53 deletions

View File

@@ -20,7 +20,7 @@ import {
exportMetricsFromTrace, exportMetricsFromTrace,
} from '../src/utils/exportMetrics'; } from '../src/utils/exportMetrics';
import {listDevices} from '../src/utils/listDevices'; import {listDevices} from '../src/utils/listDevices';
import setup from '../static/setup.js'; import setup from '../static/setup';
import {getPersistentPlugins, pluginsClassMap} from '../src/utils/pluginUtils'; import {getPersistentPlugins, pluginsClassMap} from '../src/utils/pluginUtils';
import {serialize} from '../src/utils/serialization'; import {serialize} from '../src/utils/serialization';
import {getStringFromErrorLike} from '../src/utils/index'; import {getStringFromErrorLike} from '../src/utils/index';

View File

@@ -104,7 +104,7 @@ async function compileMain() {
}); });
await Metro.runBuild(config, { await Metro.runBuild(config, {
platform: 'web', platform: 'web',
entry: path.join(staticDir, 'main.js'), entry: path.join(staticDir, 'main.ts'),
out: path.join(staticDir, 'main.bundle.js'), out: path.join(staticDir, 'main.bundle.js'),
dev: false, dev: false,
minify: false, minify: false,

View File

@@ -10,23 +10,25 @@
const [s, ns] = process.hrtime(); const [s, ns] = process.hrtime();
let launchStartTime = s * 1e3 + ns / 1e6; let launchStartTime = s * 1e3 + ns / 1e6;
const {app, BrowserWindow, ipcMain, Notification} = require('electron'); import {app, BrowserWindow, ipcMain, Notification} from 'electron';
const path = require('path'); import path from 'path';
const url = require('url'); import url from 'url';
const fs = require('fs'); import fs from 'fs';
const fixPath = require('fix-path'); import fixPath from 'fix-path';
const {exec} = require('child_process'); import {exec} from 'child_process';
const compilePlugins = require('./compilePlugins'); const compilePlugins = require('./compilePlugins');
const setup = require('./setup'); import setup from './setup';
const delegateToLauncher = require('./launcher'); const delegateToLauncher = require('./launcher');
const expandTilde = require('expand-tilde'); const expandTilde = require('expand-tilde');
const yargs = require('yargs'); const yargs = require('yargs');
const VERSION: string = (global as any).__VERSION__;
// Adds system PATH folders to process.env.PATH for MacOS production bundles. // Adds system PATH folders to process.env.PATH for MacOS production bundles.
fixPath(); fixPath();
// disable electron security warnings: https://github.com/electron/electron/blob/master/docs/tutorial/security.md#security-native-capabilities-and-your-responsibility // disable electron security warnings: https://github.com/electron/electron/blob/master/docs/tutorial/security.md#security-native-capabilities-and-your-responsibility
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = true; process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
// If we are running on macOS and the app is called Flipper, we add a comment // If we are running on macOS and the app is called Flipper, we add a comment
@@ -68,7 +70,7 @@ const argv = yargs
'[Internal] Used to provide a user message from the launcher to the user.', '[Internal] Used to provide a user message from the launcher to the user.',
type: 'string', type: 'string',
}) })
.version(global.__VERSION__) .version(VERSION)
.help() .help()
.parse(process.argv.slice(1)); .parse(process.argv.slice(1));
@@ -95,11 +97,11 @@ process.env.CONFIG = JSON.stringify({
}); });
// possible reference to main app window // possible reference to main app window
let win; let win: BrowserWindow;
let appReady = false; let appReady = false;
let pluginsCompiled = false; let pluginsCompiled = false;
let deeplinkURL = argv.url; let deeplinkURL: string = argv.url;
let filePath = argv.file; let filePath: string = argv.file;
// tracking // tracking
setInterval(() => { setInterval(() => {
@@ -130,7 +132,7 @@ const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) { if (!gotTheLock) {
app.quit(); app.quit();
} else { } else {
app.on('second-instance', (event, commandLine, workingDirectory) => { app.on('second-instance', (_event, _commandLine, _workingDirectory) => {
// Someone tried to run a second instance, we should focus our window. // Someone tried to run a second instance, we should focus our window.
if (win) { if (win) {
if (win.isMinimized()) { if (win.isMinimized()) {
@@ -195,7 +197,7 @@ app.on('ready', () => {
}); });
}); });
ipcMain.on('componentDidMount', event => { ipcMain.on('componentDidMount', _event => {
if (deeplinkURL) { if (deeplinkURL) {
win.webContents.send('flipper-protocol-handler', deeplinkURL); win.webContents.send('flipper-protocol-handler', deeplinkURL);
deeplinkURL = null; deeplinkURL = null;
@@ -226,6 +228,8 @@ ipcMain.on(
// Forwarding notification events to renderer process // Forwarding notification events to renderer process
// https://electronjs.org/docs/api/notification#instance-events // https://electronjs.org/docs/api/notification#instance-events
['show', 'click', 'close', 'reply', 'action'].forEach(eventName => { ['show', 'click', 'close', 'reply', 'action'].forEach(eventName => {
// TODO: refactor this to make typescript happy
// @ts-ignore
n.on(eventName, (event, ...args) => { n.on(eventName, (event, ...args) => {
e.sender.send( e.sender.send(
'notificationEvent', 'notificationEvent',
@@ -259,10 +263,10 @@ function tryCreateWindow() {
minWidth: 800, minWidth: 800,
minHeight: 600, minHeight: 600,
center: true, center: true,
backgroundThrottling: false,
titleBarStyle: 'hiddenInset', titleBarStyle: 'hiddenInset',
vibrancy: 'sidebar', vibrancy: 'sidebar',
webPreferences: { webPreferences: {
backgroundThrottling: false,
webSecurity: false, webSecurity: false,
scrollBounce: true, scrollBounce: true,
experimentalFeatures: true, experimentalFeatures: true,
@@ -272,15 +276,15 @@ function tryCreateWindow() {
}, },
}); });
win.once('ready-to-show', () => win.show()); win.once('ready-to-show', () => win.show());
win.once('close', ({sender}) => { win.once('close', () => {
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
// Removes as a default protocol for debug builds. Because even when the // Removes as a default protocol for debug builds. Because even when the
// production application is installed, and one tries to deeplink through // production application is installed, and one tries to deeplink through
// browser, it still looks for the debug one and tries to open electron // browser, it still looks for the debug one and tries to open electron
app.removeAsDefaultProtocolClient('flipper'); app.removeAsDefaultProtocolClient('flipper');
} }
const [x, y] = sender.getPosition(); const [x, y] = win.getPosition();
const [width, height] = sender.getSize(); const [width, height] = win.getSize();
// save window position and size // save window position and size
fs.writeFileSync( fs.writeFileSync(
configPath, configPath,
@@ -295,7 +299,11 @@ function tryCreateWindow() {
}), }),
); );
}); });
if (config.lastWindowPosition.x && config.lastWindowPosition.y) { if (
config.lastWindowPosition &&
config.lastWindowPosition.x &&
config.lastWindowPosition.y
) {
win.setPosition(config.lastWindowPosition.x, config.lastWindowPosition.y); win.setPosition(config.lastWindowPosition.x, config.lastWindowPosition.y);
} }
const entryUrl = const entryUrl =

24
static/setup.d.ts vendored
View File

@@ -1,24 +0,0 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
type Config = {
pluginPaths?: string[],
disabledPlugins?: string[],
lastWindowPosition?: {
width: number,
height: number
},
updater?: boolean | undefined,
launcherMsg?: string | undefined,
};
export default function(argv: {
updater?: boolean,
launcherMsg?: string
}): {config: Config, configPath: string, flipperDir: string};

View File

@@ -7,11 +7,26 @@
* @format * @format
*/ */
const path = require('path'); import path from 'path';
const os = require('os'); import os from 'os';
const fs = require('fs'); import fs from 'fs';
module.exports = function(argv) { export type Config = {
pluginPaths?: string[];
disabledPlugins?: string[];
lastWindowPosition?: {
x: number;
y: number;
width: number;
height: number;
};
updater?: boolean | undefined;
launcherMsg?: string | undefined;
updaterEnabled?: boolean;
launcherEnabled?: boolean;
};
export default function setup(argv: any) {
// ensure .flipper folder and config exist // ensure .flipper folder and config exist
const flipperDir = path.join(os.homedir(), '.flipper'); const flipperDir = path.join(os.homedir(), '.flipper');
if (!fs.existsSync(flipperDir)) { if (!fs.existsSync(flipperDir)) {
@@ -19,16 +34,15 @@ module.exports = function(argv) {
} }
const configPath = path.join(flipperDir, 'config.json'); const configPath = path.join(flipperDir, 'config.json');
let config = { let config: Config = {
pluginPaths: [], pluginPaths: [],
disabledPlugins: [], disabledPlugins: [],
lastWindowPosition: {},
}; };
try { try {
config = { config = {
...config, ...config,
...JSON.parse(fs.readFileSync(configPath)), ...JSON.parse(fs.readFileSync(configPath).toString()),
}; };
} catch (e) { } catch (e) {
// file not readable or not parsable, overwrite it with the new config // file not readable or not parsable, overwrite it with the new config
@@ -46,4 +60,4 @@ module.exports = function(argv) {
}; };
return {config, configPath, flipperDir}; return {config, configPath, flipperDir};
}; }