Skip to content

Commit

Permalink
refactor: replace a few any-s with proper types (#25681)
Browse files Browse the repository at this point in the history
  • Loading branch information
miniak committed Oct 8, 2020
1 parent 603f924 commit fb11a12
Show file tree
Hide file tree
Showing 19 changed files with 170 additions and 53 deletions.
6 changes: 3 additions & 3 deletions lib/asar/fs-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,15 @@ const v8Util = process._linkedBinding('electron_common_v8_util');

const Module = require('module');

const Promise: PromiseConstructor = global.Promise as any;
const Promise: PromiseConstructor = global.Promise;

const envNoAsar = process.env.ELECTRON_NO_ASAR &&
process.type !== 'browser' &&
process.type !== 'renderer';
const isAsarDisabled = () => process.noAsar || envNoAsar;

const internalBinding = (process as any).internalBinding;
delete (process as any).internalBinding;
const internalBinding = process.internalBinding!;
delete process.internalBinding;

const nextTick = (functionToCall: Function, args: any[] = []) => {
process.nextTick(() => functionToCall(...args));
Expand Down
2 changes: 1 addition & 1 deletion lib/browser/api/base-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { BaseWindow } = process._linkedBinding('electron_browser_base_window') as

Object.setPrototypeOf(BaseWindow.prototype, EventEmitter.prototype);

(BaseWindow.prototype as any)._init = function () {
BaseWindow.prototype._init = function () {
// Avoid recursive require.
const { app } = require('electron');

Expand Down
4 changes: 2 additions & 2 deletions lib/browser/api/browser-window.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ const { BrowserWindow } = process._linkedBinding('electron_browser_window') as {

Object.setPrototypeOf(BrowserWindow.prototype, BaseWindow.prototype);

(BrowserWindow.prototype as any)._init = function (this: BWT) {
BrowserWindow.prototype._init = function (this: BWT) {
// Call parent class's _init.
(BaseWindow.prototype as any)._init.call(this);
BaseWindow.prototype._init.call(this);

// Avoid recursive require.
const { app } = require('electron');
Expand Down
4 changes: 2 additions & 2 deletions lib/browser/api/screen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@ let _screen: Electron.Screen;
// side-effecting and calling createScreen upon import of this module, instead
// we export a proxy which lazily calls createScreen on first access.
export default new Proxy({}, {
get: (target, prop) => {
get: (target, prop: keyof Electron.Screen) => {
if (_screen === undefined) {
_screen = createScreen();
}
const v = (_screen as any)[prop];
const v = _screen[prop];
if (typeof v === 'function') {
return v.bind(_screen);
}
Expand Down
6 changes: 3 additions & 3 deletions lib/browser/devtools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const assertChromeDevTools = function (contents: Electron.WebContents, api: stri
}
};

ipcMainInternal.handle('ELECTRON_INSPECTOR_CONTEXT_MENU', function (event: Electron.IpcMainInvokeEvent, items: ContextMenuItem[], isEditMenu: boolean) {
ipcMainInternal.handle('ELECTRON_INSPECTOR_CONTEXT_MENU', function (event, items: ContextMenuItem[], isEditMenu: boolean) {
return new Promise(resolve => {
assertChromeDevTools(event.sender, 'window.InspectorFrontendHost.showContextMenuAtPoint()');

Expand All @@ -72,7 +72,7 @@ ipcMainInternal.handle('ELECTRON_INSPECTOR_CONTEXT_MENU', function (event: Elect
});
});

ipcMainInternal.handle('ELECTRON_INSPECTOR_SELECT_FILE', async function (event: Electron.IpcMainInvokeEvent) {
ipcMainInternal.handle('ELECTRON_INSPECTOR_SELECT_FILE', async function (event) {
assertChromeDevTools(event.sender, 'window.UI.createFileSelectorElement()');

const result = await dialog.showOpenDialog({});
Expand All @@ -84,7 +84,7 @@ ipcMainInternal.handle('ELECTRON_INSPECTOR_SELECT_FILE', async function (event:
return [path, data];
});

ipcMainUtils.handleSync('ELECTRON_INSPECTOR_CONFIRM', async function (event: Electron.IpcMainInvokeEvent, message: string = '', title: string = '') {
ipcMainUtils.handleSync('ELECTRON_INSPECTOR_CONFIRM', async function (event, message: string = '', title: string = '') {
assertChromeDevTools(event.sender, 'window.confirm()');

const options = {
Expand Down
6 changes: 3 additions & 3 deletions lib/browser/guest-window-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -266,8 +266,8 @@ export function internalWindowOpen (event: ElectronInternal.IpcMainInternalEvent
}
}

const makeSafeHandler = function<T> (handler: (event: Electron.IpcMainInvokeEvent, guestContents: Electron.webContents, ...args: any[]) => T) {
return (event: Electron.IpcMainInvokeEvent, guestId: number, ...args: any[]) => {
const makeSafeHandler = function<T, Event> (handler: (event: Event, guestContents: Electron.webContents, ...args: any[]) => T) {
return (event: Event, guestId: number, ...args: any[]) => {
// Access webContents via electron to prevent circular require.
const guestContents = electron.webContents.fromId(guestId);
if (!guestContents) {
Expand All @@ -282,7 +282,7 @@ const handleMessage = function (channel: string, handler: (event: Electron.IpcMa
ipcMainInternal.handle(channel, makeSafeHandler(handler));
};

const handleMessageSync = function (channel: string, handler: (event: Electron.IpcMainInvokeEvent, guestContents: Electron.webContents, ...args: any[]) => any) {
const handleMessageSync = function (channel: string, handler: (event: ElectronInternal.IpcMainInternalEvent, guestContents: Electron.webContents, ...args: any[]) => any) {
ipcMainUtils.handleSync(channel, makeSafeHandler(handler));
};

Expand Down
4 changes: 2 additions & 2 deletions lib/browser/ipc-main-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ export class IpcMainImpl extends EventEmitter {
}
this._invokeHandlers.set(method, async (e, ...args) => {
try {
(e as any)._reply(await Promise.resolve(fn(e, ...args)));
e._reply(await Promise.resolve(fn(e, ...args)));
} catch (err) {
(e as any)._throw(err);
e._throw(err);
}
});
}
Expand Down
2 changes: 1 addition & 1 deletion lib/browser/ipc-main-internal-utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';

type IPCHandler = (event: Electron.IpcMainInvokeEvent, ...args: any[]) => any
type IPCHandler = (event: ElectronInternal.IpcMainInternalEvent, ...args: any[]) => any

export const handleSync = function <T extends IPCHandler> (channel: string, handler: T) {
ipcMainInternal.on(channel, async (event, ...args) => {
Expand Down
10 changes: 5 additions & 5 deletions lib/browser/navigation-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ ipcMainInternal.on('ELECTRON_NAVIGATION_CONTROLLER_GO_TO_OFFSET', function (even
});

ipcMainInternal.on('ELECTRON_NAVIGATION_CONTROLLER_LENGTH', function (event) {
event.returnValue = (event.sender as any).length();
event.returnValue = event.sender.length();
});

// JavaScript implementation of Chromium's NavigationController.
Expand All @@ -39,7 +39,7 @@ export class NavigationController extends EventEmitter {
this.currentIndex++;
this.history.push(this.webContents._getURL());
}
this.webContents.on('navigation-entry-committed' as any, (event: any, url: string, inPage: boolean, replaceEntry: boolean) => {
this.webContents.on('navigation-entry-committed' as any, (event: Electron.Event, url: string, inPage: boolean, replaceEntry: boolean) => {
if (this.inPageIndex > -1 && !inPage) {
// Navigated to a new page, clear in-page mark.
this.inPageIndex = -1;
Expand Down Expand Up @@ -82,14 +82,14 @@ export class NavigationController extends EventEmitter {
const finishListener = () => {
resolveAndCleanup();
};
const failListener = (event: any, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
const failListener = (event: Electron.Event, errorCode: number, errorDescription: string, validatedURL: string, isMainFrame: boolean) => {
if (isMainFrame) {
rejectAndCleanup(errorCode, errorDescription, validatedURL);
}
};

let navigationStarted = false;
const navigationListener = (event: any, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
const navigationListener = (event: Electron.Event, url: string, isSameDocument: boolean, isMainFrame: boolean) => {
if (isMainFrame) {
if (navigationStarted && !isSameDocument) {
// the webcontents has started another unrelated navigation in the
Expand Down Expand Up @@ -159,7 +159,7 @@ export class NavigationController extends EventEmitter {
return this.webContents._loadURL(this.getURL(), {
extraHeaders: 'pragma: no-cache\n',
reloadIgnoringCache: true
} as any);
});
}

canGoBack () {
Expand Down
7 changes: 3 additions & 4 deletions lib/browser/remote/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,12 @@ const FUNCTION_PROPERTIES = [

type RendererFunctionId = [string, number] // [contextId, funcId]
type FinalizerInfo = { id: RendererFunctionId, webContents: electron.WebContents, frameId: number };
type WeakRef<T> = { deref(): T | undefined }
type CallIntoRenderer = (...args: any[]) => void

// The remote functions in renderer processes.
const rendererFunctionCache = new Map<string, WeakRef<CallIntoRenderer>>();
// eslint-disable-next-line no-undef
const finalizationRegistry = new (globalThis as any).FinalizationRegistry((fi: FinalizerInfo) => {
const finalizationRegistry = new FinalizationRegistry((fi: FinalizerInfo) => {
const mapKey = fi.id[0] + '~' + fi.id[1];
const ref = rendererFunctionCache.get(mapKey);
if (ref !== undefined && ref.deref() === undefined) {
Expand All @@ -45,7 +44,7 @@ function getCachedRendererFunction (id: RendererFunctionId): CallIntoRenderer |
}
function setCachedRendererFunction (id: RendererFunctionId, wc: electron.WebContents, frameId: number, value: CallIntoRenderer) {
// eslint-disable-next-line no-undef
const wr = new (globalThis as any).WeakRef(value) as WeakRef<CallIntoRenderer>;
const wr = new WeakRef<CallIntoRenderer>(value);
const mapKey = id[0] + '~' + id[1];
rendererFunctionCache.set(mapKey, wr);
finalizationRegistry.register(value, {
Expand Down Expand Up @@ -263,7 +262,7 @@ const unwrapArgs = function (sender: electron.WebContents, frameId: number, cont
const callIntoRenderer = function (this: any, ...args: any[]) {
let succeed = false;
if (!sender.isDestroyed()) {
succeed = (sender as any)._sendToFrameInternal(frameId, 'ELECTRON_RENDERER_CALLBACK', contextId, meta.id, valueToMeta(sender, contextId, args));
succeed = sender._sendToFrameInternal(frameId, 'ELECTRON_RENDERER_CALLBACK', contextId, meta.id, valueToMeta(sender, contextId, args));
}
if (!succeed) {
removeRemoteListenersAndLogWarning(this, callIntoRenderer);
Expand Down
16 changes: 8 additions & 8 deletions lib/browser/rpc-server.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { app } from 'electron/main';
import type { IpcMainInvokeEvent, WebContents } from 'electron/main';
import type { WebContents } from 'electron/main';
import { clipboard, crashReporter, nativeImage } from 'electron/common';
import * as fs from 'fs';
import { ipcMainInternal } from '@electron/internal/browser/ipc-main-internal';
Expand All @@ -25,15 +25,15 @@ const logStack = function (contents: WebContents, code: string, stack: string) {
};

// Implements window.close()
ipcMainInternal.on('ELECTRON_BROWSER_WINDOW_CLOSE', function (event: ElectronInternal.IpcMainInternalEvent) {
ipcMainInternal.on('ELECTRON_BROWSER_WINDOW_CLOSE', function (event) {
const window = event.sender.getOwnerBrowserWindow();
if (window) {
window.close();
}
event.returnValue = null;
});

ipcMainInternal.handle('ELECTRON_BROWSER_GET_LAST_WEB_PREFERENCES', function (event: IpcMainInvokeEvent) {
ipcMainInternal.handle('ELECTRON_BROWSER_GET_LAST_WEB_PREFERENCES', function (event) {
return event.sender.getLastWebPreferences();
});

Expand All @@ -49,7 +49,7 @@ const allowedClipboardMethods = (() => {
}
})();

ipcMainUtils.handleSync('ELECTRON_BROWSER_CLIPBOARD_SYNC', function (event: IpcMainInvokeEvent, method: string, ...args: any[]) {
ipcMainUtils.handleSync('ELECTRON_BROWSER_CLIPBOARD_SYNC', function (event, method: string, ...args: any[]) {
if (!allowedClipboardMethods.has(method)) {
throw new Error(`Invalid method: ${method}`);
}
Expand All @@ -60,7 +60,7 @@ ipcMainUtils.handleSync('ELECTRON_BROWSER_CLIPBOARD_SYNC', function (event: IpcM
if (BUILDFLAG(ENABLE_DESKTOP_CAPTURER)) {
const desktopCapturer = require('@electron/internal/browser/desktop-capturer');

ipcMainInternal.handle('ELECTRON_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', async function (event: IpcMainInvokeEvent, options: Electron.SourcesOptions, stack: string) {
ipcMainInternal.handle('ELECTRON_BROWSER_DESKTOP_CAPTURER_GET_SOURCES', async function (event, options: Electron.SourcesOptions, stack: string) {
logStack(event.sender, 'desktopCapturer.getSources()', stack);
const customEvent = emitCustomEvent(event.sender, 'desktop-capturer-get-sources');

Expand Down Expand Up @@ -88,7 +88,7 @@ const getPreloadScript = async function (preloadPath: string) {
return { preloadPath, preloadSrc, preloadError };
};

ipcMainUtils.handleSync('ELECTRON_BROWSER_SANDBOX_LOAD', async function (event: IpcMainInvokeEvent) {
ipcMainUtils.handleSync('ELECTRON_BROWSER_SANDBOX_LOAD', async function (event) {
const preloadPaths = event.sender._getPreloadPaths();
const webPreferences = event.sender.getLastWebPreferences() || {};

Expand All @@ -109,7 +109,7 @@ ipcMainUtils.handleSync('ELECTRON_BROWSER_SANDBOX_LOAD', async function (event:
};
});

ipcMainInternal.on('ELECTRON_BROWSER_PRELOAD_ERROR', function (event: ElectronInternal.IpcMainInternalEvent, preloadPath: string, error: Error) {
ipcMainInternal.on('ELECTRON_BROWSER_PRELOAD_ERROR', function (event, preloadPath: string, error: Error) {
event.sender.emit('preload-error', event, preloadPath, error);
});

Expand All @@ -125,7 +125,7 @@ ipcMainUtils.handleSync('ELECTRON_CRASH_REPORTER_GET_UPLOAD_TO_SERVER', () => {
return crashReporter.getUploadToServer();
});

ipcMainUtils.handleSync('ELECTRON_CRASH_REPORTER_SET_UPLOAD_TO_SERVER', (event: IpcMainInvokeEvent, uploadToServer: boolean) => {
ipcMainUtils.handleSync('ELECTRON_CRASH_REPORTER_SET_UPLOAD_TO_SERVER', (event, uploadToServer: boolean) => {
return crashReporter.setUploadToServer(uploadToServer);
});

Expand Down
6 changes: 3 additions & 3 deletions lib/common/api/deprecate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const deprecate: ElectronInternal.DeprecationUtil = {
return function (this: any) {
warn();
fn.apply(this, arguments);
};
} as unknown as typeof fn;
},

// change the name of a function
Expand All @@ -52,15 +52,15 @@ const deprecate: ElectronInternal.DeprecationUtil = {
return function (this: any) {
warn();
return fn.apply(this, arguments);
};
} as unknown as typeof fn;
},

moveAPI<T extends Function> (fn: T, oldUsage: string, newUsage: string): T {
const warn = warnOnce(oldUsage, newUsage);
return function (this: any) {
warn();
return fn.apply(this, arguments);
} as any;
} as unknown as typeof fn;
},

// change the name of an event
Expand Down
2 changes: 1 addition & 1 deletion lib/common/type-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ const objectMap = function (source: Object, mapper: (value: any) => any) {
return Object.fromEntries(targetEntries);
};

function serializeNativeImage (image: any) {
function serializeNativeImage (image: Electron.NativeImage) {
const representations = [];
const scaleFactors = image.getScaleFactors();

Expand Down
2 changes: 1 addition & 1 deletion lib/renderer/inspector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function completeURL (project: string, path: string) {
}

// The DOM implementation expects (message?: string) => boolean
(window.confirm as any) = function (message: string, title: string) {
window.confirm = function (message?: string, title?: string) {
return ipcRendererUtils.invokeSync('ELECTRON_INSPECTOR_CONFIRM', message, title) as boolean;
};

Expand Down
2 changes: 1 addition & 1 deletion lib/renderer/web-view/web-view-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ export const setupMethods = (WebViewElement: typeof ElectronInternal.WebViewElem

for (const property of properties) {
Object.defineProperty(WebViewElement.prototype, property, {
get: createPropertyGetter(property) as any,
get: createPropertyGetter(property),
set: createPropertySetter(property)
});
}
Expand Down
4 changes: 2 additions & 2 deletions lib/renderer/window-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,13 +255,13 @@ export const windowSetup = (
if (!usesNativeWindowOpen) {
// TODO(MarshallOfSound): Make compatible with ctx isolation without hole-punch
// Make the browser window or guest view emit "new-window" event.
(window as any).open = function (url?: string, frameName?: string, features?: string) {
window.open = function (url?: string, frameName?: string, features?: string) {
if (url != null && url !== '') {
url = resolveURL(url, location.href);
}
const guestId = ipcRendererInternal.sendSync('ELECTRON_GUEST_WINDOW_MANAGER_WINDOW_OPEN', url, toString(frameName), toString(features));
if (guestId != null) {
return getOrCreateProxy(guestId);
return getOrCreateProxy(guestId) as any as WindowProxy;
} else {
return null;
}
Expand Down
3 changes: 1 addition & 2 deletions spec-main/api-deprecate-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,7 @@ describe('deprecate', () => {
deprecate.setHandler(m => { msg = m; });

function oldFn () { return 'hello'; }
function newFn () { return 'goodbye'; }
const deprecatedFn = deprecate.renameFunction(oldFn, newFn);
const deprecatedFn = deprecate.renameFunction(oldFn, 'newFn');
deprecatedFn();

expect(msg).to.be.a('string');
Expand Down

0 comments on commit fb11a12

Please sign in to comment.