Skip to content

Commit

Permalink
chore: unify types for setTimeout return type to address the NodeJS t…
Browse files Browse the repository at this point in the history
…ypes leak issue
  • Loading branch information
peter-sanderson committed Dec 3, 2024
1 parent 94a4485 commit 3f34981
Show file tree
Hide file tree
Showing 40 changed files with 103 additions and 57 deletions.
3 changes: 2 additions & 1 deletion packages/blockchain-link/src/workers/baseWebsocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import WebSocket from 'ws';

import { createDeferred, createDeferredManager, TypedEmitter } from '@trezor/utils';
import { CustomError } from '@trezor/blockchain-link-types/src/constants/errors';
import { TimerId } from '@trezor/type-utils';

interface Subscription<T> {
id: string;
Expand Down Expand Up @@ -38,7 +39,7 @@ export abstract class BaseWebsocket<T extends EventMap> extends TypedEmitter<T &
private readonly emitter: TypedEmitter<WsEvents> = this;

private ws?: WebSocket;
private pingTimeout?: ReturnType<typeof setTimeout>;
private pingTimeout?: TimerId;
private connectPromise?: Promise<void>;

protected abstract ping(): Promise<unknown>;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { TimerId } from '@trezor/type-utils';

import { JsonRpcClient } from './json-rpc';

type Options = {
Expand All @@ -11,7 +13,7 @@ const MAX_QUEUE_LENGTH = 15;
// TODO batching should in theory improve performance
export class BatchingJsonRpcClient extends JsonRpcClient {
private queue: string[] = [];
private batchTimer?: ReturnType<typeof setTimeout>;
private batchTimer?: TimerId;

private timeoutMs: number;
private maxQueueLength: number;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Status } from '@trezor/blockchain-link-types/src/electrum';
import { IntervalId } from '@trezor/type-utils';

import { ElectrumClient } from './electrum';

Expand All @@ -15,7 +16,7 @@ export class CachingElectrumClient extends ElectrumClient {
private readonly statuses: Statuses = {};
private cached = 0;
private total = 0;
private logTimer: ReturnType<typeof setInterval>;
private logTimer: IntervalId;

constructor() {
super();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Network, networks } from '@trezor/utxo-lib';
import { ElectrumAPI, BlockHeader, Version } from '@trezor/blockchain-link-types/src/electrum';
import { IntervalId } from '@trezor/type-utils';

import { JsonRpcClientOptions } from './json-rpc';
import { BatchingJsonRpcClient } from './batching';
Expand Down Expand Up @@ -91,7 +92,8 @@ export class ElectrumClient extends BatchingJsonRpcClient implements ElectrumAPI
return super.request(method, ...params);
}

private keepAliveHandle?: ReturnType<typeof setInterval>;
private keepAliveHandle?: IntervalId;

private keepAlive() {
if (!this.socket) return;
this.keepAliveHandle = setInterval(async () => {
Expand Down
3 changes: 2 additions & 1 deletion packages/blockchain-link/src/workers/ripple/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { MESSAGES, RESPONSES } from '@trezor/blockchain-link-types/src/constants
import * as utils from '@trezor/blockchain-link-utils/src/ripple';
import type { Response, SubscriptionAccountInfo, AccountInfo } from '@trezor/blockchain-link-types';
import type * as MessageTypes from '@trezor/blockchain-link-types/src/messages';
import { TimerId } from '@trezor/type-utils';

import { BaseWorker, CONTEXT, ContextType } from '../baseWorker';

Expand Down Expand Up @@ -420,7 +421,7 @@ const onRequest = (request: Request<MessageTypes.Message>) => {
};

class RippleWorker extends BaseWorker<RippleAPI> {
pingTimeout?: ReturnType<typeof setTimeout>;
pingTimeout?: TimerId;

cleanup() {
if (this.pingTimeout) {
Expand Down
5 changes: 3 additions & 2 deletions packages/blockchain-link/src/workers/solana/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import {
TOKEN_PROGRAM_PUBLIC_KEY,
} from '@trezor/blockchain-link-utils/src/solana';
import { getSuiteVersion } from '@trezor/env-utils';
import { IntervalId } from '@trezor/type-utils';

import { getBaseFee, getPriorityFee } from './fee';
import { BaseWorker, ContextType, CONTEXT } from '../baseWorker';
Expand Down Expand Up @@ -474,7 +475,7 @@ const subscribeBlock = async ({ state, connect, post }: Context) => {

const unsubscribeBlock = ({ state }: Context) => {
if (!state.getSubscription('block')) return;
const interval = state.getSubscription('block') as ReturnType<typeof setInterval>;
const interval = state.getSubscription('block') as IntervalId;
clearInterval(interval);
state.removeSubscription('block');
};
Expand Down Expand Up @@ -769,7 +770,7 @@ class SolanaWorker extends BaseWorker<SolanaAPI> {
});

if (this.state.getSubscription('block')) {
const interval = this.state.getSubscription('block') as ReturnType<typeof setInterval>;
const interval = this.state.getSubscription('block') as IntervalId;
clearInterval(interval);
this.state.removeSubscription('block');
}
Expand Down
6 changes: 2 additions & 4 deletions packages/coinjoin/src/client/CoinjoinPrison.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { TypedEmitter } from '@trezor/utils';
import { ImmediateId, TimerId } from '@trezor/type-utils';

import { CoinjoinPrisonInmate, CoinjoinPrisonEvents } from '../types/client';
import { WabiSabiProtocolErrorCode } from '../enums';
Expand Down Expand Up @@ -28,10 +29,7 @@ export interface DetainOptions {

export class CoinjoinPrison extends TypedEmitter<CoinjoinPrisonEvents> {
inmates: CoinjoinPrisonInmate[] = [];
private changeEventThrottle:
| ReturnType<typeof setImmediate>
| ReturnType<typeof setTimeout>
| undefined;
private changeEventThrottle: ImmediateId | TimerId | undefined;

constructor(initialState: CoinjoinPrisonInmate[] = []) {
super();
Expand Down
3 changes: 2 additions & 1 deletion packages/coinjoin/src/client/Status.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { TypedEmitter } from '@trezor/utils';
import { TimerId } from '@trezor/type-utils';

import * as coordinator from './coordinator';
import { transformStatus } from '../utils/roundUtils';
Expand Down Expand Up @@ -38,7 +39,7 @@ export class Status extends TypedEmitter<StatusEvents> {
mode: StatusMode = 'idle';
private settings: CoinjoinClientSettings;
private abortController: AbortController;
private statusTimeout?: ReturnType<typeof setTimeout>;
private statusTimeout?: TimerId;
private identities: string[]; // registered identities
private runningAffiliateServer = false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import React, { useState, useEffect, useCallback, forwardRef, useRef } from 'rea
import styled from 'styled-components';

import { isChanged } from '@suite-common/suite-utils';
import { TimerId } from '@trezor/type-utils';

function debounce<T extends (...args: unknown[]) => void>(
func: T,
wait: number,
): (...args: Parameters<T>) => void {
let timeout: ReturnType<typeof setTimeout> | null = null;
let timeout: TimerId | null = null;

return (...args: Parameters<T>) => {
if (timeout !== null) {
Expand Down
3 changes: 2 additions & 1 deletion packages/connect-popup/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { analytics, EventType } from '@trezor/connect-analytics';
import { getSystemInfo } from '@trezor/connect-common';
import { initLog, setLogWriter, LogWriter } from '@trezor/connect/src/utils/debug';
import { DEFAULT_DOMAIN } from '@trezor/connect/src/data/version';
import { TimerId } from '@trezor/type-utils';

import * as view from './view';
import {
Expand All @@ -46,7 +47,7 @@ const INTERVAL_HANDSHAKE_TIMEOUT_MS = 90 * 1000;
const log = initLog('@trezor/connect-popup');
const proxyLogger = initLog('@trezor/connect-webextension');

let handshakeTimeout: ReturnType<typeof setTimeout>;
let handshakeTimeout: TimerId;
let renderConnectUIPromise: Promise<void> | undefined;

// browser built-in functionality to quickly and safely escape the string
Expand Down
3 changes: 2 additions & 1 deletion packages/connect-popup/src/log.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { InfoPanel } from '@trezor/connect-ui/src/components/InfoPanel';
import { View } from '@trezor/connect-ui/src/components/View';
import { Button, Paragraph, intermediaryTheme } from '@trezor/components';
import { LogMessage } from '@trezor/connect/src/utils/debug';
import { TimerId } from '@trezor/type-utils';

interface ReactWrapperProps {
children: React.ReactNode;
Expand Down Expand Up @@ -79,7 +80,7 @@ const DownloadButton = ({ array, filename }: { array: any[]; filename: string })
};

let logDebounceCache: any[] = [];
let logDebounceTimeout: ReturnType<typeof setTimeout> | undefined;
let logDebounceTimeout: TimerId | undefined;

const logInConsole = (logs: any[]) => {
// Logs in console are debounced in order to try to make sure that
Expand Down
7 changes: 4 additions & 3 deletions packages/connect-web/src/popup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
AbstractMessageChannel,
Message,
} from '@trezor/connect-common/src/messageChannel/abstract';
import { IntervalId, TimerId } from '@trezor/type-utils';

import { showPopupRequest } from './showPopupRequest';
import { ServiceWorkerWindowChannel } from '../channels/serviceworker-window';
Expand Down Expand Up @@ -59,11 +60,11 @@ export class PopupManager extends EventEmitter {

popupPromise: Deferred<void> | undefined;

requestTimeout: ReturnType<typeof setTimeout> | undefined;
requestTimeout: TimerId | undefined;

openTimeout: ReturnType<typeof setTimeout> | undefined;
openTimeout: TimerId | undefined;

closeInterval: ReturnType<typeof setInterval> | undefined;
closeInterval: IntervalId | undefined;

extensionTabId = 0;

Expand Down
4 changes: 3 additions & 1 deletion packages/connect/src/backend/BackendManager.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { TimerId } from '@trezor/type-utils';

import { DataManager } from '../data/DataManager';
import { ERRORS } from '../constants';
import { Blockchain, BlockchainOptions } from './Blockchain';
Expand All @@ -7,7 +9,7 @@ import type { CoinInfo, BlockchainLink } from '../types';
type CoinShortcut = CoinInfo['shortcut'];
type Identity = string;
type CoinShortcutIdentity = `${CoinShortcut}/${Identity}`;
type Reconnect = { attempts: number; handle: ReturnType<typeof setTimeout> };
type Reconnect = { attempts: number; handle: TimerId };
type BackendParams = Pick<BlockchainOptions, 'coinInfo' | 'postMessage' | 'identity'>;

const DEFAULT_IDENTITY = 'default';
Expand Down
4 changes: 2 additions & 2 deletions packages/react-utils/src/hooks/useDebounce.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef } from 'react';

import { createDeferred } from '@trezor/utils';
import type { Timeout } from '@trezor/type-utils';
import type { TimerId } from '@trezor/type-utils';

type AsyncFunction = (...args: any) => Promise<any>;
type SyncFunction = (...args: any) => any;
Expand All @@ -10,7 +10,7 @@ type SyncFunction = (...args: any) => any;
// `timeout` prevents from calling '@trezor/connect' method to many times (inputs mad-clicking)
// TODO: maybe it should be converted to regular module, could be useful elsewhere
export const useDebounce = () => {
const timeout = useRef<Timeout | null>(null);
const timeout = useRef<TimerId | null>(null);

const debounce = useCallback(
async <F extends AsyncFunction | SyncFunction>(fn: F): Promise<ReturnType<F>> => {
Expand Down
4 changes: 3 additions & 1 deletion packages/suite-desktop-core/e2e/support/networkAnalyzer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { exec } from 'child_process';

import { IntervalId } from '@trezor/type-utils';

export class NetworkAnalyzer {
interval?: string | number | ReturnType<typeof setInterval>;
interval?: string | number | IntervalId;
tcp: string[];

constructor() {
Expand Down
3 changes: 2 additions & 1 deletion packages/suite-desktop-core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { HandshakeClient } from '@trezor/suite-desktop-api';
import { validateIpcMessage } from '@trezor/ipc-proxy';
import { createDeferred, createTimeoutPromise } from '@trezor/utils';
import { isMacOs } from '@trezor/env-utils';
import { TimerId } from '@trezor/type-utils';

import { ipcMain } from './typed-electron';
import { APP_NAME } from './libs/constants';
Expand Down Expand Up @@ -51,7 +52,7 @@ const createMainWindow = (winBounds: WinBounds) => {
icon: path.join(global.resourcesPath, 'images', 'icons', '512x512.png'),
});

let resizeDebounce: ReturnType<typeof setTimeout> | null = null;
let resizeDebounce: TimerId | null = null;

mainWindow.on('resize', () => {
if (resizeDebounce) return;
Expand Down
3 changes: 2 additions & 1 deletion packages/suite-desktop-core/src/hang-detect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { BrowserWindow, dialog } from 'electron';

import { validateIpcMessage } from '@trezor/ipc-proxy';
import { ElectronIpcMainInvokeEvent } from '@trezor/ipc-proxy/src/proxy-handler';
import { TimerId } from '@trezor/type-utils';

import { ipcMain } from './typed-electron';
import { APP_SRC } from './libs/constants';
Expand All @@ -27,7 +28,7 @@ export const hangDetect = (mainWindow: BrowserWindow, statePatch?: Record<string

return Promise.resolve({});
};
let timeout: ReturnType<typeof setTimeout>;
let timeout: TimerId;

const handshake = new Promise<HandshakeResult>(resolve => {
const timeoutCallback = async () => {
Expand Down
3 changes: 2 additions & 1 deletion packages/suite-desktop-core/src/libs/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { app } from 'electron';

import { isDevEnv } from '@suite-common/suite-utils';
import { ensureDirectoryExists } from '@trezor/node-utils';
import { TimerId } from '@trezor/type-utils';

import { getBuildInfo, getComputerInfo } from './info';

Expand Down Expand Up @@ -130,7 +131,7 @@ export class Logger implements ILogger {
}

private dedupeMessage?: RepeatedLogMessage;
private dedupeTimeout?: ReturnType<typeof setTimeout>;
private dedupeTimeout?: TimerId;

private handleMessage(message: LogMessage) {
if (!this.options.dedupeTimeout) {
Expand Down
6 changes: 4 additions & 2 deletions packages/suite-desktop-core/src/libs/processes/BaseProcess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import { app } from 'electron';
import path from 'path';
import { spawn, ChildProcess } from 'child_process';

import { TimerId } from '@trezor/type-utils';

import { b2t } from '../utils';

export type Status = {
Expand Down Expand Up @@ -31,7 +33,7 @@ export abstract class BaseProcess {
resourceName: string;
processName: string;
options: Options;
startupThrottle: ReturnType<typeof setTimeout> | null;
startupThrottle: TimerId | null;
supportedSystems = ['linux-arm64', 'linux-x64', 'mac-arm64', 'mac-x64', 'win-x64'];
stopped = false;
logger: ILogger;
Expand Down Expand Up @@ -158,7 +160,7 @@ export abstract class BaseProcess {
// that started the process, so if it fails an error is thrown to let the module knows something
// went wrong.
// eslint-disable-next-line prefer-const
let resolveTimeout: ReturnType<typeof setTimeout> | undefined;
let resolveTimeout: TimerId | undefined;
const spawnErrorHandler = (message: any) => {
// This error handler will be triggered if there is an error during spawn of the process,
// it will reject with an error so the user can be notified that something went wrong.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useEffect, useState, useMemo, useRef } from 'react';
import styled from 'styled-components';

import { Button, DropdownMenuItemProps, Row } from '@trezor/components';
import type { Timeout } from '@trezor/type-utils';
import type { TimerId } from '@trezor/type-utils';
import { StaticSessionId } from '@trezor/connect';

import { useDiscovery, useDispatch, useSelector } from 'src/hooks/suite';
Expand Down Expand Up @@ -293,7 +293,7 @@ export const MetadataLabeling = ({
const dataTestBase = `@metadata/${payload.type}/${payload.defaultValue}`;
const actionButtonsDisabled = isDiscoveryRunning || pending;
const isSubscribedToSubmitResult = useRef(payload.defaultValue);
let timeout: Timeout | undefined;
let timeout: TimerId | undefined;
useEffect(() => {
setPending(false);
setShowSuccess(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useState, useEffect, useRef } from 'react';
import styled, { css } from 'styled-components';

import { selectDevicesCount, selectDevice } from '@suite-common/wallet-core';
import type { Timeout } from '@trezor/type-utils';
import type { TimerId } from '@trezor/type-utils';
import { borders, spacingsPx } from '@trezor/theme';
import { focusStyleTransition, getFocusShadowStyle } from '@trezor/components/src/utils/utils';
import { Icon } from '@trezor/components';
Expand Down Expand Up @@ -78,8 +78,8 @@ export const DeviceSelector = () => {
const [isAnimationTriggered, setIsAnimationTriggered] = useState(false);

const countChanged = localCount && localCount !== deviceCount;
const shakeAnimationTimerRef = useRef<Timeout | undefined>(undefined);
const stateAnimationTimerRef = useRef<Timeout | undefined>(undefined);
const shakeAnimationTimerRef = useRef<TimerId | undefined>(undefined);
const stateAnimationTimerRef = useRef<TimerId | undefined>(undefined);

useEffect(
() =>
Expand Down
5 changes: 3 additions & 2 deletions packages/transport/src/sessions/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*/

import { createDeferred, Deferred, TypedEmitter } from '@trezor/utils';
import { TimerId } from '@trezor/type-utils';

import type {
EnumerateDoneRequest,
Expand Down Expand Up @@ -53,8 +54,8 @@ export class SessionsBackground
private pathInternalPathPublicMap: Record<PathInternal, PathPublic> = {};

// if lock is set, somebody is doing something with device. we have to wait
private locksQueue: { id: ReturnType<typeof setTimeout>; dfd: Deferred<void> }[] = [];
private locksTimeoutQueue: ReturnType<typeof setTimeout>[] = [];
private locksQueue: { id: TimerId; dfd: Deferred<void> }[] = [];
private locksTimeoutQueue: TimerId[] = [];
private lastSessionId = 0;
private lastPathId = 0;

Expand Down
Loading

0 comments on commit 3f34981

Please sign in to comment.