diff --git a/extension/chrome/dev/ci_unit_test.ts b/extension/chrome/dev/ci_unit_test.ts index 13a79c9972f..25d5a13a367 100644 --- a/extension/chrome/dev/ci_unit_test.ts +++ b/extension/chrome/dev/ci_unit_test.ts @@ -22,7 +22,7 @@ import { Gmail } from '../../js/common/api/email-provider/gmail/gmail.js'; * importing all libs that are tested in ci tests * add lib name below, let the IDE resolve the actual import */ -const libs: any[] = [ +const libs: unknown[] = [ ApiErr, Attachment, AttachmentUI, diff --git a/extension/chrome/elements/attachment.ts b/extension/chrome/elements/attachment.ts index bcf1495b4d3..a032b321d85 100644 --- a/extension/chrome/elements/attachment.ts +++ b/extension/chrome/elements/attachment.ts @@ -136,7 +136,7 @@ export class AttachmentDownloadView extends View { } }; - protected renderErr = (e: any) => { + protected renderErr = (e: unknown) => { if (ApiErr.isAuthErr(e)) { BrowserMsg.send.notificationShowAuthPopupNeeded(this.parentTabId, { acctEmail: this.acctEmail }); Xss.sanitizeRender('body', `Error downloading file - google auth needed. ${Ui.retryLink()}`); diff --git a/extension/chrome/elements/attachment_preview.ts b/extension/chrome/elements/attachment_preview.ts index fb8da6222c7..86f54662996 100644 --- a/extension/chrome/elements/attachment_preview.ts +++ b/extension/chrome/elements/attachment_preview.ts @@ -18,7 +18,7 @@ import { Url } from '../../js/common/core/common.js'; type AttachmentType = 'img' | 'txt' | 'pdf'; -declare const pdfjsLib: any; // tslint:disable-line:ban-types +declare const pdfjsLib: { getDocument: Function }; // tslint:disable-line:ban-types View.run(class AttachmentPreviewView extends AttachmentDownloadView { protected readonly initiatorFrameId?: string; diff --git a/extension/chrome/elements/compose-modules/compose-err-module.ts b/extension/chrome/elements/compose-modules/compose-err-module.ts index 8fef8d92451..42e152e5394 100644 --- a/extension/chrome/elements/compose-modules/compose-err-module.ts +++ b/extension/chrome/elements/compose-modules/compose-err-module.ts @@ -36,7 +36,7 @@ export class ComposeErrModule extends ViewModule { return { network: async () => await Ui.modal.info(`Could not ${couldNotDoWhat} (network error). Please try again.`), auth: async () => Settings.offerToLoginWithPopupShowModalOnErr(this.view.acctEmail, undefined, `Could not ${couldNotDoWhat}.\n`), - other: async (e: any) => { + other: async (e: unknown) => { if (e instanceof Error) { e.stack = (e.stack || '') + `\n\n[compose action: ${couldNotDoWhat}]`; } else if (typeof e === 'object' && e && typeof (e as any).stack === 'undefined') { @@ -66,7 +66,7 @@ export class ComposeErrModule extends ViewModule { } }; - public handleSendErr = async (e: any, sendMsgsResult?: SendMsgsResult) => { + public handleSendErr = async (e: unknown, sendMsgsResult?: SendMsgsResult) => { this.view.errModule.debug(`handleSendErr: ${String(e)}`); if (ApiErr.isNetErr(e)) { let netErrMsg: string | undefined; diff --git a/extension/chrome/elements/compose-modules/compose-send-btn-module.ts b/extension/chrome/elements/compose-modules/compose-send-btn-module.ts index 51b8a1ad3bb..dd512308e37 100644 --- a/extension/chrome/elements/compose-modules/compose-send-btn-module.ts +++ b/extension/chrome/elements/compose-modules/compose-send-btn-module.ts @@ -122,7 +122,7 @@ export class ComposeSendBtnModule extends ViewModule { if (result.supplementaryOperationsErrors.length) { console.error(result.supplementaryOperationsErrors); Catch.setHandledTimeout(() => { - Ui.toast(result.supplementaryOperationsErrors[0]); // tslint:disable-line:no-unsafe-any + Ui.toast(result.supplementaryOperationsErrors[0] as string); }, 0); } BrowserMsg.send.notificationShow(this.view.parentTabId, { notification: `Your ${this.view.isReplyBox ? 'reply' : 'message'} has been sent.` }); @@ -231,7 +231,7 @@ export class ComposeSendBtnModule extends ViewModule { } }; - private bindMessageId = async (externalId: string, id: string, supplementaryOperationsErrors: any[]) => { + private bindMessageId = async (externalId: string, id: string, supplementaryOperationsErrors: unknown[]) => { try { const gmailMsg = await this.view.emailProvider.msgGet(id, 'metadata'); const messageId = GmailParser.findHeader(gmailMsg, 'message-id'); @@ -249,9 +249,9 @@ export class ComposeSendBtnModule extends ViewModule { private doSendMsgs = async (msgObj: MultipleMessages): Promise => { const sentIds: string[] = []; const supplementaryOperations: Promise[] = []; - const supplementaryOperationsErrors: any[] = []; // tslint:disable-line:no-unsafe-any + const supplementaryOperationsErrors: unknown[] = []; const success: EmailParts[] = []; - const failures: { recipient: EmailParts, e: any }[] = []; + const failures: { recipient: EmailParts, e: unknown }[] = []; for (const msg of msgObj.msgs) { const msgRecipients = msg.getAllRecipients(); try { diff --git a/extension/chrome/elements/compose-modules/compose-types.ts b/extension/chrome/elements/compose-modules/compose-types.ts index 8f55ecfe9a7..722dc194317 100644 --- a/extension/chrome/elements/compose-modules/compose-types.ts +++ b/extension/chrome/elements/compose-modules/compose-types.ts @@ -67,7 +67,7 @@ export const getUniqueRecipientEmails = (recipients: ParsedRecipients) => { export type SendMsgsResult = { success: EmailParts[], - failures: { recipient: EmailParts, e: any }[], - supplementaryOperationsErrors: any[], + failures: { recipient: EmailParts, e: unknown }[], + supplementaryOperationsErrors: unknown[], sentIds: string[] }; diff --git a/extension/chrome/elements/pgp_block_modules/pgp-block-error-module.ts b/extension/chrome/elements/pgp_block_modules/pgp-block-error-module.ts index c98d6129b72..8040e7caf35 100644 --- a/extension/chrome/elements/pgp_block_modules/pgp-block-error-module.ts +++ b/extension/chrome/elements/pgp_block_modules/pgp-block-error-module.ts @@ -47,7 +47,7 @@ export class PgpBlockViewErrorModule { } }; - public handleInitializeErr = async (e: any) => { + public handleInitializeErr = async (e: unknown) => { if (ApiErr.isNetErr(e)) { await this.renderErr(`Could not load message due to network error. ${Ui.retryLink()}`, undefined); } else if (ApiErr.isAuthErr(e)) { diff --git a/extension/chrome/settings/modules/debug_api.ts b/extension/chrome/settings/modules/debug_api.ts index 35251313e4f..0ec20372cca 100644 --- a/extension/chrome/settings/modules/debug_api.ts +++ b/extension/chrome/settings/modules/debug_api.ts @@ -50,7 +50,7 @@ View.run(class DebugApiView extends View { // No need }; - private renderCallRes = (api: string, variables: Dict, result: any, error?: any) => { + private renderCallRes = (api: string, variables: Dict, result: unknown, error?: unknown) => { const r = `${api} ${JSON.stringify(variables)}
${JSON.stringify(result, undefined, 2)} (${error ? JSON.stringify(error) : 'no err'})
`; Xss.sanitizeAppend('#content', r); }; diff --git a/extension/chrome/settings/modules/my_key.ts b/extension/chrome/settings/modules/my_key.ts index 6db13fc0b1b..aaf6104f7c1 100644 --- a/extension/chrome/settings/modules/my_key.ts +++ b/extension/chrome/settings/modules/my_key.ts @@ -19,7 +19,9 @@ import { KeyStore } from '../../../js/common/platform/store/key-store.js'; import { Xss } from '../../../js/common/platform/xss.js'; import { FlowCryptWebsite } from '../../../js/common/api/flowcrypt-website.js'; -declare const ClipboardJS: any; +declare class ClipboardJS { + constructor(selector: string, options: {}); +} View.run(class MyKeyView extends View { diff --git a/extension/js/background_page/bgutils.ts b/extension/js/background_page/bgutils.ts index ad8f3b45e2a..aa76127dc2c 100644 --- a/extension/js/background_page/bgutils.ts +++ b/extension/js/background_page/bgutils.ts @@ -46,7 +46,7 @@ export class BgUtils { }); }; - public static handleStoreErr = async (e: any, reason?: 'storage_undefined' | 'db_corrupted' | 'db_denied' | 'db_failed') => { + public static handleStoreErr = async (e: unknown, reason?: 'storage_undefined' | 'db_corrupted' | 'db_denied' | 'db_failed') => { if (!reason) { if (e instanceof StoreCorruptedError) { reason = 'db_corrupted'; diff --git a/extension/js/common/api/email-provider/gmail/google-auth.ts b/extension/js/common/api/email-provider/gmail/google-auth.ts index 7902ac17c31..0e9cf9abc2d 100644 --- a/extension/js/common/api/email-provider/gmail/google-auth.ts +++ b/extension/js/common/api/email-provider/gmail/google-auth.ts @@ -97,7 +97,7 @@ export class GoogleAuth { throw new GoogleAuthErr(`Could not refresh google auth token - did not become valid (access:${refreshTokenRes.access_token},expires_in:${refreshTokenRes.expires_in},now:${Date.now()})`); }; - public static apiGoogleCallRetryAuthErrorOneTime = async (acctEmail: string, request: JQuery.AjaxSettings): Promise => { + public static apiGoogleCallRetryAuthErrorOneTime = async (acctEmail: string, request: JQuery.AjaxSettings): Promise => { try { return await Api.ajax(request, Catch.stackTrace()); } catch (firstAttemptErr) { @@ -173,7 +173,7 @@ export class GoogleAuth { /** * Happens on enterprise builds */ - public static isFesUnreachableErr = (e: any, email: string): boolean => { + public static isFesUnreachableErr = (e: unknown, email: string): boolean => { const domain = Str.getDomainFromEmailAddress(email); const errString = String(e); if (errString.includes(`-1 when GET-ing https://fes.${domain}/api/ `)) { // the space is important to match the full url @@ -301,7 +301,7 @@ export class GoogleAuth { method: 'POST', crossDomain: true, async: true, - }, Catch.stackTrace()) as any as GoogleAuthTokensResponse; + }, Catch.stackTrace()) as unknown as GoogleAuthTokensResponse; }; private static googleAuthRefreshToken = async (refreshToken: string) => { @@ -310,7 +310,7 @@ export class GoogleAuth { method: 'POST', crossDomain: true, async: true, - }, Catch.stackTrace()) as any as GoogleAuthTokensResponse; + }, Catch.stackTrace()) as unknown as GoogleAuthTokensResponse; }; // todo - would be better to use a TS type guard instead of the type cast when checking OpenId diff --git a/extension/js/common/api/shared/api-error.ts b/extension/js/common/api/shared/api-error.ts index 32e033a1368..0ff272d9c5e 100644 --- a/extension/js/common/api/shared/api-error.ts +++ b/extension/js/common/api/shared/api-error.ts @@ -144,7 +144,7 @@ export class AjaxErr extends ApiCallErr { // no static props, else will get seri } export class ApiErr { - public static eli5 = (e: any): string => { // "explain like I'm five" + public static eli5 = (e: unknown): string => { // "explain like I'm five" if (ApiErr.isMailOrAcctDisabledOrPolicy(e)) { return 'Email account is disabled, or access has been blocked by admin policy. Contact your email administrator.'; } else if (ApiErr.isAuthErr(e)) { @@ -174,7 +174,7 @@ export class ApiErr { } }; - public static isStandardErr = (e: any, internalType: 'auth' | 'subscription'): boolean => { + public static isStandardErr = (e: unknown, internalType: 'auth' | 'subscription'): boolean => { if (!e || !(typeof e === 'object')) { return false; } @@ -190,7 +190,7 @@ export class ApiErr { return false; }; - public static isAuthErr = (e: any): boolean => { + public static isAuthErr = (e: unknown): boolean => { if (e instanceof AuthErr || e instanceof GoogleAuthErr) { return true; } @@ -214,7 +214,7 @@ export class ApiErr { return false; }; - public static isMailOrAcctDisabledOrPolicy = (e: any): boolean => { + public static isMailOrAcctDisabledOrPolicy = (e: unknown): boolean => { if (e instanceof AjaxErr && ApiErr.isBadReq(e) && typeof e.responseText === 'string') { if (e.responseText.indexOf('Mail service not enabled') !== -1 || e.responseText.indexOf('Account has been deleted') !== -1) { return true; @@ -226,7 +226,7 @@ export class ApiErr { return false; }; - public static isBlockedByProxy = (e: any): boolean => { + public static isBlockedByProxy = (e: unknown): boolean => { if (!(e instanceof AjaxErr)) { return false; } @@ -241,7 +241,7 @@ export class ApiErr { return false; }; - public static isNetErr = (e: any): e is Error => { + public static isNetErr = (e: unknown): e is Error => { if (e instanceof TypeError && (e.message === 'Failed to fetch' || e.message === 'NetworkError when attempting to fetch resource.')) { return true; // openpgp.js uses fetch()... which produces these errors } @@ -257,38 +257,38 @@ export class ApiErr { return false; }; - public static isDecryptErr = (e: any): e is DecryptionError => { + public static isDecryptErr = (e: unknown): e is DecryptionError => { if (e instanceof DecryptionError) { return true; } return false; }; - public static isSignificant = (e: any): boolean => { + public static isSignificant = (e: unknown): boolean => { return !ApiErr.isNetErr(e) && !ApiErr.isServerErr(e) && !ApiErr.isNotFound(e) && !ApiErr.isMailOrAcctDisabledOrPolicy(e) && !ApiErr.isAuthErr(e) && !ApiErr.isBlockedByProxy(e); }; - public static isBadReq = (e: any): e is AjaxErr => { + public static isBadReq = (e: unknown): e is AjaxErr => { return e instanceof AjaxErr && e.status === 400; }; - public static isInsufficientPermission = (e: any): e is AjaxErr => { + public static isInsufficientPermission = (e: unknown): e is AjaxErr => { return e instanceof AjaxErr && e.status === 403 && e.responseText.indexOf('insufficientPermissions') !== -1; }; - public static isNotFound = (e: any): e is AjaxErr => { + public static isNotFound = (e: unknown): e is AjaxErr => { return e instanceof AjaxErr && e.status === 404; }; - public static isReqTooLarge = (e: any): boolean => { + public static isReqTooLarge = (e: unknown): boolean => { return e instanceof AjaxErr && e.status === 413; }; - public static isServerErr = (e: any): boolean => { + public static isServerErr = (e: unknown): boolean => { return e instanceof AjaxErr && e.status >= 500; }; - public static detailsAsHtmlWithNewlines = (e: any): string => { + public static detailsAsHtmlWithNewlines = (e: unknown): string => { let details = 'Below are technical details about the error. This may be useful for debugging.\n\n'; details += `Error string: ${Xss.escape(String(e))}\n\n`; details += `Error stack: ${e instanceof Error ? Xss.escape((e.stack || '(empty)')) : '(no error stack)'}\n\n`; @@ -298,11 +298,11 @@ export class ApiErr { return details; }; - public static isInPrivateMode = (e: any) => { + public static isInPrivateMode = (e: unknown) => { return e instanceof Error && e.message.startsWith('BrowserMsg() (no status text): -1 when GET-ing blob:moz-extension://'); }; - public static reportIfSignificant = (e: any) => { + public static reportIfSignificant = (e: unknown) => { if (ApiErr.isSignificant(e)) { Catch.reportErr(e); } diff --git a/extension/js/common/assert.ts b/extension/js/common/assert.ts index 0e036a60857..921f1ae6a79 100644 --- a/extension/js/common/assert.ts +++ b/extension/js/common/assert.ts @@ -31,7 +31,7 @@ export class Assert { throw new Error(`urlParamRequire.optionalString: type of ${name} unexpectedly ${typeof r}`); }, oneof: (values: UrlParams, name: string, allowed: T[]): T => { - return Assert.abortAndRenderErrOnUrlParamValMismatch(values, name, allowed as any as UrlParam[]) as any as T; // todo - there should be a better way + return Assert.abortAndRenderErrOnUrlParamValMismatch(values, name, allowed as unknown as UrlParam[]) as unknown as T; // todo - there should be a better way }, }; diff --git a/extension/js/common/browser/browser-extension.ts b/extension/js/common/browser/browser-extension.ts index 70be0d6cc6e..e3a76be3e49 100644 --- a/extension/js/common/browser/browser-extension.ts +++ b/extension/js/common/browser/browser-extension.ts @@ -8,7 +8,7 @@ import { FlatTypes } from '../platform/store/abstract-store.js'; export class BrowserExtension { // todo - move extension-specific common.js code here - public static prepareBugReport = (name: string, details?: Dict, error?: Error | any): string => { + public static prepareBugReport = (name: string, details?: Dict, error?: Error | unknown): string => { const bugReport: Dict = { name, stack: Catch.stackTrace() }; try { bugReport.error = JSON.stringify(error, undefined, 2); diff --git a/extension/js/common/browser/browser-msg.ts b/extension/js/common/browser/browser-msg.ts index 8664500a7c8..2de6a82760f 100644 --- a/extension/js/common/browser/browser-msg.ts +++ b/extension/js/common/browser/browser-msg.ts @@ -24,8 +24,8 @@ export type GoogleAuthWindowResult$result = 'Success' | 'Denied' | 'Error' | 'Cl export namespace Bm { export type Dest = string; export type Sender = chrome.runtime.MessageSender | 'background'; - export type Response = any; - export type RawResponse = { result: any, objUrls: { [name: string]: string }, exception?: Bm.ErrAsJson }; + export type Response = unknown; + export type RawResponse = { result: unknown, objUrls: { [name: string]: string }, exception?: Bm.ErrAsJson }; export type Raw = { name: string; data: { bm: AnyRequest | {}, objUrls: Dict }; to: Dest | null; uid: string; stack: string }; export type SetCss = { css: Dict, traverseUp?: number, selector: string; }; @@ -47,7 +47,7 @@ export namespace Bm { export type OpenGoogleAuthDialog = { acctEmail?: string, scopes?: string[] }; export type OpenPage = { page: string, addUrlText?: string | UrlParams }; export type PassphraseEntry = { entered: boolean, initiatorFrameId?: string }; - export type Db = { f: string, args: any[] }; + export type Db = { f: string, args: unknown[] }; export type InMemoryStoreSet = { acctEmail: string, key: string, value: string | undefined, expiration: number | undefined }; export type InMemoryStoreGet = { acctEmail: string, key: string }; export type StoreGlobalGet = { keys: GlobalIndex[]; }; @@ -461,7 +461,7 @@ export class BrowserMsg { return requestOrResponse; }; - private static errToJson = (e: any): Bm.ErrAsJson => { + private static errToJson = (e: unknown): Bm.ErrAsJson => { if (e instanceof AjaxErr) { const { message, stack, status, url, responseText, statusText, resMsg, resDetails } = e; return { stack, message, errorConstructor: 'AjaxErr', ajaxErrorDetails: { status, url, responseText, statusText, resMsg, resDetails } }; diff --git a/extension/js/common/browser/browser-window.ts b/extension/js/common/browser/browser-window.ts index 20e2da435a0..1b9ee3a4d94 100644 --- a/extension/js/common/browser/browser-window.ts +++ b/extension/js/common/browser/browser-window.ts @@ -6,7 +6,7 @@ type AnyThirdPartyLibrary = any; export type AddrParserResult = { name?: string, address?: string }; export interface BrowserWindow extends Window { - onunhandledrejection: (e: any) => void; + onunhandledrejection: (e: unknown) => void; 'emailjs-mime-codec': AnyThirdPartyLibrary; 'emailjs-mime-parser': AnyThirdPartyLibrary; 'emailjs-mime-builder': AnyThirdPartyLibrary; diff --git a/extension/js/common/browser/chrome.ts b/extension/js/common/browser/chrome.ts index 4e3448f472b..e31cdc4ff69 100644 --- a/extension/js/common/browser/chrome.ts +++ b/extension/js/common/browser/chrome.ts @@ -23,7 +23,7 @@ const handleFatalErr = (reason: 'storage_undefined', error: Error) => { } catch (e) { if (e && e instanceof Error && e.message === 'Extension context invalidated.') { console.info(`FlowCrypt cannot handle fatal error because: Extension context invalidated. Destroying.`, error); - (window as any as ContentScriptWindow).destroy(); + (window as unknown as ContentScriptWindow).destroy(); } else { throw e; } @@ -62,7 +62,7 @@ export const storageLocalGet = async (keys: string[]): Promise> => }); }; -export const storageLocalGetAll = async (): Promise<{ [key: string]: any }> => { +export const storageLocalGetAll = async (): Promise<{ [key: string]: unknown }> => { return await new Promise((resolve) => { if (typeof chrome.storage === 'undefined') { handleFatalErr('storage_undefined', new Error('storage is undefined')); @@ -72,7 +72,7 @@ export const storageLocalGetAll = async (): Promise<{ [key: string]: any }> => { }); }; -export const storageLocalSet = async (values: Dict): Promise => { +export const storageLocalSet = async (values: Dict): Promise => { return await new Promise((resolve) => { if (typeof chrome.storage === 'undefined') { handleFatalErr('storage_undefined', new Error('storage is undefined')); diff --git a/extension/js/common/browser/ui.ts b/extension/js/common/browser/ui.ts index 3bbb203bdcf..6e23dea5eac 100644 --- a/extension/js/common/browser/ui.ts +++ b/extension/js/common/browser/ui.ts @@ -13,7 +13,7 @@ type ProvidedEventHandler = (e: HTMLElement, event: JQuery.Event JQuery; now: (name: string) => JQuery; sel: (name: string) => string; }; export type PreventableEventName = 'double' | 'parallel' | 'spree' | 'slowspree' | 'veryslowspree'; -export type BrowserEventErrHandler = { auth?: () => Promise, authPopup?: () => Promise, network?: () => Promise, other?: (e: any) => Promise }; +export type BrowserEventErrHandler = { auth?: () => Promise, authPopup?: () => Promise, network?: () => Promise, other?: (e: unknown) => Promise }; export class Ui { @@ -53,7 +53,7 @@ export class Ui { } }; }, - _dispatchErr: (e: any, errHandlers?: BrowserEventErrHandler) => { + _dispatchErr: (e: unknown, errHandlers?: BrowserEventErrHandler) => { if (ApiErr.isNetErr(e) && errHandlers && errHandlers.network) { errHandlers.network().catch(Catch.reportErr); } else if (ApiErr.isAuthErr(e) && errHandlers && errHandlers.auth) { diff --git a/extension/js/common/core/common.ts b/extension/js/common/core/common.ts index a3f0e68f5f7..98ac1fa6b14 100644 --- a/extension/js/common/core/common.ts +++ b/extension/js/common/core/common.ts @@ -56,7 +56,7 @@ export class Str { return list.map(x => Str.formatEmailWithOptionalNameEx(x, forceBrackets)).join(', '); }; - public static prettyPrint = (obj: any) => { + public static prettyPrint = (obj: unknown) => { return (typeof obj === 'object') ? JSON.stringify(obj, undefined, 2).replace(/ /g, ' ').replace(/\n/g, '
') : String(obj); }; @@ -136,13 +136,13 @@ export class Str { .replace(/\n/g, ''); // strip newlines, already have
}; - public static htmlAttrEncode = (values: Dict): string => { + public static htmlAttrEncode = (values: Dict): string => { return Str.base64urlUtfEncode(JSON.stringify(values)); }; - public static htmlAttrDecode = (encoded: string): any => { + public static htmlAttrDecode = (encoded: string): unknown => { try { - return JSON.parse(Str.base64urlUtfDecode(encoded)); // tslint:disable-line:no-unsafe-any + return JSON.parse(Str.base64urlUtfDecode(encoded)); } catch (e) { return undefined; } @@ -238,7 +238,7 @@ export class Value { } return result; }, - contains: (arr: T[] | string, value: T): boolean => Boolean(arr && typeof arr.indexOf === 'function' && (arr as any[]).indexOf(value) !== -1), + contains: (arr: T[] | string, value: T): boolean => Boolean(arr && typeof arr.indexOf === 'function' && (arr as unknown[]).indexOf(value) !== -1), intersection: (array1: T[], array2: T[]): T[] => array1.filter(value => array2.includes(value)), hasIntersection: (array1: T[], array2: T[]): boolean => array1.some(value => array2.includes(value)), sum: (arr: number[]) => arr.reduce((a, b) => a + b, 0), diff --git a/extension/js/common/core/const.ts b/extension/js/common/core/const.ts index 28d83f6a5a2..62cf3eed2ab 100644 --- a/extension/js/common/core/const.ts +++ b/extension/js/common/core/const.ts @@ -3,7 +3,7 @@ 'use strict'; export const VERSION = '[BUILD_REPLACEABLE_VERSION]'; -export const FLAVOR: 'consumer' | 'enterprise' = '[BUILD_REPLACEABLE_FLAVOR]' as any; +export const FLAVOR: 'consumer' | 'enterprise' = '[BUILD_REPLACEABLE_FLAVOR]' as unknown as 'consumer' | 'enterprise'; export const OAUTH_GOOGLE_API_HOST = '[BUILD_REPLACEABLE_OAUTH_GOOGLE_API_HOST]'; export const GMAIL_GOOGLE_API_HOST = '[BUILD_REPLACEABLE_GMAIL_GOOGLE_API_HOST]'; export const PEOPLE_GOOGLE_API_HOST = '[BUILD_REPLACEABLE_PEOPLE_GOOGLE_API_HOST]'; diff --git a/extension/js/common/core/crypto/pgp/msg-util.ts b/extension/js/common/core/crypto/pgp/msg-util.ts index ba51745cdf6..a4b00515eda 100644 --- a/extension/js/common/core/crypto/pgp/msg-util.ts +++ b/extension/js/common/core/crypto/pgp/msg-util.ts @@ -342,7 +342,7 @@ export class MsgUtil { return msgKeyIds.filter(kid => OpenPGPKey.isPacketDecrypted(prv, kid)).length === msgKeyIds.length; // test if all needed key packets are decrypted }; - private static cryptoMsgDecryptCategorizeErr = (decryptErr: any, msgPwd?: string): DecryptError$error => { + private static cryptoMsgDecryptCategorizeErr = (decryptErr: unknown, msgPwd?: string): DecryptError$error => { const e = String(decryptErr).replace('Error: ', '').replace('Error decrypting message: ', ''); const keyMismatchErrStrings = ['Cannot read property \'isDecrypted\' of null', 'privateKeyPacket is null', 'TypeprivateKeyPacket is null', 'Session key decryption failed.', 'Invalid session key for decryption.']; diff --git a/extension/js/common/core/crypto/pgp/openpgp-key.ts b/extension/js/common/core/crypto/pgp/openpgp-key.ts index 08e2d4396c0..99cf1aa3cb1 100644 --- a/extension/js/common/core/crypto/pgp/openpgp-key.ts +++ b/extension/js/common/core/crypto/pgp/openpgp-key.ts @@ -521,7 +521,7 @@ export class OpenPGPKey { private static getLatestValidSignature = async (signatures: OpenPGP.packet.Signature[], primaryKey: OpenPGP.packet.PublicKey | OpenPGP.packet.SecretKey, signatureType: OpenPGP.enums.signature, - dataToVerify: any, + dataToVerify: unknown, date = new Date()): Promise => { let signature: OpenPGP.packet.Signature | undefined; diff --git a/extension/js/common/core/msg-block-parser.ts b/extension/js/common/core/msg-block-parser.ts index 5d04ceae5ea..fdb81ca4607 100644 --- a/extension/js/common/core/msg-block-parser.ts +++ b/extension/js/common/core/msg-block-parser.ts @@ -13,7 +13,7 @@ import { Str } from './common.js'; import { FcAttachmentLinkData } from './attachment.js'; import { KeyUtil } from './crypto/key.js'; -type SanitizedBlocks = { blocks: MsgBlock[], subject: string | undefined, isRichText: boolean, webReplyToken: any | undefined }; +type SanitizedBlocks = { blocks: MsgBlock[], subject: string | undefined, isRichText: boolean, webReplyToken: unknown | undefined }; export class MsgBlockParser { @@ -43,7 +43,7 @@ export class MsgBlockParser { public static fmtDecryptedAsSanitizedHtmlBlocks = async (decryptedContent: Uint8Array, imgHandling: SanitizeImgHandling = 'IMG-TO-LINK'): Promise => { const blocks: MsgBlock[] = []; let isRichText = false; - let webReplyToken: any | undefined; + let webReplyToken: unknown | undefined; if (!Mime.resemblesMsg(decryptedContent)) { let plain = Buf.fromUint8(decryptedContent).toUtfStr(); plain = MsgBlockParser.extractFcAttachments(plain, blocks); diff --git a/extension/js/common/platform/catch.ts b/extension/js/common/platform/catch.ts index 0660f0a2a7d..d6ab5838b70 100644 --- a/extension/js/common/platform/catch.ts +++ b/extension/js/common/platform/catch.ts @@ -40,13 +40,13 @@ export class Catch { 'ResizeObserver loop limit exceeded', ]; - public static rewrapErr = (e: any, message: string): Error => { + public static rewrapErr = (e: unknown, message: string): Error => { const newErr = new Error(`${message}::${e instanceof Error ? `${e.name}: ${e.message}` : String(e)}`); newErr.stack += `\n\n${Catch.stringify(e)}`; return newErr; }; - public static stringify = (e: any): string => { + public static stringify = (e: unknown): string => { if (e instanceof Error) { return `[typeof:Error:${e.name}] ${e.message}\n\n${e.stack}`; } @@ -67,7 +67,7 @@ export class Catch { /** * @returns boolean - whether error was reported remotely or not */ - public static onErrorInternalHandler = (errMsg: string | undefined, url: string, line: number, col: number, originalErr: any, isManuallyCalled: boolean): boolean => { + public static onErrorInternalHandler = (errMsg: string | undefined, url: string, line: number, col: number, originalErr: unknown, isManuallyCalled: boolean): boolean => { const exception = Catch.formExceptionFromThrown(originalErr, errMsg, url, line, col, isManuallyCalled); if ((Catch.IGNORE_ERR_MSG.indexOf(exception.message) !== -1) || (errMsg && Catch.IGNORE_ERR_MSG.indexOf(errMsg) !== -1)) { return false; @@ -103,7 +103,7 @@ export class Catch { /** * @returns boolean - whether error was reported remotely or not */ - public static reportErr = (e: any): boolean => { + public static reportErr = (e: unknown): boolean => { const { line, col } = Catch.getErrorLineAndCol(e); return Catch.onErrorInternalHandler(e instanceof Error ? e.message : String(e), window.location.href, line, col, e, true); }; @@ -111,11 +111,11 @@ export class Catch { /** * @returns boolean - whether error was reported remotely or not */ - public static report = (name: string, details?: any): boolean => { + public static report = (name: string, details?: unknown): boolean => { return Catch.reportErr(Catch.nameAndDetailsAsException(name, details)); }; - public static isPromise = (v: any): v is Promise => { + public static isPromise = (v: any): v is Promise => { return v && typeof v === 'object' // tslint:disable-line:no-unsafe-any && typeof (v as Promise).then === 'function' // tslint:disable-line:no-unbound-method - only testing if exists && typeof (v as Promise).catch === 'function'; // tslint:disable-line:no-unbound-method - only testing if exists @@ -212,7 +212,7 @@ export class Catch { return url; }; - public static onUnhandledRejectionInternalHandler = (e: any) => { + public static onUnhandledRejectionInternalHandler = (e: unknown) => { if (Catch.isPromiseRejectionEvent(e)) { Catch.reportErr(e.reason); } else { @@ -254,7 +254,7 @@ export class Catch { } }; - private static formatExceptionForReport = (thrown: any, line?: number, col?: number): ErrorReport => { + private static formatExceptionForReport = (thrown: unknown, line?: number, col?: number): ErrorReport => { if (!line || !col) { const { line: parsedLine, col: parsedCol } = Catch.getErrorLineAndCol(thrown); line = parsedLine; @@ -306,7 +306,7 @@ export class Catch { } }; - private static formExceptionFromThrown = (thrown: any, errMsg?: string, url?: string, line?: number, col?: number, isManuallyCalled?: boolean): Error => { + private static formExceptionFromThrown = (thrown: unknown, errMsg?: string, url?: string, line?: number, col?: number, isManuallyCalled?: boolean): Error => { let exception: Error; if (typeof thrown !== 'object') { exception = new Error(`THROWN_NON_OBJECT[${typeof thrown}]: ${String(thrown)}`); @@ -341,7 +341,7 @@ export class Catch { return `\n\n### ${name} ###\n# ${text.split('\n').join('\n# ')}\n######################\n`; }; - private static nameAndDetailsAsException = (name: string, details: any): Error => { + private static nameAndDetailsAsException = (name: string, details: unknown): Error => { try { throw new Error(name); } catch (e) { @@ -350,7 +350,7 @@ export class Catch { } }; - private static isPromiseRejectionEvent = (ev: any): ev is PromiseRejectionEvent => { + private static isPromiseRejectionEvent = (ev: unknown): ev is PromiseRejectionEvent => { if (ev && typeof ev === 'object') { const eHasReason = (ev as {}).hasOwnProperty('reason') && typeof (ev as PromiseRejectionEvent).reason === 'object'; const eHasPromise = (ev as {}).hasOwnProperty('promise') && Catch.isPromise((ev as PromiseRejectionEvent).promise); diff --git a/extension/js/common/platform/debug.ts b/extension/js/common/platform/debug.ts index f9871f463ba..7d64c638744 100644 --- a/extension/js/common/platform/debug.ts +++ b/extension/js/common/platform/debug.ts @@ -26,9 +26,9 @@ export class Debug { /** * Extracts all the stored messages from the `debug` database, also deleting them */ - public static readDatabase = async (): Promise => { + public static readDatabase = async (): Promise => { const db = await Debug.openDatabase(); - const records: any[] = []; + const records: unknown[] = []; const tx = db.transaction(['messages'], 'readwrite'); await new Promise((resolve, reject) => { tx.oncomplete = () => resolve(undefined); @@ -46,7 +46,7 @@ export class Debug { /** * Add an arbitrary message to `debug` database */ - public static addMessage = async (message: any): Promise => { + public static addMessage = async (message: unknown): Promise => { const db = await Debug.openDatabase(); const tx = db.transaction(['messages'], 'readwrite'); await new Promise((resolve, reject) => { diff --git a/extension/js/common/platform/store/abstract-store.ts b/extension/js/common/platform/store/abstract-store.ts index 79d7c5c05f5..d9937757dd2 100644 --- a/extension/js/common/platform/store/abstract-store.ts +++ b/extension/js/common/platform/store/abstract-store.ts @@ -31,7 +31,7 @@ export abstract class AbstractStore { return `cryptup_${emailKeyIndex(scope, key)}`; }; - public static errCategorize = (err: any): Error => { + public static errCategorize = (err: unknown): Error => { let message: string; if (err instanceof Error) { message = err.message; @@ -60,11 +60,11 @@ export abstract class AbstractStore { } }; - public static setReqOnError = (req: IDBRequest | IDBTransaction, reject: (reason?: any) => void) => { + public static setReqOnError = (req: IDBRequest | IDBTransaction, reject: (reason?: unknown) => void) => { req.onerror = () => reject(AbstractStore.errCategorize(req.error || new Error('Unknown db error'))); }; - public static setTxHandlers = (tx: IDBTransaction, resolve: (value: unknown) => void, reject: (reason?: any) => void) => { + public static setTxHandlers = (tx: IDBTransaction, resolve: (value: unknown) => void, reject: (reason?: unknown) => void) => { tx.oncomplete = () => resolve(undefined); AbstractStore.setReqOnError(tx, reject); }; diff --git a/extension/js/common/platform/store/contact-store.ts b/extension/js/common/platform/store/contact-store.ts index 3e396481c55..b12e6f2cf0b 100644 --- a/extension/js/common/platform/store/contact-store.ts +++ b/extension/js/common/platform/store/contact-store.ts @@ -640,7 +640,7 @@ export class ContactStore extends AbstractStore { } }; - public static setReqPipe(req: IDBRequest, pipe: (value?: T) => void, reject?: ((reason?: any) => void) | undefined) { + public static setReqPipe(req: IDBRequest, pipe: (value?: T) => void, reject?: ((reason?: unknown) => void) | undefined) { req.onsuccess = () => { try { pipe(req.result as T); diff --git a/extension/js/common/settings.ts b/extension/js/common/settings.ts index 5c29348fbf4..d2745d8152a 100644 --- a/extension/js/common/settings.ts +++ b/extension/js/common/settings.ts @@ -257,7 +257,7 @@ export class Settings { /** * todo - could probably replace most usages of this method with retryPromptUntilSuccessful which is more intuitive */ - public static promptToRetry = async (lastErr: any, userMsg: string, retryCb: () => Promise, contactSentence: string): Promise => { + public static promptToRetry = async (lastErr: unknown, userMsg: string, retryCb: () => Promise, contactSentence: string): Promise => { let userErrMsg = `${userMsg} ${ApiErr.eli5(lastErr)}`; if (lastErr instanceof AjaxErr && (lastErr.status === 400 || lastErr.status === 405)) { // this will make reason for err 400 obvious to user - eg on EKM 405 error diff --git a/extension/js/common/view.ts b/extension/js/common/view.ts index 98daa01fc91..de8a8b56a12 100644 --- a/extension/js/common/view.ts +++ b/extension/js/common/view.ts @@ -26,7 +26,7 @@ export abstract class View { $('body').attr('data-test-view-state', 'loaded'); }; - private static reportAndRenderErr = (e: any) => { + private static reportAndRenderErr = (e: unknown) => { ApiErr.reportIfSignificant(e); Xss.sanitizeRender('body', `
diff --git a/extension/js/content_scripts/webmail/webmail.ts b/extension/js/content_scripts/webmail/webmail.ts index 2c2e0ebfa78..187ad913c73 100644 --- a/extension/js/content_scripts/webmail/webmail.ts +++ b/extension/js/content_scripts/webmail/webmail.ts @@ -54,7 +54,7 @@ Catch.try(async () => { '', ].join('')); // executed synchronously - we can read the vars below try { - const extracted = (JSON.parse($('body > div#FC_VAR_PASS').text()) as any[]).map(String); + const extracted = (JSON.parse($('body > div#FC_VAR_PASS').text()) as unknown[]).map(String); if (extracted[0] === 'true') { insights.newDataLayer = true; } else if (extracted[0] === 'false') { diff --git a/test/source/browser/browser-pool.ts b/test/source/browser/browser-pool.ts index 10917a35608..99d0afadd86 100644 --- a/test/source/browser/browser-pool.ts +++ b/test/source/browser/browser-pool.ts @@ -159,7 +159,7 @@ export class BrowserPool { } }; - private processTestError = (err: any, t: AvaContext, attemptHtmls: string[], flag?: 'FAILING') => { + private processTestError = (err: unknown, t: AvaContext, attemptHtmls: string[], flag?: 'FAILING') => { t.retry = undefined; if (t.attemptNumber! < t.totalAttempts!) { t.log(`${t.attemptText} Retrying: ${String(err)}`); @@ -172,7 +172,7 @@ export class BrowserPool { } }; - private testFailSingleAttemptDebugHtml = async (t: AvaContext, browser: BrowserHandle, err: any): Promise => { + private testFailSingleAttemptDebugHtml = async (t: AvaContext, browser: BrowserHandle, err: unknown): Promise => { return `
diff --git a/test/source/browser/controllable.ts b/test/source/browser/controllable.ts index 0da596da8d1..5b0e382e9da 100644 --- a/test/source/browser/controllable.ts +++ b/test/source/browser/controllable.ts @@ -598,7 +598,7 @@ export class ControllablePage extends ControllableBase { this.preventclose = true; t.log(`${t.attemptText} Dismissing unexpected alert ${alert.message()}`); try { - alert.dismiss().catch((e: any) => t.log(`${t.attemptText} Err1 dismissing alert ${String(e)}`)); + alert.dismiss().catch((e: unknown) => t.log(`${t.attemptText} Err1 dismissing alert ${String(e)}`)); } catch (e) { t.log(`${t.attemptText} Err2 dismissing alert ${String(e)}`); } diff --git a/test/source/mock/lib/api.ts b/test/source/mock/lib/api.ts index 17ae0c7ca63..ea4e29d53af 100644 --- a/test/source/mock/lib/api.ts +++ b/test/source/mock/lib/api.ts @@ -102,7 +102,7 @@ export class Api { }; public close = (): Promise => { - return new Promise((resolve, reject) => this.server.close((err: any) => err ? reject(err) : resolve())); + return new Promise((resolve, reject) => this.server.close((err: unknown) => err ? reject(err) : resolve())); }; protected log = (ms: number, req: http.IncomingMessage, res: http.ServerResponse, errRes?: Buffer) => { // eslint-disable-line @typescript-eslint/no-unused-vars @@ -150,7 +150,7 @@ export class Api { } }; - protected fmtErr = (e: any): Buffer => { + protected fmtErr = (e: unknown): Buffer => { if (String(e).includes('invalid_grant')) { return Buffer.from(JSON.stringify({ "error": "invalid_grant", "error_description": "Bad Request" })); } diff --git a/test/source/platform/catch.ts b/test/source/platform/catch.ts index 75a6b82bf55..55ae6fd024c 100644 --- a/test/source/platform/catch.ts +++ b/test/source/platform/catch.ts @@ -12,11 +12,11 @@ export class Catch { public static RUNTIME_VERSION = VERSION; public static RUNTIME_ENVIRONMENT = 'undetermined'; - public static handleErr = (e: any) => { // eslint-disable-line @typescript-eslint/no-unused-vars + public static handleErr = (e: unknown) => { // eslint-disable-line @typescript-eslint/no-unused-vars // core errs that are not rethrown are not very interesting }; - public static reportErr = (err: any) => { // eslint-disable-line @typescript-eslint/no-unused-vars + public static reportErr = (err: unknown) => { // eslint-disable-line @typescript-eslint/no-unused-vars // core reports are not very interesting }; diff --git a/test/source/platform/debug.ts b/test/source/platform/debug.ts index 2290e9abc8e..9530446ea54 100644 --- a/test/source/platform/debug.ts +++ b/test/source/platform/debug.ts @@ -3,15 +3,15 @@ 'use strict'; export class Debug { - private static DATA: any[] = []; + private static DATA: unknown[] = []; - public static readDatabase = async (): Promise => { + public static readDatabase = async (): Promise => { const old = Debug.DATA; Debug.DATA = []; return old; }; - public static addMessage = async (message: any): Promise => { + public static addMessage = async (message: unknown): Promise => { Debug.DATA.push(message); }; } diff --git a/test/source/platform/require.ts b/test/source/platform/require.ts index 707430803ae..f69c333e37b 100644 --- a/test/source/platform/require.ts +++ b/test/source/platform/require.ts @@ -5,7 +5,7 @@ 'use strict'; export const requireOpenpgp = (): typeof OpenPGP => { - return require('openpgp') as any as typeof OpenPGP; + return require('openpgp') as unknown as typeof OpenPGP; }; export const requireMimeParser = (): any => { diff --git a/test/source/test.ts b/test/source/test.ts index 6c07a2f452e..c9683e7a090 100644 --- a/test/source/test.ts +++ b/test/source/test.ts @@ -37,7 +37,7 @@ const consts = { // higher concurrency can cause 429 google errs when composing TIMEOUT_OVERALL: minutes(19), ATTEMPTS: testGroup === 'STANDARD-GROUP' ? oneIfNotPooled(3) : process.argv.includes('--retry=false') ? 1 : 3, POOL_SIZE: oneIfNotPooled(isMock ? 20 : 3), - PROMISE_TIMEOUT_OVERALL: undefined as any as Promise, // will be set right below + PROMISE_TIMEOUT_OVERALL: undefined as unknown as Promise, // will be set right below IS_LOCAL_DEBUG: process.argv.includes('--debug') ? true : false, // run locally by developer, not in ci }; console.info('consts: ', JSON.stringify(consts), '\n'); diff --git a/test/source/tests/tooling/api.ts b/test/source/tests/tooling/api.ts index 877c9c77648..6399a338ba2 100644 --- a/test/source/tests/tooling/api.ts +++ b/test/source/tests/tooling/api.ts @@ -18,7 +18,7 @@ export class FlowCryptApi { console.info('hookCiDebugEmail-response', r.body, r.statusCode); }; - private static call = async (url: string, values: { [k: string]: any }) => { + private static call = async (url: string, values: { [k: string]: unknown }) => { return await request.post({ url, json: values, headers: { 'api-version': 3 } }); };