diff --git a/eslint.config.mjs b/eslint.config.mjs index 9081ccfe2d..62b0fc99bf 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -502,11 +502,30 @@ export default [ // certain TypeScript compilation errors after fixes '@typescript-eslint/no-unnecessary-type-assertion': 'off', + '@typescript-eslint/no-inferrable-types': 'error', + '@typescript-eslint/consistent-generic-constructors': [ 'error', 'constructor', ], + // This is more performant + // And should provide better stack trace when debugging + // see https://v8.dev/blog/fast-async. + '@typescript-eslint/return-await': ['error', 'always'], + + '@typescript-eslint/ban-ts-comment': [ + 'error', + { + // Change after we add some placeholder for old errors + minimumDescriptionLength: 0, + 'ts-check': false, + 'ts-expect-error': 'allow-with-description', + 'ts-ignore': true, + 'ts-nocheck': true, + }, + ], + 'rulesdir/no-underscored-properties': 'error', 'rulesdir/inline-type-imports': 'error', diff --git a/extensions/cxx_debugging/src/CustomFormatters.ts b/extensions/cxx_debugging/src/CustomFormatters.ts index d1d3285f7f..2cb5a87c6d 100644 --- a/extensions/cxx_debugging/src/CustomFormatters.ts +++ b/extensions/cxx_debugging/src/CustomFormatters.ts @@ -361,7 +361,8 @@ export class CXXValue implements Value, LazyObject { try { const formattedValue = await formatter.format(this.wasm, value); - return lazyObjectFromAny(formattedValue, this.objectStore, this.type, this.displayValue, this.memoryAddress) + return await lazyObjectFromAny( + formattedValue, this.objectStore, this.type, this.displayValue, this.memoryAddress) .asRemoteObject(); } catch { // Fallthrough @@ -505,7 +506,7 @@ function lazyObjectFromAny( } export class LazyObjectStore { - private nextObjectId: number = 0; + private nextObjectId = 0; private objects = new Map(); store(lazyObject: LazyObject): string { diff --git a/extensions/cxx_debugging/src/DWARFSymbols.ts b/extensions/cxx_debugging/src/DWARFSymbols.ts index 46d3f5d403..86070a14d3 100644 --- a/extensions/cxx_debugging/src/DWARFSymbols.ts +++ b/extensions/cxx_debugging/src/DWARFSymbols.ts @@ -201,7 +201,7 @@ export class DWARFLanguageExtensionPlugin implements Chrome.DevTools.LanguageExt // Ensure directory exists if (parentDirectory.length > 1) { // TypeScript doesn't know about createPath - // @ts-ignore + // @ts-expect-error backend.FS.createPath('/', parentDirectory.substring(1), true, true); } @@ -216,7 +216,7 @@ export class DWARFLanguageExtensionPlugin implements Chrome.DevTools.LanguageExt void this.hostInterface.reportResourceLoad(dwoURL, {success: false, errorMessage: (e as Error).message}); // Rethrow any error fetching the content as errno 44 (EEXIST) // TypeScript doesn't know about the ErrnoError constructor - // @ts-ignore + // @ts-expect-error throw new backend.FS.ErrnoError(44); } }; @@ -557,7 +557,7 @@ export class DWARFLanguageExtensionPlugin implements Chrome.DevTools.LanguageExt description: '', }; } - return cxxObject.asRemoteObject(); + return await cxxObject.asRemoteObject(); } async getProperties(objectId: Chrome.DevTools.RemoteObjectId): Promise { @@ -582,7 +582,7 @@ export class DWARFLanguageExtensionPlugin implements Chrome.DevTools.LanguageExt export async function createPlugin( hostInterface: HostInterface, resourceLoader: ResourceLoader, moduleConfigurations: ModuleConfigurations = DEFAULT_MODULE_CONFIGURATIONS, - logPluginApiCalls: boolean = false): Promise { + logPluginApiCalls = false): Promise { const plugin = new DWARFLanguageExtensionPlugin(moduleConfigurations, resourceLoader, hostInterface); if (logPluginApiCalls) { const pluginLoggingProxy = { diff --git a/extensions/cxx_debugging/src/DevToolsPluginHost.ts b/extensions/cxx_debugging/src/DevToolsPluginHost.ts index d50ac08b97..c5025c26b2 100644 --- a/extensions/cxx_debugging/src/DevToolsPluginHost.ts +++ b/extensions/cxx_debugging/src/DevToolsPluginHost.ts @@ -35,7 +35,7 @@ export class WorkerPlugin implements Chrome.DevTools.LanguageExtensionPlugin, As static async create( moduleConfigurations: ModuleConfigurations = DEFAULT_MODULE_CONFIGURATIONS, - logPluginApiCalls: boolean = false): Promise { + logPluginApiCalls = false): Promise { const plugin = new WorkerPlugin(); await plugin.rpc.sendMessage('hello', moduleConfigurations, logPluginApiCalls); return plugin; diff --git a/extensions/cxx_debugging/tests/RealBackend.ts b/extensions/cxx_debugging/tests/RealBackend.ts index addcb1371e..b9c380a1ec 100644 --- a/extensions/cxx_debugging/tests/RealBackend.ts +++ b/extensions/cxx_debugging/tests/RealBackend.ts @@ -36,7 +36,7 @@ async function waitFor( reject(e); } }; - return new Promise((resolve, reject) => callback(resolve, reject)); + return await new Promise((resolve, reject) => callback(resolve, reject)); } export interface BreakLocation { @@ -218,7 +218,7 @@ export class Debugger { } async waitForScript(url: string, timeout = 0): Promise { - return waitFor(() => this.scripts.get(url)?.scriptId, timeout); + return await waitFor(() => this.scripts.get(url)?.scriptId, timeout); } async waitForPause(timeout = 0): Promise { @@ -227,10 +227,10 @@ export class Debugger { } const waitPromise = new Promise(resolve => this.waitForPauseQueue.push({resolve})); if (timeout === 0) { - return waitPromise; + return await waitPromise; } const timeoutPromise = new Promise((_, r) => setTimeout(() => r(new Error('Timeout')), timeout)); - return Promise.race([waitPromise, timeoutPromise]); + return await Promise.race([waitPromise, timeoutPromise]); } async evaluateFunction(expression: string): Promise { @@ -285,7 +285,7 @@ export class Debugger { async evaluateOnCallFrame( expectValue: boolean, convert: (result: Protocol.Runtime.RemoteObject) => T, expression: string, {callFrameId}: Protocol.Debugger.CallFrame): Promise { - return this.evaluateOnCallFrameId(expectValue, convert, expression, callFrameId); + return await this.evaluateOnCallFrameId(expectValue, convert, expression, callFrameId); } async evaluateOnCallFrameId( @@ -301,7 +301,7 @@ export class Debugger { } async waitForFunction(expression: string, timeout = 0): Promise { - return waitFor(() => this.evaluateFunction(expression), timeout); + return await waitFor(() => this.evaluateFunction(expression), timeout); } page(script: string): WasmBackendPage { @@ -465,7 +465,7 @@ class WasmBackendPage { async go(timeout = 0): Promise { await this.debug.waitForFunction('window.isReady && window.isReady()', timeout); - return this.debug.evaluateFunction('window.go()'); + return await this.debug.evaluateFunction('window.go()'); } } diff --git a/extensions/cxx_debugging/tests/TestUtils.ts b/extensions/cxx_debugging/tests/TestUtils.ts index ca00198c82..7588fdce80 100644 --- a/extensions/cxx_debugging/tests/TestUtils.ts +++ b/extensions/cxx_debugging/tests/TestUtils.ts @@ -35,7 +35,7 @@ export function makeURL(path: string): string { } export async function createWorkerPlugin(debug?: Debugger): Promise { - return WorkerPlugin.create([], true).then(p => { + return await WorkerPlugin.create([], true).then(p => { if (debug) { p.getWasmLinearMemory = debug.getWasmLinearMemory.bind(debug); p.getWasmLocal = debug.getWasmLocal.bind(debug); @@ -116,52 +116,52 @@ export class TestValue implements Value { size: number; typeNames: string[]; - static fromInt8(value: number, typeName: string = 'int8_t'): TestValue { + static fromInt8(value: number, typeName = 'int8_t'): TestValue { const content = new DataView(new ArrayBuffer(1)); content.setInt8(0, value); return new TestValue(content, typeName); } - static fromInt16(value: number, typeName: string = 'int16_t'): TestValue { + static fromInt16(value: number, typeName = 'int16_t'): TestValue { const content = new DataView(new ArrayBuffer(2)); content.setInt16(0, value, true); return new TestValue(content, typeName); } - static fromInt32(value: number, typeName: string = 'int32_t'): TestValue { + static fromInt32(value: number, typeName = 'int32_t'): TestValue { const content = new DataView(new ArrayBuffer(4)); content.setInt32(0, value, true); return new TestValue(content, typeName); } - static fromInt64(value: bigint, typeName: string = 'int64_t'): TestValue { + static fromInt64(value: bigint, typeName = 'int64_t'): TestValue { const content = new DataView(new ArrayBuffer(8)); content.setBigInt64(0, value, true); return new TestValue(content, typeName); } - static fromUint8(value: number, typeName: string = 'uint8_t'): TestValue { + static fromUint8(value: number, typeName = 'uint8_t'): TestValue { const content = new DataView(new ArrayBuffer(1)); content.setUint8(0, value); return new TestValue(content, typeName); } - static fromUint16(value: number, typeName: string = 'uint16_t'): TestValue { + static fromUint16(value: number, typeName = 'uint16_t'): TestValue { const content = new DataView(new ArrayBuffer(2)); content.setUint16(0, value, true); return new TestValue(content, typeName); } - static fromUint32(value: number, typeName: string = 'uint32_t'): TestValue { + static fromUint32(value: number, typeName = 'uint32_t'): TestValue { const content = new DataView(new ArrayBuffer(4)); content.setUint32(0, value, true); return new TestValue(content, typeName); } - static fromUint64(value: bigint, typeName: string = 'uint64_t'): TestValue { + static fromUint64(value: bigint, typeName = 'uint64_t'): TestValue { const content = new DataView(new ArrayBuffer(8)); content.setBigUint64(0, value, true); return new TestValue(content, typeName); } - static fromFloat32(value: number, typeName: string = 'float'): TestValue { + static fromFloat32(value: number, typeName = 'float'): TestValue { const content = new DataView(new ArrayBuffer(4)); content.setFloat32(0, value, true); return new TestValue(content, typeName); } - static fromFloat64(value: number, typeName: string = 'double'): TestValue { + static fromFloat64(value: number, typeName = 'double'): TestValue { const content = new DataView(new ArrayBuffer(8)); content.setFloat64(0, value, true); return new TestValue(content, typeName); diff --git a/front_end/core/common/Color.ts b/front_end/core/common/Color.ts index 74732cd401..fca46f7f63 100644 --- a/front_end/core/common/Color.ts +++ b/front_end/core/common/Color.ts @@ -65,7 +65,7 @@ function normalizeHue(hue: number): number { // and returns the canonicalized `degree`. function parseAngle(angleText: string): number|null { const angle = angleText.replace(/(deg|g?rad|turn)$/, ''); - // @ts-ignore: isNaN can accept strings + // @ts-expect-error: isNaN can accept strings if (isNaN(angle) || angleText.match(/\s+(deg|g?rad|turn)/)) { return null; } @@ -337,7 +337,7 @@ function parseAlpha(value: string|undefined): number|null { * - 20% in range [0, 1] is 0.5 */ function parsePercentOrNumber(value: string, range: [number, number] = [0, 1]): number|null { - // @ts-ignore: isNaN can accept strings + // @ts-expect-error: isNaN can accept strings if (isNaN(value.replace('%', ''))) { return null; } @@ -366,7 +366,7 @@ function parseRgbNumeric(value: string): number|null { export function parseHueNumeric(value: string): number|null { const angle = value.replace(/(deg|g?rad|turn)$/, ''); - // @ts-ignore: isNaN can accept strings + // @ts-expect-error: isNaN can accept strings if (isNaN(angle) || value.match(/\s+(deg|g?rad|turn)/)) { return null; } @@ -385,7 +385,7 @@ export function parseHueNumeric(value: string): number|null { } function parseSatLightNumeric(value: string): number|null { - // @ts-ignore: isNaN can accept strings + // @ts-expect-error: isNaN can accept strings if (value.indexOf('%') !== value.length - 1 || isNaN(value.replace('%', ''))) { return null; } @@ -762,7 +762,7 @@ export class Lab implements Color { #getRGBArray(withAlpha: true): Color4DOr3D; #getRGBArray(withAlpha: false): Color3D; - #getRGBArray(withAlpha: boolean = true): Color3D|Color4DOr3D { + #getRGBArray(withAlpha = true): Color3D|Color4DOr3D { const params = ColorConverter.xyzd50ToSrgb(...this.#toXyzd50()); if (withAlpha) { return [...params, this.alpha ?? undefined]; @@ -899,7 +899,7 @@ export class LCH implements Color { #getRGBArray(withAlpha: true): Color4DOr3D; #getRGBArray(withAlpha: false): Color3D; - #getRGBArray(withAlpha: boolean = true): Color4DOr3D|Color3D { + #getRGBArray(withAlpha = true): Color4DOr3D|Color3D { const params = ColorConverter.xyzd50ToSrgb(...this.#toXyzd50()); if (withAlpha) { return [...params, this.alpha ?? undefined]; @@ -1039,7 +1039,7 @@ export class Oklab implements Color { #getRGBArray(withAlpha: true): Color4DOr3D; #getRGBArray(withAlpha: false): Color3D; - #getRGBArray(withAlpha: boolean = true): Color4DOr3D|Color3D { + #getRGBArray(withAlpha = true): Color4DOr3D|Color3D { const params = ColorConverter.xyzd50ToSrgb(...this.#toXyzd50()); if (withAlpha) { return [...params, this.alpha ?? undefined]; @@ -1176,7 +1176,7 @@ export class Oklch implements Color { #getRGBArray(withAlpha: true): Color4DOr3D; #getRGBArray(withAlpha: false): Color3D; - #getRGBArray(withAlpha: boolean = true): Color4DOr3D|Color3D { + #getRGBArray(withAlpha = true): Color4DOr3D|Color3D { const params = ColorConverter.xyzd50ToSrgb(...this.#toXyzd50()); if (withAlpha) { return [...params, this.alpha ?? undefined]; @@ -1336,7 +1336,7 @@ export class ColorFunction implements Color { #getRGBArray(withAlpha: true): Color4DOr3D; #getRGBArray(withAlpha: false): Color3D; - #getRGBArray(withAlpha: boolean = true): Color4DOr3D|Color3D { + #getRGBArray(withAlpha = true): Color4DOr3D|Color3D { // With color(), out-of-gamut inputs are to be used for intermediate computations const [p0, p1, p2] = this.#rawParams; const params: Color3D = @@ -1531,7 +1531,7 @@ export class HSL implements Color { #getRGBArray(withAlpha: true): Color4DOr3D; #getRGBArray(withAlpha: false): Color3D; - #getRGBArray(withAlpha: boolean = true): Color4DOr3D|Color3D { + #getRGBArray(withAlpha = true): Color4DOr3D|Color3D { const rgb = hsl2rgb([this.h, this.s, this.l, 0]); if (withAlpha) { return [rgb[0], rgb[1], rgb[2], this.alpha ?? undefined]; @@ -1682,7 +1682,7 @@ export class HWB implements Color { #getRGBArray(withAlpha: true): Color4DOr3D; #getRGBArray(withAlpha: false): Color3D; - #getRGBArray(withAlpha: boolean = true): Color4DOr3D|Color3D { + #getRGBArray(withAlpha = true): Color4DOr3D|Color3D { const rgb = hwb2rgb([this.h, this.w, this.b, 0]); if (withAlpha) { return [rgb[0], rgb[1], rgb[2], this.alpha ?? undefined]; @@ -2200,9 +2200,9 @@ export class Legacy implements Color { } } -export const Regex: RegExp = +export const Regex = /((?:rgba?|hsla?|hwba?|lab|lch|oklab|oklch|color)\([^)]+\)|#[0-9a-fA-F]{8}|#[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,4}|\b[a-zA-Z]+\b(?!-))/g; -export const ColorMixRegex: RegExp = /color-mix\(.*,\s*(?.+)\s*,\s*(?.+)\s*\)/g; +export const ColorMixRegex = /color-mix\(.*,\s*(?.+)\s*,\s*(?.+)\s*\)/g; const COLOR_TO_RGBA_ENTRIES: Array = [ ['aliceblue', [240, 248, 255]], diff --git a/front_end/core/common/ColorConverter.ts b/front_end/core/common/ColorConverter.ts index 2a8367873d..b9d2311e26 100644 --- a/front_end/core/common/ColorConverter.ts +++ b/front_end/core/common/ColorConverter.ts @@ -66,7 +66,7 @@ class TransferFunction { e: number; f: number; - constructor(g: number, a: number, b: number = 0, c: number = 0, d: number = 0, e: number = 0, f: number = 0) { + constructor(g: number, a: number, b = 0, c = 0, d = 0, e = 0, f = 0) { this.g = g; this.a = a; this.b = b; diff --git a/front_end/core/common/ResolverBase.ts b/front_end/core/common/ResolverBase.ts index 5ce26de2be..cb0e0b9ad8 100644 --- a/front_end/core/common/ResolverBase.ts +++ b/front_end/core/common/ResolverBase.ts @@ -28,7 +28,7 @@ export abstract class ResolverBase { async waitFor(id: Id): Promise { const obj = this.getForId(id); if (!obj) { - return this.getOrCreatePromise(id); + return await this.getOrCreatePromise(id); } return obj; } diff --git a/front_end/core/common/Revealer.ts b/front_end/core/common/Revealer.ts index 53528dcbc4..96eb3e0d92 100644 --- a/front_end/core/common/Revealer.ts +++ b/front_end/core/common/Revealer.ts @@ -164,7 +164,7 @@ export function registerRevealer(registration: RevealerRegistration): void * @param revealable the object to reveal. * @param omitFocus whether to omit focusing on the presentation of `revealable` afterwards. */ -export async function reveal(revealable: unknown, omitFocus: boolean = false): Promise { +export async function reveal(revealable: unknown, omitFocus = false): Promise { await RevealerRegistry.instance().reveal(revealable, omitFocus); } diff --git a/front_end/core/common/SettingRegistration.ts b/front_end/core/common/SettingRegistration.ts index fc17d6fcbf..de38248b87 100644 --- a/front_end/core/common/SettingRegistration.ts +++ b/front_end/core/common/SettingRegistration.ts @@ -97,7 +97,7 @@ export function getRegisteredSettings(): SettingRegistration[] { return registeredSettings.filter(setting => Root.Runtime.Runtime.isDescriptorEnabled(setting)); } -export function registerSettingsForTest(settings: SettingRegistration[], forceReset: boolean = false): void { +export function registerSettingsForTest(settings: SettingRegistration[], forceReset = false): void { if (registeredSettings.length === 0 || forceReset) { registeredSettings = settings; settingNameSet.clear(); diff --git a/front_end/core/common/Settings.ts b/front_end/core/common/Settings.ts index aa1408d463..d0bcd40304 100644 --- a/front_end/core/common/Settings.ts +++ b/front_end/core/common/Settings.ts @@ -256,7 +256,7 @@ export const NOOP_STORAGE: SettingsBackingStore = { export class SettingsStorage { constructor( private object: Record, private readonly backingStore: SettingsBackingStore = NOOP_STORAGE, - private readonly storagePrefix: string = '') { + private readonly storagePrefix = '') { } register(name: string): void { @@ -690,11 +690,11 @@ export class VersionController { Math.min(this.#globalVersionSetting.get(), this.#syncedVersionSetting.get(), this.#localVersionSetting.get()); const methodsToRun = this.methodsToRunToUpdateVersion(minimumVersion, currentVersion); console.assert( - // @ts-ignore + // @ts-expect-error this[`updateVersionFrom${currentVersion}To${currentVersion + 1}`] === undefined, 'Unexpected migration method found. Increment CURRENT_VERSION or remove the method.'); for (const method of methodsToRun) { - // @ts-ignore Special version method matching + // @ts-expect-error Special version method matching this[method].call(this); } this.resetToCurrent(); diff --git a/front_end/core/dom_extension/DOMExtension.ts b/front_end/core/dom_extension/DOMExtension.ts index 5060011dba..eccfb7f374 100644 --- a/front_end/core/dom_extension/DOMExtension.ts +++ b/front_end/core/dom_extension/DOMExtension.ts @@ -34,6 +34,7 @@ * http://ejohn.org/files/jsdiff.js (released under the MIT license). */ +// eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-nocheck This file is not checked by TypeScript Compiler as it has a lot of legacy code. import * as Platform from '../platform/platform.js'; @@ -290,7 +291,7 @@ Node.prototype.isSelfOrDescendant = function(node: Node|null): boolean { return Boolean(node) && (node === this || this.isDescendant(node)); }; -Node.prototype.traverseNextNode = function(stayWithin?: Node, skipShadowRoot: boolean = false): Node|null { +Node.prototype.traverseNextNode = function(stayWithin?: Node, skipShadowRoot = false): Node|null { if (!skipShadowRoot && this.shadowRoot) { return this.shadowRoot; } diff --git a/front_end/core/host/InspectorFrontendHost.ts b/front_end/core/host/InspectorFrontendHost.ts index 0ca98788aa..518530ffda 100644 --- a/front_end/core/host/InspectorFrontendHost.ts +++ b/front_end/core/host/InspectorFrontendHost.ts @@ -406,7 +406,7 @@ export class InspectorFrontendHostStub implements InspectorFrontendHostAPI { getSyncInformation(callback: (arg0: SyncInformation) => void): void { if ('getSyncInformationForTesting' in globalThis) { - // @ts-ignore for testing + // @ts-expect-error for testing return callback(globalThis.getSyncInformationForTesting()); } callback({ @@ -554,14 +554,14 @@ export class InspectorFrontendHostStub implements InspectorFrontendHostAPI { } } -// @ts-ignore Global injected by devtools_compatibility.js +// @ts-expect-error Global injected by devtools_compatibility.js // eslint-disable-next-line @typescript-eslint/naming-convention export let InspectorFrontendHostInstance: InspectorFrontendHostStub = globalThis.InspectorFrontendHost; class InspectorFrontendAPIImpl { constructor() { for (const descriptor of EventDescriptors) { - // @ts-ignore Dispatcher magic + // @ts-expect-error Dispatcher magic this[descriptor[1]] = this.dispatch.bind(this, descriptor[0], descriptor[2], descriptor[3]); } } @@ -602,7 +602,7 @@ function initializeInspectorFrontendHost(): void { let proto; if (!InspectorFrontendHostInstance) { // Instantiate stub for web-hosted mode if necessary. - // @ts-ignore Global injected by devtools_compatibility.js + // @ts-expect-error Global injected by devtools_compatibility.js globalThis.InspectorFrontendHost = InspectorFrontendHostInstance = new InspectorFrontendHostStub(); } else { // Otherwise add stubs for missing methods that are declared in the interface. @@ -611,13 +611,13 @@ function initializeInspectorFrontendHost(): void { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) // @ts-expect-error const stub = proto[name]; - // @ts-ignore Global injected by devtools_compatibility.js + // @ts-expect-error Global injected by devtools_compatibility.js if (typeof stub !== 'function' || InspectorFrontendHostInstance[name]) { continue; } console.error(`Incompatible embedder: method Host.InspectorFrontendHost.${name} is missing. Using stub instead.`); - // @ts-ignore Global injected by devtools_compatibility.js + // @ts-expect-error Global injected by devtools_compatibility.js InspectorFrontendHostInstance[name] = stub; } } @@ -629,7 +629,7 @@ function initializeInspectorFrontendHost(): void { // FIXME: This file is included into both apps, since the devtools_app needs the InspectorFrontendHostAPI only, // so the host instance should not be initialized there. initializeInspectorFrontendHost(); -// @ts-ignore Global injected by devtools_compatibility.js +// @ts-expect-error Global injected by devtools_compatibility.js globalThis.InspectorFrontendAPI = new InspectorFrontendAPIImpl(); })(); diff --git a/front_end/core/platform/MimeType.ts b/front_end/core/platform/MimeType.ts index 14c4e05c3a..f65aa6b1a2 100644 --- a/front_end/core/platform/MimeType.ts +++ b/front_end/core/platform/MimeType.ts @@ -148,7 +148,7 @@ function parseMimeType(contentType: string): {mimeType: string|null, params: Map * @returns the smallest index of any character in 'characters' or -1 if none of * the characters occur in 'searchString' */ -function findFirstIndexOf(searchString: string, characters: string, pos: number = 0): number { +function findFirstIndexOf(searchString: string, characters: string, pos = 0): number { for (let i = pos; i < searchString.length; i++) { if (characters.includes(searchString[i])) { return i; @@ -161,7 +161,7 @@ function findFirstIndexOf(searchString: string, characters: string, pos: number * @returns the smallest index of any character not in 'characters' or -1 if only * 'characters' occur in 'searchString' */ -function findFirstIndexNotOf(searchString: string, characters: string, pos: number = 0): number { +function findFirstIndexNotOf(searchString: string, characters: string, pos = 0): number { for (let i = pos; i < searchString.length; i++) { if (!characters.includes(searchString[i])) { return i; diff --git a/front_end/core/platform/NumberUtilities.ts b/front_end/core/platform/NumberUtilities.ts index ba5ed894f9..c16f3ca12a 100644 --- a/front_end/core/platform/NumberUtilities.ts +++ b/front_end/core/platform/NumberUtilities.ts @@ -27,7 +27,7 @@ export const toFixedIfFloating = (value: string): string => { /** * Rounds a number (including float) down. */ -export const floor = (value: number, precision: number = 0): number => { +export const floor = (value: number, precision = 0): number => { // Allows for rounding to the nearest whole number. // Ex: 1 / 10 -> round down to nearest 10th place // Ex: 1 / 5 -> round down to nearest 5 diff --git a/front_end/core/platform/StringUtilities.ts b/front_end/core/platform/StringUtilities.ts index f4c94e2a5f..c7ddf05471 100644 --- a/front_end/core/platform/StringUtilities.ts +++ b/front_end/core/platform/StringUtilities.ts @@ -52,7 +52,7 @@ export const formatAsJSLiteral = (content: string): string => { const escapePattern = (match: string, pattern: string, controlChar: string, loneSurrogate: string): string => { if (controlChar) { if (escapedReplacements.has(controlChar)) { - // @ts-ignore https://github.com/microsoft/TypeScript/issues/13086 + // @ts-expect-error https://github.com/microsoft/TypeScript/issues/13086 return escapedReplacements.get(controlChar); } const twoDigitHex = toHexadecimal(controlChar.charCodeAt(0), 2); @@ -292,7 +292,7 @@ export const filterRegex = function(query: string): RegExp { }; export const createSearchRegex = function( - query: string, caseSensitive: boolean, isRegex: boolean, matchWholeWord: boolean = false): RegExp { + query: string, caseSensitive: boolean, isRegex: boolean, matchWholeWord = false): RegExp { const regexFlags = caseSensitive ? 'g' : 'gi'; let regexObject; diff --git a/front_end/core/protocol_client/InspectorBackend.ts b/front_end/core/protocol_client/InspectorBackend.ts index bc9f4441cc..ea3d37affe 100644 --- a/front_end/core/protocol_client/InspectorBackend.ts +++ b/front_end/core/protocol_client/InspectorBackend.ts @@ -101,7 +101,7 @@ interface CallbackWithDebugInfo { export class InspectorBackend { readonly agentPrototypes = new Map(); - #initialized: boolean = false; + #initialized = false; #eventParameterNamesForDomain = new Map(); readonly typeMap = new Map(); readonly enumMap = new Map>(); @@ -153,13 +153,13 @@ export class InspectorBackend { registerEnum(type: QualifiedName, values: Record): void { const [domain, name] = splitQualifiedName(type); - // @ts-ignore globalThis global namespace pollution + // @ts-expect-error globalThis global namespace pollution if (!globalThis.Protocol[domain]) { - // @ts-ignore globalThis global namespace pollution + // @ts-expect-error globalThis global namespace pollution globalThis.Protocol[domain] = {}; } - // @ts-ignore globalThis global namespace pollution + // @ts-expect-error globalThis global namespace pollution globalThis.Protocol[domain][name] = values; this.enumMap.set(type, values); this.#initialized = true; @@ -947,7 +947,7 @@ class AgentPrototype { function sendMessagePromise(this: AgentPrototype, ...args: unknown[]): Promise { return AgentPrototype.prototype.sendMessageToBackendPromise.call(this, domainAndMethod, parameters, args); } - // @ts-ignore Method code generation + // @ts-expect-error Method code generation this[methodName] = sendMessagePromise; this.metadata[domainAndMethod] = {parameters, description, replyArgs}; @@ -955,7 +955,7 @@ class AgentPrototype { return this.invoke(domainAndMethod, request); } - // @ts-ignore Method code generation + // @ts-expect-error Method code generation this['invoke_' + methodName] = invoke; this.replyArgs[domainAndMethod] = replyArgs; } @@ -1107,7 +1107,7 @@ class DispatcherManager { if (event in dispatcher) { const f = dispatcher[event as string as keyof ProtocolProxyApi.ProtocolDispatchers[Domain]]; - // @ts-ignore Can't type check the dispatch. + // @ts-expect-error Can't type check the dispatch. f.call(dispatcher, messageParams); } } diff --git a/front_end/core/protocol_client/protocol_client.ts b/front_end/core/protocol_client/protocol_client.ts index 6f4b3f92db..ccc94969a9 100644 --- a/front_end/core/protocol_client/protocol_client.ts +++ b/front_end/core/protocol_client/protocol_client.ts @@ -14,7 +14,7 @@ export { // Create the global here because registering commands will involve putting // items onto the global. -// @ts-ignore Global namespace instantiation +// @ts-expect-error Global namespace instantiation self.Protocol = self.Protocol || {}; // FIXME: This instance of InspectorBackend should not be a side effect of importing this module. diff --git a/front_end/core/sdk/AnimationModel.ts b/front_end/core/sdk/AnimationModel.ts index 71007195cb..7bd3a3201d 100644 --- a/front_end/core/sdk/AnimationModel.ts +++ b/front_end/core/sdk/AnimationModel.ts @@ -57,7 +57,7 @@ export class AnimationDOMNode { #scrollListenersById: Map; #scrollBindingListener?: BindingListener; - static lastAddedListenerId: number = 0; + static lastAddedListenerId = 0; constructor(domNode: DOMNode) { this.#domNode = domNode; @@ -138,14 +138,14 @@ export class AnimationDOMNode { } const scrollingElement = ('scrollingElement' in this ? this.scrollingElement : this) as HTMLElement; - // @ts-ignore We're setting a custom field on `Element` or `Document` for retaining the function on the page. + // @ts-expect-error We're setting a custom field on `Element` or `Document` for retaining the function on the page. this[scrollListenerNameInPage] = () => { - // @ts-ignore `reportScrollPosition` binding is injected to the page before calling the function. + // @ts-expect-error `reportScrollPosition` binding is injected to the page before calling the function. globalThis[reportScrollPositionBindingName]( JSON.stringify({scrollTop: scrollingElement.scrollTop, scrollLeft: scrollingElement.scrollLeft, id})); }; - // @ts-ignore We've already defined the function used below. + // @ts-expect-error We've already defined the function used below. this.addEventListener('scroll', this[scrollListenerNameInPage], true); } } @@ -168,15 +168,15 @@ export class AnimationDOMNode { } function removeScrollListenerInPage(this: HTMLElement|Document, scrollListenerNameInPage: string): void { - // @ts-ignore We've already set this custom field while adding scroll listener. + // @ts-expect-error We've already set this custom field while adding scroll listener. this.removeEventListener('scroll', this[scrollListenerNameInPage]); - // @ts-ignore We've already set this custom field while adding scroll listener. + // @ts-expect-error We've already set this custom field while adding scroll listener. delete this[scrollListenerNameInPage]; } } async scrollTop(): Promise { - return this.#domNode.callFunction(scrollTopInPage).then(res => res?.value ?? null); + return await this.#domNode.callFunction(scrollTopInPage).then(res => res?.value ?? null); function scrollTopInPage(this: Element|Document): number { if ('scrollingElement' in this) { @@ -191,7 +191,7 @@ export class AnimationDOMNode { } async scrollLeft(): Promise { - return this.#domNode.callFunction(scrollLeftInPage).then(res => res?.value ?? null); + return await this.#domNode.callFunction(scrollLeftInPage).then(res => res?.value ?? null); function scrollLeftInPage(this: Element|Document): number { if ('scrollingElement' in this) { @@ -238,7 +238,7 @@ export class AnimationDOMNode { } async verticalScrollRange(): Promise { - return this.#domNode.callFunction(verticalScrollRangeInPage).then(res => res?.value ?? null); + return await this.#domNode.callFunction(verticalScrollRangeInPage).then(res => res?.value ?? null); function verticalScrollRangeInPage(this: Element|Document): number { if ('scrollingElement' in this) { @@ -254,7 +254,7 @@ export class AnimationDOMNode { } async horizontalScrollRange(): Promise { - return this.#domNode.callFunction(horizontalScrollRangeInPage).then(res => res?.value ?? null); + return await this.#domNode.callFunction(horizontalScrollRangeInPage).then(res => res?.value ?? null); function horizontalScrollRangeInPage(this: Element|Document): number { if ('scrollingElement' in this) { @@ -1065,7 +1065,7 @@ export class ScreenshotCapture { readonly #screenCaptureModel: ScreenCaptureModel; readonly #animationModel: AnimationModel; // This prevents multiple synchronous calls to captureScreenshots to result in one startScreencast call in model. - #isCapturing: boolean = false; + #isCapturing = false; // Holds the id for capturing & cancelling the screencast operation. #screencastOperationId: number|undefined; #stopTimer?: number; diff --git a/front_end/core/sdk/CPUThrottlingManager.ts b/front_end/core/sdk/CPUThrottlingManager.ts index 43383b3376..01af9b7d9c 100644 --- a/front_end/core/sdk/CPUThrottlingManager.ts +++ b/front_end/core/sdk/CPUThrottlingManager.ts @@ -128,14 +128,14 @@ export class CPUThrottlingManager extends Common.ObjectWrapper.ObjectWrapper { + return await new Promise(r => { this.#pendingMainTargetPromise = (result: number) => { r(result); existingCallback(result); }; }); } - return new Promise(r => { + return await new Promise(r => { this.#pendingMainTargetPromise = r; }); } diff --git a/front_end/core/sdk/CSSMatchedStyles.ts b/front_end/core/sdk/CSSMatchedStyles.ts index 93383ec5c4..cc65dec604 100644 --- a/front_end/core/sdk/CSSMatchedStyles.ts +++ b/front_end/core/sdk/CSSMatchedStyles.ts @@ -815,7 +815,7 @@ class NodeCascade { readonly activeProperties = new Map(); constructor( matchedStyles: CSSMatchedStyles, styles: CSSStyleDeclaration[], isInherited: boolean, - isHighlightPseudoCascade: boolean = false) { + isHighlightPseudoCascade = false) { this.#matchedStyles = matchedStyles; this.styles = styles; this.#isInherited = isInherited; diff --git a/front_end/core/sdk/CSSMetadata.ts b/front_end/core/sdk/CSSMetadata.ts index 5b1bf4cc0f..940fd0c4cd 100644 --- a/front_end/core/sdk/CSSMetadata.ts +++ b/front_end/core/sdk/CSSMetadata.ts @@ -367,13 +367,13 @@ export class CSSMetadata { // [^- ][a-zA-Z-]+ matches property key values (e.g. smaller, x-large, initial) // -?\+?(?:[0-9]+\.[0-9]+|\.[0-9]+|[0-9]+) matches numeric property values (e.g. -.23, 3.3, 55) // [a-zA-Z%]{0,4} matches the units of numeric property values (e.g. px, vmin, or blank units) -export const FontPropertiesRegex: RegExp = /^[^- ][a-zA-Z-]+$|^-?\+?(?:[0-9]+\.[0-9]+|\.[0-9]+|[0-9]+)[a-zA-Z%]{0,4}$/; +export const FontPropertiesRegex = /^[^- ][a-zA-Z-]+$|^-?\+?(?:[0-9]+\.[0-9]+|\.[0-9]+|[0-9]+)[a-zA-Z%]{0,4}$/; // "[\w \,-]+",? ? matches double quoted values and the trailing comma/space (e.g. "Tahoma", ) // ('[\w \,-]+',? ?) matches single quoted values and the trailing comma/space (e.g. 'Segoe UI', ) // ([\w \,-]+,? ?) matches non quoted values and the trailing comma/space (e.g. Helvetica) // (?: ...)+ will match 1 or more of the groups above such that it would match a value with fallbacks (e.g. "Tahoma", 'Segoe UI', Helvetica) -export const FontFamilyRegex: RegExp = /^("[\w \,-]+"?, ?|'[\w \,-]+',? ?|[\w \-]+,? ?)+$/; +export const FontFamilyRegex = /^("[\w \,-]+"?, ?|'[\w \,-]+',? ?|[\w \-]+,? ?)+$/; export const CubicBezierKeywordValues = new Map([ ['linear', 'cubic-bezier(0, 0, 1, 1)'], diff --git a/front_end/core/sdk/CSSModel.ts b/front_end/core/sdk/CSSModel.ts index 3ce2f0e1d1..bbe36bc4cd 100644 --- a/front_end/core/sdk/CSSModel.ts +++ b/front_end/core/sdk/CSSModel.ts @@ -398,7 +398,7 @@ export class CSSModel extends SDKModel { if (!this.isEnabled()) { await this.enable(); } - return this.#styleLoader.computedStylePromise(nodeId); + return await this.#styleLoader.computedStylePromise(nodeId); } async getBackgroundColors(nodeId: Protocol.DOM.NodeId): Promise { @@ -828,7 +828,7 @@ export class CSSModel extends SDKModel { } override async resumeModel(): Promise { - return this.enable(); + return await this.enable(); } setEffectivePropertyValueForNode(nodeId: Protocol.DOM.NodeId, propertyName: string, value: string): void { diff --git a/front_end/core/sdk/CSSProperty.ts b/front_end/core/sdk/CSSProperty.ts index 33f04bb809..364b83a8f6 100644 --- a/front_end/core/sdk/CSSProperty.ts +++ b/front_end/core/sdk/CSSProperty.ts @@ -255,7 +255,7 @@ export class CSSProperty extends Common.ObjectWrapper.ObjectWrapper const text = new TextUtils.Text.Text(this.ownerStyle.cssText || ''); const newStyleText = text.replaceRange(range, Platform.StringUtilities.sprintf(';%s;', propertyText)); const styleText = await CSSProperty.formatStyle(newStyleText, indentation, endIndentation); - return this.ownerStyle.setText(styleText, majorChange); + return await this.ownerStyle.setText(styleText, majorChange); } static async formatStyle(styleText: string, indentation: string, endIndentation: string): Promise { @@ -383,7 +383,7 @@ export class CSSProperty extends Common.ObjectWrapper.ObjectWrapper } else { text = appendSemicolonIfMissing(this.text.substring(2, propertyText.length - 2).trim()); } - return this.setText(text, true, true); + return await this.setText(text, true, true); } /** diff --git a/front_end/core/sdk/CSSPropertyParser.ts b/front_end/core/sdk/CSSPropertyParser.ts index 5f9a27b758..b725dbf70c 100644 --- a/front_end/core/sdk/CSSPropertyParser.ts +++ b/front_end/core/sdk/CSSPropertyParser.ts @@ -293,7 +293,7 @@ class ComputedTextChunk { export class ComputedText { readonly #chunks: ComputedTextChunk[] = []; readonly text: string; - #sorted: boolean = true; + #sorted = true; constructor(text: string) { this.text = text; } diff --git a/front_end/core/sdk/CSSSupports.ts b/front_end/core/sdk/CSSSupports.ts index 62a838449d..96a7021b41 100644 --- a/front_end/core/sdk/CSSSupports.ts +++ b/front_end/core/sdk/CSSSupports.ts @@ -13,7 +13,7 @@ export class CSSSupports extends CSSQuery { return payload.map(supports => new CSSSupports(cssModel, supports)); } - #active: boolean = true; + #active = true; constructor(cssModel: CSSModel, payload: Protocol.CSS.CSSSupports) { super(cssModel); diff --git a/front_end/core/sdk/ConsoleModel.ts b/front_end/core/sdk/ConsoleModel.ts index a0f8e6ef96..4175922e47 100644 --- a/front_end/core/sdk/ConsoleModel.ts +++ b/front_end/core/sdk/ConsoleModel.ts @@ -485,7 +485,7 @@ export class ConsoleModel extends SDKModel { ++index; } const name = prefix + index; - // @ts-ignore Assignment to global object + // @ts-expect-error Assignment to global object this[name] = value; return name; } @@ -604,7 +604,7 @@ export class ConsoleMessage { #exceptionId?: number = undefined; #affectedResources?: AffectedResources; category?: Protocol.Log.LogEntryCategory; - isCookieReportIssue: boolean = false; + isCookieReportIssue = false; /** * The parent frame of the `console.log` call of logpoints or conditional breakpoints diff --git a/front_end/core/sdk/DOMDebuggerModel.ts b/front_end/core/sdk/DOMDebuggerModel.ts index 9f90a487a3..ba64d2c336 100644 --- a/front_end/core/sdk/DOMDebuggerModel.ts +++ b/front_end/core/sdk/DOMDebuggerModel.ts @@ -380,9 +380,9 @@ export class EventListener { }, type: string, listener: () => void, useCapture: boolean): void { this.removeEventListener(type, listener, useCapture); - // @ts-ignore: + // @ts-expect-error: if (this['on' + type]) { - // @ts-ignore: + // @ts-expect-error: this['on' + type] = undefined; } } diff --git a/front_end/core/sdk/DOMModel.ts b/front_end/core/sdk/DOMModel.ts index 895244c419..4e64cc7b1f 100644 --- a/front_end/core/sdk/DOMModel.ts +++ b/front_end/core/sdk/DOMModel.ts @@ -215,7 +215,7 @@ export class DOMNode { private async requestChildDocument(frameId: Protocol.Page.FrameId, notInTarget: Target): Promise { const frame = await FrameManager.instance().getOrWaitForFrame(frameId, notInTarget); const childModel = frame.resourceTreeModel()?.target().model(DOMModel); - return childModel?.requestDocument() || null; + return await (childModel?.requestDocument() || null); } isAdFrameNode(): boolean { @@ -1565,7 +1565,7 @@ export class DOMModel extends SDKModel { name: string, value: string, }>, - pierce: boolean = false): Promise { + pierce = false): Promise { await this.requestDocument(); if (!this.#document) { throw new Error('DOMModel.getNodesByStyle expects to have a document.'); @@ -1836,7 +1836,7 @@ export class DOMModelUndoStack { async undo(): Promise { if (this.#index === 0) { - return Promise.resolve(); + return await Promise.resolve(); } --this.#index; this.#lastModelWithMinorChange = null; @@ -1845,7 +1845,7 @@ export class DOMModelUndoStack { async redo(): Promise { if (this.#index >= this.#stack.length) { - return Promise.resolve(); + return await Promise.resolve(); } ++this.#index; this.#lastModelWithMinorChange = null; diff --git a/front_end/core/sdk/DebuggerModel.ts b/front_end/core/sdk/DebuggerModel.ts index 70991e65d9..2e95f0df65 100644 --- a/front_end/core/sdk/DebuggerModel.ts +++ b/front_end/core/sdk/DebuggerModel.ts @@ -332,7 +332,7 @@ export class DebuggerModel extends SDKModel { const maxScriptsCacheSize = isRemoteFrontend ? 10e6 : 100e6; const enablePromise = this.agent.invoke_enable({maxScriptsCacheSize}); void enablePromise.then(this.registerDebugger.bind(this)); - return enablePromise; + return await enablePromise; } private onFrameNavigated(): void { @@ -895,7 +895,7 @@ export class DebuggerModel extends SDKModel { if (!callFrame) { throw new Error('No call frame selected'); } - return callFrame.evaluate(options); + return await callFrame.evaluate(options); } functionDetailsPromise(remoteObject: RemoteObject): Promise { diff --git a/front_end/core/sdk/EmulationModel.ts b/front_end/core/sdk/EmulationModel.ts index 8caba63ca2..92e9cbeedb 100644 --- a/front_end/core/sdk/EmulationModel.ts +++ b/front_end/core/sdk/EmulationModel.ts @@ -446,7 +446,7 @@ export class EmulationModel extends SDKModel { value: this.#mediaConfiguration.get('prefers-reduced-transparency') ?? '', }, ]; - return this.emulateCSSMedia(type, features); + return await this.emulateCSSMedia(type, features); } } diff --git a/front_end/core/sdk/FrameManager.ts b/front_end/core/sdk/FrameManager.ts index 62c7ee8ba3..1d07d44e94 100644 --- a/front_end/core/sdk/FrameManager.ts +++ b/front_end/core/sdk/FrameManager.ts @@ -207,7 +207,7 @@ export class FrameManager extends Common.ObjectWrapper.ObjectWrapper if (frame && (!notInTarget || notInTarget !== frame.resourceTreeModel().target())) { return frame; } - return new Promise(resolve => { + return await new Promise(resolve => { const waiting = this.#awaitedFrames.get(frameId); if (waiting) { waiting.push({notInTarget, resolve}); diff --git a/front_end/core/sdk/HeapProfilerModel.ts b/front_end/core/sdk/HeapProfilerModel.ts index cc68c13e2f..ce7b050227 100644 --- a/front_end/core/sdk/HeapProfilerModel.ts +++ b/front_end/core/sdk/HeapProfilerModel.ts @@ -59,7 +59,7 @@ export class HeapProfilerModel extends SDKModel { throw new Error('Sampling profiler is not running.'); } if (--this.#samplingProfilerDepth) { - return this.getSamplingProfile(); + return await this.getSamplingProfile(); } const response = await this.#heapProfilerAgent.invoke_stopSampling(); if (response.getError()) { diff --git a/front_end/core/sdk/NetworkManager.ts b/front_end/core/sdk/NetworkManager.ts index 750a9e851b..95393462c4 100644 --- a/front_end/core/sdk/NetworkManager.ts +++ b/front_end/core/sdk/NetworkManager.ts @@ -368,8 +368,8 @@ export class NetworkManager extends SDKModel { return result.status; } - async enableReportingApi(enable: boolean = true): Promise> { - return this.#networkAgent.invoke_enableReportingApi({enable}); + async enableReportingApi(enable = true): Promise> { + return await this.#networkAgent.invoke_enableReportingApi({enable}); } async loadNetworkResource( @@ -1701,7 +1701,7 @@ export class MultitargetNetworkManager extends Common.ObjectWrapper.ObjectWrappe const allowRemoteFilePaths = Common.Settings.Settings.instance().moduleSetting('network.enable-remote-file-loading').get(); - return new Promise( + return await new Promise( resolve => Host.ResourceLoader.load(url, headers, (success, _responseHeaders, content, errorDescription) => { resolve({success, content, errorDescription}); }, allowRemoteFilePaths)); diff --git a/front_end/core/sdk/NetworkRequest.ts b/front_end/core/sdk/NetworkRequest.ts index f1c23ea3a4..546541e7d6 100644 --- a/front_end/core/sdk/NetworkRequest.ts +++ b/front_end/core/sdk/NetworkRequest.ts @@ -1422,7 +1422,7 @@ export class NetworkRequest extends Common.ObjectWrapper.ObjectWrapper { if (!this.#contentDataProvider) { - return NetworkManager.searchInRequest(this, query, caseSensitive, isRegex); + return await NetworkManager.searchInRequest(this, query, caseSensitive, isRegex); } const contentData = await this.requestContentData(); diff --git a/front_end/core/sdk/OverlayModel.ts b/front_end/core/sdk/OverlayModel.ts index d95fcb71f9..52d37003b9 100644 --- a/front_end/core/sdk/OverlayModel.ts +++ b/front_end/core/sdk/OverlayModel.ts @@ -183,11 +183,11 @@ export class OverlayModel extends SDKModel implements ProtocolProxyA } static async muteHighlight(): Promise { - return Promise.all(TargetManager.instance().models(OverlayModel).map(model => model.suspendModel())); + return await Promise.all(TargetManager.instance().models(OverlayModel).map(model => model.suspendModel())); } static async unmuteHighlight(): Promise { - return Promise.all(TargetManager.instance().models(OverlayModel).map(model => model.resumeModel())); + return await Promise.all(TargetManager.instance().models(OverlayModel).map(model => model.resumeModel())); } static highlightRect(rect: HighlightRect): void { @@ -787,7 +787,7 @@ export class OverlayModel extends SDKModel implements ProtocolProxyA } async hasStyleSheetText(url: Platform.DevToolsPath.UrlString): Promise { - return this.#windowControls.initializeStyleSheetText(url); + return await this.#windowControls.initializeStyleSheetText(url); } } diff --git a/front_end/core/sdk/OverlayPersistentHighlighter.ts b/front_end/core/sdk/OverlayPersistentHighlighter.ts index 4777cdf9bb..ec82df0e1d 100644 --- a/front_end/core/sdk/OverlayPersistentHighlighter.ts +++ b/front_end/core/sdk/OverlayPersistentHighlighter.ts @@ -415,7 +415,7 @@ export class OverlayPersistentHighlighter { const currentURL = document ? document.documentURL : Platform.DevToolsPath.EmptyUrlString; await Promise.all(this.#persistentHighlightSetting.get().map(async persistentHighlight => { if (persistentHighlight.url === currentURL) { - return this.#model.getDOMModel().pushNodeByPathToFrontend(persistentHighlight.path).then(nodeId => { + return await this.#model.getDOMModel().pushNodeByPathToFrontend(persistentHighlight.path).then(nodeId => { const node = this.#model.getDOMModel().nodeForId(nodeId); if (!node) { return; diff --git a/front_end/core/sdk/PageResourceLoader.ts b/front_end/core/sdk/PageResourceLoader.ts index 4642a1f886..33c59fe44d 100644 --- a/front_end/core/sdk/PageResourceLoader.ts +++ b/front_end/core/sdk/PageResourceLoader.ts @@ -294,7 +294,7 @@ export class PageResourceLoader extends Common.ObjectWrapper.ObjectWrapper { export class PreloadingModel extends SDKModel { private agent: ProtocolProxyApi.PreloadApi; private loaderIds: Protocol.Network.LoaderId[] = []; - private targetJustAttached: boolean = true; + private targetJustAttached = true; private lastPrimaryPageModel: PreloadingModel|null = null; private documents: Map = new Map(); diff --git a/front_end/core/sdk/RehydratingConnection.ts b/front_end/core/sdk/RehydratingConnection.ts index 18ccc8ba48..74ce141483 100644 --- a/front_end/core/sdk/RehydratingConnection.ts +++ b/front_end/core/sdk/RehydratingConnection.ts @@ -246,7 +246,7 @@ export class RehydratingSession extends RehydratingSessionBase { this.sessionAttachToTarget(); } - override sendMessageToFrontend(payload: ServerMessage, attachSessionId: boolean = true): void { + override sendMessageToFrontend(payload: ServerMessage, attachSessionId = true): void { // Attach the session's Id to the message. if (this.sessionId !== 0 && attachSessionId) { payload.sessionId = this.sessionId; diff --git a/front_end/core/sdk/RemoteObject.ts b/front_end/core/sdk/RemoteObject.ts index fc2f329a5e..6d5b17c6ff 100644 --- a/front_end/core/sdk/RemoteObject.ts +++ b/front_end/core/sdk/RemoteObject.ts @@ -156,9 +156,8 @@ export abstract class RemoteObject { return {value: objectAsProtocolRemoteObject.value}; } - static async loadFromObjectPerProto( - object: RemoteObject, generatePreview: boolean, - nonIndexedPropertiesOnly: boolean = false): Promise { + static async loadFromObjectPerProto(object: RemoteObject, generatePreview: boolean, nonIndexedPropertiesOnly = false): + Promise { const result = await Promise.all([ object.getAllProperties(true /* accessorPropertiesOnly */, generatePreview, nonIndexedPropertiesOnly), object.getOwnProperties(generatePreview, nonIndexedPropertiesOnly), @@ -391,14 +390,13 @@ export class RemoteObjectImpl extends RemoteObject { return this.#classNameInternal; } - override getOwnProperties(generatePreview: boolean, nonIndexedPropertiesOnly: boolean = false): - Promise { + override getOwnProperties(generatePreview: boolean, nonIndexedPropertiesOnly = false): Promise { return this.doGetProperties(true, false, nonIndexedPropertiesOnly, generatePreview); } override getAllProperties( accessorPropertiesOnly: boolean, generatePreview: boolean, - nonIndexedPropertiesOnly: boolean = false): Promise { + nonIndexedPropertiesOnly = false): Promise { return this.doGetProperties(false, accessorPropertiesOnly, nonIndexedPropertiesOnly, generatePreview); } @@ -496,7 +494,7 @@ export class RemoteObjectImpl extends RemoteObject { void this.#runtimeAgent.invoke_releaseObject({objectId: response.result.objectId}); } - return resultPromise; + return await resultPromise; } async doSetObjectPropertyValue(result: Protocol.Runtime.RemoteObject, name: Protocol.Runtime.CallArgument): @@ -876,7 +874,7 @@ export class LocalJSONObject extends RemoteObject { return Boolean(Object.keys((this.valueInternal as Object)).length); } - override async getOwnProperties(_generatePreview: boolean, nonIndexedPropertiesOnly: boolean = false): + override async getOwnProperties(_generatePreview: boolean, nonIndexedPropertiesOnly = false): Promise { function isArrayIndex(name: string): boolean { const index = Number(name) >>> 0; @@ -892,7 +890,7 @@ export class LocalJSONObject extends RemoteObject { override async getAllProperties( accessorPropertiesOnly: boolean, generatePreview: boolean, - nonIndexedPropertiesOnly: boolean = false): Promise { + nonIndexedPropertiesOnly = false): Promise { if (accessorPropertiesOnly) { return {properties: [], internalProperties: null}; } diff --git a/front_end/core/sdk/Resource.ts b/front_end/core/sdk/Resource.ts index a73f0e8e4f..e7b89da226 100644 --- a/front_end/core/sdk/Resource.ts +++ b/front_end/core/sdk/Resource.ts @@ -173,7 +173,7 @@ export class Resource implements TextUtils.ContentProvider.ContentProvider { return this.#contentData; } if (this.#pendingContentData) { - return this.#pendingContentData; + return await this.#pendingContentData; } this.#pendingContentData = this.innerRequestContent().then(contentData => { // If an error happended we don't set `this.#contentData` so future `requestContentData` will @@ -184,7 +184,7 @@ export class Resource implements TextUtils.ContentProvider.ContentProvider { this.#pendingContentData = null; return contentData; }); - return this.#pendingContentData; + return await this.#pendingContentData; } canonicalMimeType(): string { @@ -197,7 +197,7 @@ export class Resource implements TextUtils.ContentProvider.ContentProvider { return []; } if (this.request) { - return this.request.searchInContent(query, caseSensitive, isRegex); + return await this.request.searchInContent(query, caseSensitive, isRegex); } const result = await this.#resourceTreeModel.target().pageAgent().invoke_searchInResource( {frameId: this.frameId, url: this.url, query, caseSensitive, isRegex}); @@ -215,7 +215,7 @@ export class Resource implements TextUtils.ContentProvider.ContentProvider { private async innerRequestContent(): Promise { if (this.request) { // The `contentData` promise only resolves once the request is done. - return this.request.requestContentData(); + return await this.request.requestContentData(); } const response = await this.#resourceTreeModel.target().pageAgent().invoke_getResourceContent( diff --git a/front_end/core/sdk/ResourceTreeModel.ts b/front_end/core/sdk/ResourceTreeModel.ts index 6a24d0b7da..8ae17abef9 100644 --- a/front_end/core/sdk/ResourceTreeModel.ts +++ b/front_end/core/sdk/ResourceTreeModel.ts @@ -93,7 +93,7 @@ export class ResourceTreeModel extends SDKModel { } async #buildResourceTree(): Promise { - return this.agent.invoke_getResourceTree().then(event => { + return await this.agent.invoke_getResourceTree().then(event => { this.processCachedResources(event.getError() ? null : event.frameTree); if (this.mainFrame) { this.processPendingEvents(this.mainFrame); @@ -475,7 +475,7 @@ export class ResourceTreeModel extends SDKModel { } async getAppId(): Promise { - return this.agent.invoke_getAppId(); + return await this.agent.invoke_getAppId(); } private executionContextComparator(a: ExecutionContext, b: ExecutionContext): number { @@ -580,7 +580,7 @@ export class ResourceTreeModel extends SDKModel { } async getMainStorageKey(): Promise { - return this.mainFrame ? this.mainFrame.getStorageKey(/* forceFetch */ false) : null; + return this.mainFrame ? await this.mainFrame.getStorageKey(/* forceFetch */ false) : null; } getMainSecurityOrigin(): string|null { @@ -998,16 +998,16 @@ export class ResourceTreeFrame { if (!parentFrame) { return null; } - return parentFrame.resourceTreeModel().domModel().getOwnerNodeForFrame(this.#idInternal); + return await parentFrame.resourceTreeModel().domModel().getOwnerNodeForFrame(this.#idInternal); } async getOwnerDOMNodeOrDocument(): Promise { const deferredNode = await this.getOwnerDeferredDOMNode(); if (deferredNode) { - return deferredNode.resolvePromise(); + return await deferredNode.resolvePromise(); } if (this.isOutermostFrame()) { - return this.resourceTreeModel().domModel().requestDocument(); + return await this.resourceTreeModel().domModel().requestDocument(); } return null; } @@ -1023,14 +1023,14 @@ export class ResourceTreeFrame { }; if (parentFrame) { - return highlightFrameOwner(parentFrame.resourceTreeModel().domModel()); + return await highlightFrameOwner(parentFrame.resourceTreeModel().domModel()); } // Fenced frames. if (parentTarget?.type() === Type.FRAME) { const domModel = parentTarget.model(DOMModel); if (domModel) { - return highlightFrameOwner(domModel); + return await highlightFrameOwner(domModel); } } diff --git a/front_end/core/sdk/RuntimeModel.ts b/front_end/core/sdk/RuntimeModel.ts index cb0da79957..e2dbf1e085 100644 --- a/front_end/core/sdk/RuntimeModel.ts +++ b/front_end/core/sdk/RuntimeModel.ts @@ -619,9 +619,9 @@ export class ExecutionContext { async evaluate(options: EvaluationOptions, userGesture: boolean, awaitPromise: boolean): Promise { // FIXME: It will be moved to separate ExecutionContext. if (this.debuggerModel.selectedCallFrame()) { - return this.debuggerModel.evaluateOnSelectedCallFrame(options); + return await this.debuggerModel.evaluateOnSelectedCallFrame(options); } - return this.evaluateGlobal(options, userGesture, awaitPromise); + return await this.evaluateGlobal(options, userGesture, awaitPromise); } globalObject(objectGroup: string, generatePreview: boolean): Promise { diff --git a/front_end/core/sdk/Script.test.ts b/front_end/core/sdk/Script.test.ts index a16f07e549..f7ab191e86 100644 --- a/front_end/core/sdk/Script.test.ts +++ b/front_end/core/sdk/Script.test.ts @@ -51,7 +51,7 @@ console.log("foo"); }); describe('editSource', () => { - function setupEditTest(scriptId: string, scriptSource: string = '') { + function setupEditTest(scriptId: string, scriptSource = '') { const target = createTarget(); const model = target.model(SDK.DebuggerModel.DebuggerModel) as SDK.DebuggerModel.DebuggerModel; dispatchEvent(target, 'Debugger.scriptParsed', { diff --git a/front_end/core/sdk/Script.ts b/front_end/core/sdk/Script.ts index 7633d0908d..fbd00d2b92 100644 --- a/front_end/core/sdk/Script.ts +++ b/front_end/core/sdk/Script.ts @@ -311,7 +311,7 @@ export class Script implements TextUtils.ContentProvider.ContentProvider, FrameA async getWasmBytecode(): Promise { const base64 = await this.debuggerModel.target().debuggerAgent().invoke_getWasmBytecode({scriptId: this.scriptId}); const response = await fetch(`data:application/wasm;base64,${base64.bytecode}`); - return response.arrayBuffer(); + return await response.arrayBuffer(); } originalContentProvider(): TextUtils.ContentProvider.ContentProvider { diff --git a/front_end/core/sdk/ServerSentEvents.ts b/front_end/core/sdk/ServerSentEvents.ts index a6be63aaf1..1183ca55f3 100644 --- a/front_end/core/sdk/ServerSentEvents.ts +++ b/front_end/core/sdk/ServerSentEvents.ts @@ -23,7 +23,7 @@ export class ServerSentEvents { // In the case where we parse the events ourselves we use the time of the last 'dataReceived' // event for all the events that come out of the corresponding chunk of data. - #lastDataReceivedTime: number = 0; + #lastDataReceivedTime = 0; readonly #eventSourceMessages: EventSourceMessage[] = []; diff --git a/front_end/core/sdk/StorageBucketsModel.ts b/front_end/core/sdk/StorageBucketsModel.ts index 1ada4ca6f0..d9743208c3 100644 --- a/front_end/core/sdk/StorageBucketsModel.ts +++ b/front_end/core/sdk/StorageBucketsModel.ts @@ -37,7 +37,7 @@ import {Events as StorageKeyManagerEvents, StorageKeyManager} from './StorageKey import {Capability, type Target} from './Target.js'; export class StorageBucketsModel extends SDKModel implements ProtocolProxyApi.StorageDispatcher { - private enabled: boolean = false; + private enabled = false; readonly storageAgent: ProtocolProxyApi.StorageApi; private readonly storageKeyManager: StorageKeyManager|null; private bucketsById = new Map(); diff --git a/front_end/core/sdk/StorageKeyManager.test.ts b/front_end/core/sdk/StorageKeyManager.test.ts index fe3a104263..97c844fadf 100644 --- a/front_end/core/sdk/StorageKeyManager.test.ts +++ b/front_end/core/sdk/StorageKeyManager.test.ts @@ -18,7 +18,7 @@ describeWithMockConnection('StorageKeyManager', () => { }); it('updates storage keys and emits events correctly', () => { - let eventFired: boolean = false; + let eventFired = false; const keys = ['storagekey1', 'storagekey2']; assert.isEmpty(manager.storageKeys()); diff --git a/front_end/core/sdk/Target.ts b/front_end/core/sdk/Target.ts index 34687cd9a0..a9fdacaa5b 100644 --- a/front_end/core/sdk/Target.ts +++ b/front_end/core/sdk/Target.ts @@ -32,7 +32,7 @@ export class Target extends ProtocolClient.InspectorBackend.TargetBase { * the page crashes, but a reload fixes it and the targets get restored (see * crbug.com/387258086). */ - #hasCrashed: boolean = false; + #hasCrashed = false; #targetInfoInternal: Protocol.Target.TargetInfo|undefined; #creatingModels?: boolean; diff --git a/front_end/entrypoints/device_mode_emulation_frame/device_mode_emulation_frame.ts b/front_end/entrypoints/device_mode_emulation_frame/device_mode_emulation_frame.ts index d3a20d2b51..7acb9f3054 100644 --- a/front_end/entrypoints/device_mode_emulation_frame/device_mode_emulation_frame.ts +++ b/front_end/entrypoints/device_mode_emulation_frame/device_mode_emulation_frame.ts @@ -6,7 +6,6 @@ import '../../core/dom_extension/dom_extension.js'; import '../../Images/Images.js'; if (window.opener) { - // @ts-ignore TypeScript doesn't know about `Emulation` on `Window`. const app = window.opener.Emulation.AdvancedApp.instance(); app.deviceModeEmulationFrameLoaded(document); } diff --git a/front_end/entrypoints/devtools_app/devtools_app.ts b/front_end/entrypoints/devtools_app/devtools_app.ts index f5f996a089..2644b17c03 100644 --- a/front_end/entrypoints/devtools_app/devtools_app.ts +++ b/front_end/entrypoints/devtools_app/devtools_app.ts @@ -31,6 +31,6 @@ import '../../panels/whats_new/whats_new-meta.js'; import * as Root from '../../core/root/root.js'; import * as Main from '../main/main.js'; -// @ts-ignore Exposed for legacy layout tests +// @ts-expect-error Exposed for legacy layout tests self.runtime = Root.Runtime.Runtime.instance({forceNew: true}); new Main.MainImpl.MainImpl(); diff --git a/front_end/entrypoints/formatter_worker/ESTreeWalker.ts b/front_end/entrypoints/formatter_worker/ESTreeWalker.ts index 3707d0f78c..9a4a6c705c 100644 --- a/front_end/entrypoints/formatter_worker/ESTreeWalker.ts +++ b/front_end/entrypoints/formatter_worker/ESTreeWalker.ts @@ -41,7 +41,7 @@ export class ESTreeWalker { this.#innerWalk(templateLiteral.quasis[expressionsLength], templateLiteral); } else { for (let i = 0; i < walkOrder.length; ++i) { - // @ts-ignore We are doing type traversal here, but the strings + // @ts-expect-error We are doing type traversal here, but the strings // in _walkOrder are not mapping. Preferably, we would use the // properties as defined in the types, but we can't do that yet. // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration diff --git a/front_end/entrypoints/formatter_worker/JavaScriptFormatter.ts b/front_end/entrypoints/formatter_worker/JavaScriptFormatter.ts index 5df8b31fba..b3ba39bc9c 100644 --- a/front_end/entrypoints/formatter_worker/JavaScriptFormatter.ts +++ b/front_end/entrypoints/formatter_worker/JavaScriptFormatter.ts @@ -63,7 +63,7 @@ export class JavaScriptFormatter { }); this.#tokenizer = new AcornTokenizer(this.#content, tokens); const walker = new ESTreeWalker(this.#beforeVisit.bind(this), this.#afterVisit.bind(this)); - // @ts-ignore Technically, the acorn Node type is a subclass of Acorn.ESTree.Node. + // @ts-expect-error Technically, the acorn Node type is a subclass of Acorn.ESTree.Node. // However, the acorn package currently exports its type without specifying // this relationship. So while this is allowed on runtime, we can't properly // typecheck it. @@ -104,7 +104,7 @@ export class JavaScriptFormatter { let token; while ((token = this.#tokenizer.peekToken()) && token.start < node.start) { const token = (this.#tokenizer.nextToken() as TokenOrComment); - // @ts-ignore Same reason as above about Acorn types and ESTree types + // @ts-expect-error Same reason as above about Acorn types and ESTree types const format = this.#formatToken(node.parent, token); this.#push(token, format); } @@ -256,7 +256,7 @@ export class JavaScriptFormatter { let allVariablesInitialized = true; const declarations = (node.declarations as Acorn.ESTree.Node[]); for (let i = 0; i < declarations.length; ++i) { - // @ts-ignore We are doing a subtype check, without properly checking whether + // @ts-expect-error We are doing a subtype check, without properly checking whether // it exists. We can't fix that, unless we use proper typechecking allVariablesInitialized = allVariablesInitialized && Boolean(declarations[i].init); } @@ -419,7 +419,7 @@ export class JavaScriptFormatter { } if (node.parent && node.parent.type === 'CatchClause') { const parentNode = (node.parent as Acorn.ESTree.CatchClause); - // @ts-ignore We are doing a subtype check, without properly checking whether + // @ts-expect-error We are doing a subtype check, without properly checking whether // it exists. We can't fix that, unless we use proper typechecking if (parentNode.parent && parentNode.parent.finalizer) { return 's'; diff --git a/front_end/entrypoints/formatter_worker/ScopeParser.ts b/front_end/entrypoints/formatter_worker/ScopeParser.ts index 7fec79fefb..367f22d563 100644 --- a/front_end/entrypoints/formatter_worker/ScopeParser.ts +++ b/front_end/entrypoints/formatter_worker/ScopeParser.ts @@ -436,7 +436,7 @@ export class ScopeVariableAnalysis { #addVariable( name: string, offset: number, definitionKind: DefinitionKind = DefinitionKind.NONE, - isShorthandAssignmentProperty: boolean = false): void { + isShorthandAssignmentProperty = false): void { this.#allNames.add(name); this.#currentScope.addVariable(name, offset, definitionKind, isShorthandAssignmentProperty); } diff --git a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshot.ts b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshot.ts index 9dda6c5d69..79a837af5f 100644 --- a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshot.ts +++ b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshot.ts @@ -1057,15 +1057,15 @@ export abstract class HeapSnapshot { if (!filter) { throw new Error('Unable to create filter'); } - // @ts-ignore key can be added as a static property + // @ts-expect-error key can be added as a static property filter.key = 'AllocationNodeId: ' + allocationNodeId; } else if (typeof minNodeId === 'number' && typeof maxNodeId === 'number') { filter = this.createNodeIdFilter(minNodeId, maxNodeId); - // @ts-ignore key can be added as a static property + // @ts-expect-error key can be added as a static property filter.key = 'NodeIdRange: ' + minNodeId + '..' + maxNodeId; } else if (filterName !== undefined) { filter = this.createNamedFilter(filterName); - // @ts-ignore key can be added as a static property + // @ts-expect-error key can be added as a static property filter.key = 'NamedFilter: ' + filterName; } return filter; @@ -1138,7 +1138,7 @@ export abstract class HeapSnapshot { aggregatesWithFilter(nodeFilter: HeapSnapshotModel.HeapSnapshotModel.NodeFilter): {[x: string]: HeapSnapshotModel.HeapSnapshotModel.Aggregate} { const filter = this.createFilter(nodeFilter); - // @ts-ignore key is added in createFilter + // @ts-expect-error key is added in createFilter const key = filter ? filter.key : 'allObjects'; return this.getAggregatesByClassKey(false, key, filter); } @@ -2860,7 +2860,7 @@ export class HeapSnapshotEdgesProvider extends HeapSnapshotItemProvider { function compareEdgeField(fieldName: string, ascending: boolean, indexA: number, indexB: number): number { edgeA.edgeIndex = indexA; edgeB.edgeIndex = indexB; - let result: number = 0; + let result = 0; if (fieldName === '!edgeName') { if (edgeB.name() === '__proto__') { return -1; @@ -3685,7 +3685,7 @@ export class JSHeapSnapshotEdge extends HeapSnapshotEdge { if (!this.isShortcut()) { return this.hasStringNameInternal(); } - // @ts-ignore parseInt is successful against numbers. + // @ts-expect-error parseInt is successful against numbers. return isNaN(parseInt(this.nameInternal(), 10)); } @@ -3718,7 +3718,7 @@ export class JSHeapSnapshotEdge extends HeapSnapshotEdge { if (!this.isShortcut()) { return String(name); } - // @ts-ignore parseInt is successful against numbers. + // @ts-expect-error parseInt is successful against numbers. const numName = parseInt(name, 10); return String(isNaN(numName) ? name : numName); } diff --git a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotLoader.ts b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotLoader.ts index 2daf9602cf..5bb9615077 100644 --- a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotLoader.ts +++ b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotLoader.ts @@ -44,7 +44,7 @@ export class HeapSnapshotLoader { #snapshot?: {[x: string]: any}; #array!: Platform.TypedArrayUtilities.BigUint32Array|null; #arrayIndex!: number; - #json: string = ''; + #json = ''; constructor(dispatcher: HeapSnapshotWorkerDispatcher) { this.#reset(); this.#progress = new HeapSnapshotProgress(dispatcher); diff --git a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.ts b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.ts index bfe06601df..849c619d53 100644 --- a/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.ts +++ b/front_end/entrypoints/heap_snapshot_worker/HeapSnapshotWorkerDispatcher.ts @@ -94,13 +94,13 @@ export class HeapSnapshotWorkerDispatcher { case 'evaluateForTest': { try { // Make 'HeapSnapshotWorker' and 'HeapSnapshotModel' available to web tests. 'eval' can't use 'import'. - // @ts-ignore + // @ts-expect-error globalThis.HeapSnapshotWorker = { AllocationProfile, HeapSnapshot, HeapSnapshotLoader, }; - // @ts-ignore + // @ts-expect-error globalThis.HeapSnapshotModel = HeapSnapshotModel; response.result = self.eval(data.source); } catch (error) { diff --git a/front_end/entrypoints/lighthouse_worker/LighthouseWorkerService.ts b/front_end/entrypoints/lighthouse_worker/LighthouseWorkerService.ts index 57363e8bff..f3956170a0 100644 --- a/front_end/entrypoints/lighthouse_worker/LighthouseWorkerService.ts +++ b/front_end/entrypoints/lighthouse_worker/LighthouseWorkerService.ts @@ -224,7 +224,6 @@ async function onFrontendMessage(event: MessageEvent): Promise { self.onmessage = onFrontendMessage; // Make lighthouse and traceviewer happy. -// @ts-ignore https://github.com/GoogleChrome/lighthouse/issues/11628 globalThis.global = self; // @ts-expect-error https://github.com/GoogleChrome/lighthouse/issues/11628 globalThis.global.isVinn = true; diff --git a/front_end/entrypoints/main/ExecutionContextSelector.test.ts b/front_end/entrypoints/main/ExecutionContextSelector.test.ts index 1e4a91e54b..81ebce8d8f 100644 --- a/front_end/entrypoints/main/ExecutionContextSelector.test.ts +++ b/front_end/entrypoints/main/ExecutionContextSelector.test.ts @@ -30,7 +30,7 @@ describeWithMockConnection('ExecutionContextSelector', () => { const contextSetFlavor = sinon.spy(UI.Context.Context.instance(), 'setFlavor'); - const sentExecutionContextCreated = (target: SDK.Target.Target, includeFrameId: boolean = true) => { + const sentExecutionContextCreated = (target: SDK.Target.Target, includeFrameId = true) => { const frameId = includeFrameId ? getMainFrame(target).id : undefined; const runtimeModel = target.model(SDK.RuntimeModel.RuntimeModel); diff --git a/front_end/entrypoints/main/MainImpl.ts b/front_end/entrypoints/main/MainImpl.ts index 297ddcf85f..1122bc10cd 100644 --- a/front_end/entrypoints/main/MainImpl.ts +++ b/front_end/entrypoints/main/MainImpl.ts @@ -184,17 +184,17 @@ export class MainImpl { } #initializeGlobalsForLayoutTests(): void { - // @ts-ignore e2e test global + // @ts-expect-error e2e test global self.Extensions ||= {}; - // @ts-ignore e2e test global + // @ts-expect-error e2e test global self.Host ||= {}; - // @ts-ignore e2e test global + // @ts-expect-error e2e test global self.Host.userMetrics ||= Host.userMetrics; - // @ts-ignore e2e test global + // @ts-expect-error e2e test global self.Host.UserMetrics ||= Host.UserMetrics; - // @ts-ignore e2e test global + // @ts-expect-error e2e test global self.ProtocolClient ||= {}; - // @ts-ignore e2e test global + // @ts-expect-error e2e test global self.ProtocolClient.test ||= ProtocolClient.InspectorBackend.test; } @@ -504,7 +504,7 @@ export class MainImpl { targetManager, debuggerWorkspaceBinding: Bindings.DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance(), }); - // @ts-ignore e2e test global + // @ts-expect-error e2e test global self.Extensions.extensionServer = Extensions.ExtensionServer.ExtensionServer.instance({forceNew: true}); new Persistence.FileSystemWorkspaceBinding.FileSystemWorkspaceBinding( @@ -676,7 +676,7 @@ export class MainImpl { const promises: Array> = Common.Runnable.lateInitializationRunnables().map(async lateInitializationLoader => { const runnable = await lateInitializationLoader(); - return runnable.run(); + return await runnable.run(); }); if (Root.Runtime.experiments.isEnabled('live-heap-profile')) { const PerfUI = await import('../../ui/legacy/components/perf_ui/perf_ui.js'); @@ -749,7 +749,7 @@ export class MainImpl { #redispatchClipboardEvent(event: Event): void { const eventCopy = new CustomEvent('clipboard-' + event.type, {bubbles: true}); - // @ts-ignore Used in ElementsTreeOutline + // @ts-expect-error Used in ElementsTreeOutline eventCopy['original'] = event; const document = event.target && (event.target as HTMLElement).ownerDocument; const target = document ? Platform.DOMUtilities.deepActiveElement(document) : null; @@ -784,9 +784,9 @@ export class MainImpl { static instanceForTest: MainImpl|null = null; } -// @ts-ignore Exported for Tests.js +// @ts-expect-error Exported for Tests.js globalThis.Main = globalThis.Main || {}; -// @ts-ignore Exported for Tests.js +// @ts-expect-error Exported for Tests.js globalThis.Main.Main = MainImpl; export class ZoomActionDelegate implements UI.ActionRegistration.ActionDelegate { diff --git a/front_end/entrypoints/node_app/node_app.ts b/front_end/entrypoints/node_app/node_app.ts index cec9239505..3873216a76 100644 --- a/front_end/entrypoints/node_app/node_app.ts +++ b/front_end/entrypoints/node_app/node_app.ts @@ -76,7 +76,7 @@ UI.ViewManager.registerViewExtension({ }, }); -// @ts-ignore Exposed for legacy layout tests +// @ts-expect-error Exposed for legacy layout tests self.runtime = Root.Runtime.Runtime.instance({forceNew: true}); Common.Runnable.registerEarlyInitializationRunnable(NodeMainImpl.instance); new Main.MainImpl.MainImpl(); diff --git a/front_end/entrypoints/worker_app/worker_app.ts b/front_end/entrypoints/worker_app/worker_app.ts index 4004b5dc05..ab9c9f0cbb 100644 --- a/front_end/entrypoints/worker_app/worker_app.ts +++ b/front_end/entrypoints/worker_app/worker_app.ts @@ -15,6 +15,6 @@ import './WorkerMain.js'; import * as Root from '../../core/root/root.js'; import * as Main from '../main/main.js'; -// @ts-ignore Exposed for legacy layout tests +// @ts-expect-error Exposed for legacy layout tests self.runtime = Root.Runtime.Runtime.instance({forceNew: true}); new Main.MainImpl.MainImpl(); diff --git a/front_end/generated/InspectorBackendCommands.js b/front_end/generated/InspectorBackendCommands.js index dd9ae5ca02..3ab5ac84aa 100644 --- a/front_end/generated/InspectorBackendCommands.js +++ b/front_end/generated/InspectorBackendCommands.js @@ -31,7 +31,7 @@ * ): void, * }} */ -// @ts-ignore typedef +// @ts-expect-error typedef export let InspectorBackendAPI; /** diff --git a/front_end/legacy_test_runner/legacy_test_runner.ts b/front_end/legacy_test_runner/legacy_test_runner.ts index b805546c3c..ebeec75533 100644 --- a/front_end/legacy_test_runner/legacy_test_runner.ts +++ b/front_end/legacy_test_runner/legacy_test_runner.ts @@ -5,10 +5,10 @@ import '../entrypoints/devtools_app/devtools_app.js'; import './test_runner/test_runner.js'; -// @ts-ignore +// @ts-expect-error if (self.testRunner) { - // @ts-ignore + // @ts-expect-error testRunner.dumpAsText(); - // @ts-ignore + // @ts-expect-error testRunner.waitUntilDone(); } diff --git a/front_end/models/autofill_manager/AutofillManager.ts b/front_end/models/autofill_manager/AutofillManager.ts index 8bd4554590..e4fb29431f 100644 --- a/front_end/models/autofill_manager/AutofillManager.ts +++ b/front_end/models/autofill_manager/AutofillManager.ts @@ -14,7 +14,7 @@ let autofillManagerInstance: AutofillManager; export class AutofillManager extends Common.ObjectWrapper.ObjectWrapper { #autoOpenViewSetting: Common.Settings.Setting; - #address: string = ''; + #address = ''; #filledFields: Protocol.Autofill.FilledField[] = []; #matches: Match[] = []; #autofillModel: SDK.AutofillModel.AutofillModel|null = null; diff --git a/front_end/models/bindings/DebuggerLanguagePlugins.ts b/front_end/models/bindings/DebuggerLanguagePlugins.ts index 72f1cc85c5..412bfabf78 100644 --- a/front_end/models/bindings/DebuggerLanguagePlugins.ts +++ b/front_end/models/bindings/DebuggerLanguagePlugins.ts @@ -990,7 +990,7 @@ export class DebuggerLanguagePluginManager implements try { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) - // @ts-ignore + // @ts-expect-error const locations = await plugin.getInlinedFunctionRanges(pluginLocation); return locations.map( m => ({ @@ -1027,7 +1027,7 @@ export class DebuggerLanguagePluginManager implements try { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) - // @ts-ignore + // @ts-expect-error const locations = await plugin.getInlinedCalleesRanges(pluginLocation); return locations.map( m => ({ diff --git a/front_end/models/bindings/DebuggerWorkspaceBinding.ts b/front_end/models/bindings/DebuggerWorkspaceBinding.ts index aa4c1ff539..b18c299213 100644 --- a/front_end/models/bindings/DebuggerWorkspaceBinding.ts +++ b/front_end/models/bindings/DebuggerWorkspaceBinding.ts @@ -186,7 +186,7 @@ export class DebuggerWorkspaceBinding implements SDK.TargetManager.SDKModelObser } const liveLocationPromise = modelData.createLiveLocation(rawLocation, updateDelegate, locationPool); this.recordLiveLocationChange(liveLocationPromise); - return liveLocationPromise; + return await liveLocationPromise; } async createStackTraceTopFrameLiveLocation( @@ -196,7 +196,7 @@ export class DebuggerWorkspaceBinding implements SDK.TargetManager.SDKModelObser const locationPromise = StackTraceTopFrameLocation.createStackTraceTopFrameLocation(rawLocations, this, updateDelegate, locationPool); this.recordLiveLocationChange(locationPromise); - return locationPromise; + return await locationPromise; } async createCallFrameLiveLocation( @@ -247,14 +247,14 @@ export class DebuggerWorkspaceBinding implements SDK.TargetManager.SDKModelObser debuggerModel: SDK.DebuggerModel.DebuggerModel, url: Platform.DevToolsPath.UrlString, isContentScript: boolean): Promise { const uiSourceCode = this.uiSourceCodeForSourceMapSourceURL(debuggerModel, url, isContentScript); - return uiSourceCode || this.waitForUISourceCodeAdded(url, debuggerModel.target()); + return await (uiSourceCode || this.waitForUISourceCodeAdded(url, debuggerModel.target())); } async uiSourceCodeForDebuggerLanguagePluginSourceURLPromise( debuggerModel: SDK.DebuggerModel.DebuggerModel, url: Platform.DevToolsPath.UrlString): Promise { const uiSourceCode = this.pluginManager.uiSourceCodeForURL(debuggerModel, url); - return uiSourceCode || this.waitForUISourceCodeAdded(url, debuggerModel.target()); + return await (uiSourceCode || this.waitForUISourceCodeAdded(url, debuggerModel.target())); } uiSourceCodeForScript(script: SDK.Script.Script): Workspace.UISourceCode.UISourceCode|null { @@ -593,7 +593,7 @@ export class Location extends LiveLocationWithPool { override async uiLocation(): Promise { const debuggerModelLocation = this.rawLocation; - return this.#binding.rawLocationToUILocation(debuggerModelLocation); + return await this.#binding.rawLocationToUILocation(debuggerModelLocation); } override dispose(): void { @@ -634,11 +634,11 @@ class StackTraceTopFrameLocation extends LiveLocationWithPool { } override async uiLocation(): Promise { - return this.#current ? this.#current.uiLocation() : null; + return this.#current ? await this.#current.uiLocation() : null; } override async isIgnoreListed(): Promise { - return this.#current ? this.#current.isIgnoreListed() : false; + return this.#current ? await this.#current.isIgnoreListed() : false; } override dispose(): void { diff --git a/front_end/models/bindings/FileUtils.ts b/front_end/models/bindings/FileUtils.ts index 7903ec2607..a6a55b5ff6 100644 --- a/front_end/models/bindings/FileUtils.ts +++ b/front_end/models/bindings/FileUtils.ts @@ -98,7 +98,7 @@ export class ChunkedFileReader implements ChunkedReader { this.#output = output; void this.loadChunk(); - return new Promise(resolve => { + return await new Promise(resolve => { this.#transferFinished = resolve; }); } @@ -192,7 +192,7 @@ export class ChunkedFileReader implements ChunkedReader { if (done || !value) { // Write empty string to inform of file end await this.#output.write('', true); - return this.finishRead(); + return await this.finishRead(); } void this.decodeChunkBuffer(value.buffer, false); } diff --git a/front_end/models/bindings/TempFile.ts b/front_end/models/bindings/TempFile.ts index f2ab0bc473..01993d50cb 100644 --- a/front_end/models/bindings/TempFile.ts +++ b/front_end/models/bindings/TempFile.ts @@ -84,7 +84,7 @@ export class TempFile { return null; } const reader = new ChunkedFileReader((this.#lastBlob as File), 10 * 1000 * 1000, progress); - return reader.read(outputStream).then(success => success ? null : reader.error()); + return await reader.read(outputStream).then(success => success ? null : reader.error()); } remove(): void { diff --git a/front_end/models/breakpoints/BreakpointManager.ts b/front_end/models/breakpoints/BreakpointManager.ts index ba57cd6130..a9034e4222 100644 --- a/front_end/models/breakpoints/BreakpointManager.ts +++ b/front_end/models/breakpoints/BreakpointManager.ts @@ -612,7 +612,7 @@ export class Breakpoint implements SDK.TargetManager.SDKModelObserver { await modelBreakpoint.resetBreakpoint(); - return this.#updateModel(modelBreakpoint); + return await this.#updateModel(modelBreakpoint); })); } } @@ -847,7 +847,7 @@ export class Breakpoint implements SDK.TargetManager.SDKModelObserver { diff --git a/front_end/models/cpu_profile/CPUProfileDataModel.ts b/front_end/models/cpu_profile/CPUProfileDataModel.ts index 169ceb9ba1..d67cd4091b 100644 --- a/front_end/models/cpu_profile/CPUProfileDataModel.ts +++ b/front_end/models/cpu_profile/CPUProfileDataModel.ts @@ -72,13 +72,13 @@ export class CPUProfileDataModel extends ProfileTreeModel { #stackChildrenDuration?: number[]; constructor(profile: ExtendedProfile) { super(); - // @ts-ignore Legacy types + // @ts-expect-error Legacy types const isLegacyFormat = Boolean(profile['head']); if (isLegacyFormat) { // Legacy format contains raw timestamps and start/stop times are in seconds. this.profileStartTime = profile.startTime * 1000; this.profileEndTime = profile.endTime * 1000; - // @ts-ignore Legacy types + // @ts-expect-error Legacy types this.timestamps = profile.timestamps; this.compatibilityConversionHeadToNodes(profile); } else { @@ -110,19 +110,19 @@ export class CPUProfileDataModel extends ProfileTreeModel { } private compatibilityConversionHeadToNodes(profile: Protocol.Profiler.Profile): void { - // @ts-ignore Legacy types + // @ts-expect-error Legacy types if (!profile.head || profile.nodes) { return; } const nodes: Protocol.Profiler.ProfileNode[] = []; - // @ts-ignore Legacy types + // @ts-expect-error Legacy types convertNodesTree(profile.head); profile.nodes = nodes; - // @ts-ignore Legacy types + // @ts-expect-error Legacy types delete profile.head; function convertNodesTree(node: Protocol.Profiler.ProfileNode): number { nodes.push(node); - // @ts-ignore Legacy types + // @ts-expect-error Legacy types node.children = (node.children as Protocol.Profiler.ProfileNode[]).map(convertNodesTree); return node.id; } @@ -163,7 +163,7 @@ export class CPUProfileDataModel extends ProfileTreeModel { nodes[0].children = []; for (let i = 1; i < nodes.length; ++i) { const node = nodes[i]; - // @ts-ignore Legacy types + // @ts-expect-error Legacy types const parentNode = protocolNodeById.get(node.parent); if (!parentNode) { continue; diff --git a/front_end/models/crux-manager/CrUXManager.ts b/front_end/models/crux-manager/CrUXManager.ts index 0ecf596b63..cc16d6d02a 100644 --- a/front_end/models/crux-manager/CrUXManager.ts +++ b/front_end/models/crux-manager/CrUXManager.ts @@ -233,7 +233,7 @@ export class CrUXManager extends Common.ObjectWrapper.ObjectWrapper } async getFieldDataForCurrentPageForTesting(): Promise { - return this.#getFieldDataForCurrentPage(); + return await this.#getFieldDataForCurrentPage(); } /** diff --git a/front_end/models/emulation/DeviceModeModel.ts b/front_end/models/emulation/DeviceModeModel.ts index bde74580b2..bf24e1ef9d 100644 --- a/front_end/models/emulation/DeviceModeModel.ts +++ b/front_end/models/emulation/DeviceModeModel.ts @@ -782,7 +782,7 @@ export class DeviceModeModel extends Common.ObjectWrapper.ObjectWrapper { switch (request.method) { case PrivateAPI.RecorderExtensionPluginCommands.Stringify: - return (plugin as PublicAPI.Chrome.DevTools.RecorderExtensionExportPlugin) + return await (plugin as PublicAPI.Chrome.DevTools.RecorderExtensionExportPlugin) .stringify(request.parameters.recording); case PrivateAPI.RecorderExtensionPluginCommands.StringifyStep: - return (plugin as PublicAPI.Chrome.DevTools.RecorderExtensionExportPlugin) + return await (plugin as PublicAPI.Chrome.DevTools.RecorderExtensionExportPlugin) .stringifyStep(request.parameters.step); case PrivateAPI.RecorderExtensionPluginCommands.Replay: try { @@ -1006,18 +1006,18 @@ self.injectedExtensionAPI = function( }, getWasmLocal: async function( this: APIImpl.LanguageExtensions, local: number, stopId: number): Promise { - return new Promise( + return await new Promise( resolve => extensionServer.sendRequest({command: PrivateAPI.Commands.GetWasmLocal, local, stopId}, resolve)); }, getWasmGlobal: async function(this: APIImpl.LanguageExtensions, global: number, stopId: number): Promise { - return new Promise( + return await new Promise( resolve => extensionServer.sendRequest({command: PrivateAPI.Commands.GetWasmGlobal, global, stopId}, resolve)); }, getWasmOp: async function(this: APIImpl.LanguageExtensions, op: number, stopId: number): Promise { - return new Promise( + return await new Promise( resolve => extensionServer.sendRequest({command: PrivateAPI.Commands.GetWasmOp, op, stopId}, resolve)); }, diff --git a/front_end/models/extensions/ExtensionEndpoint.ts b/front_end/models/extensions/ExtensionEndpoint.ts index 8cd071db7b..9c220fe8e1 100644 --- a/front_end/models/extensions/ExtensionEndpoint.ts +++ b/front_end/models/extensions/ExtensionEndpoint.ts @@ -16,7 +16,7 @@ type Message = MessageEvent; export class ExtensionEndpoint { private readonly port: MessagePort; - private nextRequestId: number = 0; + private nextRequestId = 0; private pendingRequests: Map void, reject: (error: Error) => void, diff --git a/front_end/models/extensions/ExtensionServer.ts b/front_end/models/extensions/ExtensionServer.ts index 76a70fa0fb..fb9a2326eb 100644 --- a/front_end/models/extensions/ExtensionServer.ts +++ b/front_end/models/extensions/ExtensionServer.ts @@ -919,7 +919,7 @@ export class ExtensionServer extends Common.ObjectWrapper.ObjectWrapper this.extensionAllowedOnURL(r.url(), port)); const harLog = await HAR.Log.Log.build(requests, {sanitize: false}); for (let i = 0; i < harLog.entries.length; ++i) { - // @ts-ignore + // @ts-expect-error harLog.entries[i]._requestId = this.requestId(requests[i]); } return harLog; @@ -1092,7 +1092,7 @@ export class ExtensionServer extends Common.ObjectWrapper.ObjectWrapper { - return this.endpoint.sendRequest( + return await this.endpoint.sendRequest( PrivateAPI.LanguageExtensionPluginCommands.GetMappedLines, {rawModuleId, sourceFileURL}); } async evaluate(expression: string, context: Chrome.DevTools.RawLocation, stopId: number): Promise { - return this.endpoint.sendRequest( + return await this.endpoint.sendRequest( PrivateAPI.LanguageExtensionPluginCommands.FormatValue, {expression, context, stopId}); } diff --git a/front_end/models/formatter/ScriptFormatter.ts b/front_end/models/formatter/ScriptFormatter.ts index 8694005b03..832c063f7b 100644 --- a/front_end/models/formatter/ScriptFormatter.ts +++ b/front_end/models/formatter/ScriptFormatter.ts @@ -61,7 +61,7 @@ export async function format( indent: string = Common.Settings.Settings.instance().moduleSetting('text-editor-indent').get()): Promise { if (contentType.isDocumentOrScriptOrStyleSheet()) { - return formatScriptContent(mimeType, content, indent); + return await formatScriptContent(mimeType, content, indent); } return {formattedContent: content, formattedMapping: new IdentityFormatterSourceMapping()}; diff --git a/front_end/models/har/HARFormat.ts b/front_end/models/har/HARFormat.ts index 57a59d2abb..d6a5b97bb4 100644 --- a/front_end/models/har/HARFormat.ts +++ b/front_end/models/har/HARFormat.ts @@ -444,9 +444,9 @@ export class HARStack extends HARBase { export class HARCallFrame extends HARBase { functionName: string; scriptId: Protocol.Runtime.ScriptId; - url: string = ''; - lineNumber: number = -1; - columnNumber: number = -1; + url = ''; + lineNumber = -1; + columnNumber = -1; /** * Based on Protocol.Runtime.CallFrame defined in browser_protocol.pdl */ diff --git a/front_end/models/issues_manager/IssuesManager.ts b/front_end/models/issues_manager/IssuesManager.ts index e2cfff9133..5503165707 100644 --- a/front_end/models/issues_manager/IssuesManager.ts +++ b/front_end/models/issues_manager/IssuesManager.ts @@ -197,7 +197,7 @@ export class IssuesManager extends Common.ObjectWrapper.ObjectWrapper(); #issuesById = new Map(); #issuesByOutermostTarget: WeakMap> = new Map(); - #thirdPartyCookiePhaseoutIssueMessageSent: boolean = false; + #thirdPartyCookiePhaseoutIssueMessageSent = false; constructor( private readonly showThirdPartyIssuesSetting?: Common.Settings.Setting, @@ -464,7 +464,7 @@ export interface EventTypes { [Events.ISSUE_ADDED]: IssueAddedEvent; } -// @ts-ignore +// @ts-expect-error globalThis.addIssueForTest = (issue: Protocol.Audits.InspectorIssue) => { const mainTarget = SDK.TargetManager.TargetManager.instance().primaryPageTarget(); const issuesModel = mainTarget?.model(SDK.IssuesModel.IssuesModel); diff --git a/front_end/models/issues_manager/MarkdownIssueDescription.ts b/front_end/models/issues_manager/MarkdownIssueDescription.ts index 2c616bd834..06e8e5f075 100644 --- a/front_end/models/issues_manager/MarkdownIssueDescription.ts +++ b/front_end/models/issues_manager/MarkdownIssueDescription.ts @@ -58,7 +58,7 @@ export interface IssueDescription { export async function getFileContent(url: URL): Promise { try { const response = await fetch(url.toString()); - return response.text(); + return await response.text(); } catch { throw new Error( `Markdown file ${url.toString()} not found. Make sure it is correctly listed in the relevant BUILD.gn files.`); @@ -66,7 +66,7 @@ export async function getFileContent(url: URL): Promise { } export async function getMarkdownFileContent(filename: string): Promise { - return getFileContent(new URL(`descriptions/${filename}`, import.meta.url)); + return await getFileContent(new URL(`descriptions/${filename}`, import.meta.url)); } export async function createIssueDescriptionFromMarkdown(description: MarkdownIssueDescription): diff --git a/front_end/models/issues_manager/RelatedIssue.ts b/front_end/models/issues_manager/RelatedIssue.ts index 5cf9234e35..9b4f9fb2fd 100644 --- a/front_end/models/issues_manager/RelatedIssue.ts +++ b/front_end/models/issues_manager/RelatedIssue.ts @@ -73,12 +73,12 @@ export async function reveal(obj: IssuesAssociatable, category?: IssueCategory): if (typeof obj === 'string') { const issue = IssuesManager.instance().getIssueById(obj); if (issue) { - return Common.Revealer.reveal(issue); + return await Common.Revealer.reveal(issue); } } const issues = Array.from(IssuesManager.instance().issues()); const candidates = issuesAssociatedWith(issues, obj).filter(issue => !category || issue.getCategory() === category); if (candidates.length > 0) { - return Common.Revealer.reveal(candidates[0]); + return await Common.Revealer.reveal(candidates[0]); } } diff --git a/front_end/models/live-metrics/LiveMetrics.ts b/front_end/models/live-metrics/LiveMetrics.ts index 43d7241424..de54416836 100644 --- a/front_end/models/live-metrics/LiveMetrics.ts +++ b/front_end/models/live-metrics/LiveMetrics.ts @@ -389,7 +389,7 @@ export class LiveMetrics extends Common.ObjectWrapper.ObjectWrapper } const frameManager = SDK.FrameManager.FrameManager.instance(); - return frameManager.getOrWaitForFrame(frameId); + return await frameManager.getOrWaitForFrame(frameId); } async #onBindingCalled(event: {data: Protocol.Runtime.BindingCalledEvent}): Promise { diff --git a/front_end/models/persistence/IsolatedFileSystem.ts b/front_end/models/persistence/IsolatedFileSystem.ts index 9c269dabc1..9dcb27fa0f 100644 --- a/front_end/models/persistence/IsolatedFileSystem.ts +++ b/front_end/models/persistence/IsolatedFileSystem.ts @@ -95,7 +95,7 @@ export class IsolatedFileSystem extends PlatformFileSystem { } const fileSystem = new IsolatedFileSystem(manager, path, embedderPath, domFileSystem, type); - return fileSystem.initializeFilePaths().then(() => fileSystem).catch(error => { + return await fileSystem.initializeFilePaths().then(() => fileSystem).catch(error => { console.error(error); return null; }); @@ -381,7 +381,7 @@ export class IsolatedFileSystem extends PlatformFileSystem { } function errorHandler(this: IsolatedFileSystem, error: DOMError|ProgressEvent): void { - // @ts-ignore TODO(crbug.com/1172300) Properly type this after jsdoc to ts migration + // @ts-expect-error TODO(crbug.com/1172300) Properly type this after jsdoc to ts migration const errorMessage = IsolatedFileSystem.errorMessage(error); console.error(errorMessage + ' when setting content for file \'' + (this.path() + '/' + path) + '\''); resolve(undefined); diff --git a/front_end/models/persistence/NetworkPersistenceManager.ts b/front_end/models/persistence/NetworkPersistenceManager.ts index 985be1ef05..9baf712a89 100644 --- a/front_end/models/persistence/NetworkPersistenceManager.ts +++ b/front_end/models/persistence/NetworkPersistenceManager.ts @@ -700,7 +700,7 @@ export class NetworkPersistenceManager extends Common.ObjectWrapper.ObjectWrappe async #innerUpdateInterceptionPatterns(): Promise { this.#headerOverridesMap.clear(); if (!this.activeInternal || !this.projectInternal) { - return SDK.NetworkManager.MultitargetNetworkManager.instance().setInterceptionHandlerForPatterns( + return await SDK.NetworkManager.MultitargetNetworkManager.instance().setInterceptionHandlerForPatterns( [], this.interceptionHandlerBound); } let patterns = new Set(); @@ -730,7 +730,7 @@ export class NetworkPersistenceManager extends Common.ObjectWrapper.ObjectWrappe } } - return SDK.NetworkManager.MultitargetNetworkManager.instance().setInterceptionHandlerForPatterns( + return await SDK.NetworkManager.MultitargetNetworkManager.instance().setInterceptionHandlerForPatterns( Array.from(patterns).map( pattern => ({urlPattern: pattern, requestStage: Protocol.Fetch.RequestStage.Response})), this.interceptionHandlerBound); diff --git a/front_end/models/persistence/PersistenceImpl.ts b/front_end/models/persistence/PersistenceImpl.ts index 9b386fc2ae..faa857dddf 100644 --- a/front_end/models/persistence/PersistenceImpl.ts +++ b/front_end/models/persistence/PersistenceImpl.ts @@ -267,7 +267,7 @@ export class PersistenceImpl extends Common.ObjectWrapper.ObjectWrapper breakpointLocation.breakpoint); await Promise.all(breakpoints.map(async breakpoint => { await breakpoint.remove(false /* keepInStorage */); - return this.breakpointManager.setBreakpoint( + return await this.breakpointManager.setBreakpoint( to, breakpoint.lineNumber(), breakpoint.columnNumber(), breakpoint.condition(), breakpoint.enabled(), breakpoint.isLogpoint(), BreakpointManager.BreakpointManager.BreakpointOrigin.OTHER); })); diff --git a/front_end/models/persistence/PlatformFileSystem.ts b/front_end/models/persistence/PlatformFileSystem.ts index 937f8581c9..a0116756b5 100644 --- a/front_end/models/persistence/PlatformFileSystem.ts +++ b/front_end/models/persistence/PlatformFileSystem.ts @@ -50,7 +50,7 @@ export class PlatformFileSystem { async createFile(_path: Platform.DevToolsPath.EncodedPathString, _name: Platform.DevToolsPath.RawPathString|null): Promise { - return Promise.resolve(null); + return await Promise.resolve(null); } deleteFile(_path: Platform.DevToolsPath.EncodedPathString): Promise { diff --git a/front_end/models/source_map_scopes/NamesResolver.ts b/front_end/models/source_map_scopes/NamesResolver.ts index 9bd1731ea0..cd22c7c554 100644 --- a/front_end/models/source_map_scopes/NamesResolver.ts +++ b/front_end/models/source_map_scopes/NamesResolver.ts @@ -208,7 +208,7 @@ const resolveDebuggerScope = async(scope: SDK.DebuggerModel.ScopeChainEntry): } const script = scope.callFrame().script; const scopeChain = await findScopeChainForDebuggerScope(scope); - return resolveScope(script, scopeChain); + return await resolveScope(script, scopeChain); }; const resolveScope = async(script: SDK.Script.Script, scopeChain: Formatter.FormatterWorkerPool.ScopeTreeNode[]): @@ -727,11 +727,11 @@ export class RemoteObject extends SDK.RemoteObject.RemoteObject { break; } } - return this.object.setPropertyValue(actualName, value); + return await this.object.setPropertyValue(actualName, value); } override async deleteProperty(name: Protocol.Runtime.CallArgument): Promise { - return this.object.deleteProperty(name); + return await this.object.deleteProperty(name); } override callFunction( diff --git a/front_end/models/source_map_scopes/ScopeChainModel.test.ts b/front_end/models/source_map_scopes/ScopeChainModel.test.ts index dfffe4fa9a..59612fefe1 100644 --- a/front_end/models/source_map_scopes/ScopeChainModel.test.ts +++ b/front_end/models/source_map_scopes/ScopeChainModel.test.ts @@ -41,7 +41,7 @@ describeWithMockConnection('ScopeChainModel', () => { const debuggerModel = target.model(SDK.DebuggerModel.DebuggerModel)!; const fakeFrame = sinon.createStubInstance(SDK.DebuggerModel.CallFrame); fakeFrame.debuggerModel = debuggerModel; - // @ts-ignore readonly for test. + // @ts-expect-error readonly for test. fakeFrame.script = sinon.createStubInstance(SDK.Script.Script, {isWasm: false}); fakeFrame.scopeChain.returns([]); @@ -63,7 +63,7 @@ describeWithMockConnection('ScopeChainModel', () => { const debuggerModel = target.model(SDK.DebuggerModel.DebuggerModel)!; const fakeFrame = sinon.createStubInstance(SDK.DebuggerModel.CallFrame); fakeFrame.debuggerModel = debuggerModel; - // @ts-ignore readonly for test. + // @ts-expect-error readonly for test. fakeFrame.script = sinon.createStubInstance(SDK.Script.Script, {isWasm: false}); fakeFrame.scopeChain.returns([]); diff --git a/front_end/models/text_utils/ContentProvider.ts b/front_end/models/text_utils/ContentProvider.ts index c92e53f52e..d13bbacb07 100644 --- a/front_end/models/text_utils/ContentProvider.ts +++ b/front_end/models/text_utils/ContentProvider.ts @@ -57,7 +57,7 @@ export class SearchMatch { export const contentAsDataURL = function( content: string|null, mimeType: string, contentEncoded: boolean, charset?: string|null, - limitSize: boolean = true): string|null { + limitSize = true): string|null { const maxDataUrlSize = 1024 * 1024; if (content === undefined || content === null || (limitSize && content.length > maxDataUrlSize)) { return null; diff --git a/front_end/models/text_utils/TextCursor.ts b/front_end/models/text_utils/TextCursor.ts index b66c8adcbb..43af28ac9a 100644 --- a/front_end/models/text_utils/TextCursor.ts +++ b/front_end/models/text_utils/TextCursor.ts @@ -7,9 +7,9 @@ import * as Platform from '../../core/platform/platform.js'; export class TextCursor { readonly #lineEndings: number[]; - #offset: number = 0; - #lineNumber: number = 0; - #columnNumber: number = 0; + #offset = 0; + #lineNumber = 0; + #columnNumber = 0; constructor(lineEndings: number[]) { this.#lineEndings = lineEndings; diff --git a/front_end/models/trace/extras/FetchNodes.ts b/front_end/models/trace/extras/FetchNodes.ts index 59730bf38b..f238ef0896 100644 --- a/front_end/models/trace/extras/FetchNodes.ts +++ b/front_end/models/trace/extras/FetchNodes.ts @@ -112,7 +112,7 @@ export async function extractRelatedDOMNodesFromEvent(modelData: Handlers.Types. Promise|null> { const nodeIds = nodeIdsForEvent(modelData, event); if (nodeIds.size) { - return domNodesForMultipleBackendNodeIds(modelData, Array.from(nodeIds)); + return await domNodesForMultipleBackendNodeIds(modelData, Array.from(nodeIds)); } return null; } diff --git a/front_end/models/trace/extras/StackTraceForEvent.test.ts b/front_end/models/trace/extras/StackTraceForEvent.test.ts index 68efc3ab1e..a18004b9ae 100644 --- a/front_end/models/trace/extras/StackTraceForEvent.test.ts +++ b/front_end/models/trace/extras/StackTraceForEvent.test.ts @@ -12,7 +12,7 @@ function shapeStackTraceAsArray(stackTrace: Protocol.Runtime.StackTrace): const stackTraceAsArray: Array<{callFrames: Protocol.Runtime.CallFrame[], description?: string}> = []; let currentStackTrace: Protocol.Runtime.StackTrace|undefined = stackTrace; while (currentStackTrace) { - // @ts-ignore `codeType` is not included in the protocol types but + // @ts-expect-error `codeType` is not included in the protocol types but // occasionally present currentStackTrace.callFrames.forEach(callFrame => delete callFrame.codeType); stackTraceAsArray.push({callFrames: currentStackTrace.callFrames, description: currentStackTrace.description}); diff --git a/front_end/models/trace/handlers/ExtensionTraceDataHandler.test.ts b/front_end/models/trace/handlers/ExtensionTraceDataHandler.test.ts index 088c46db1a..9d7b322193 100644 --- a/front_end/models/trace/handlers/ExtensionTraceDataHandler.test.ts +++ b/front_end/models/trace/handlers/ExtensionTraceDataHandler.test.ts @@ -82,13 +82,13 @@ export async function createTraceExtensionDataFromPerformanceAPITestInput( extensionData: PerformanceAPIExtensionTestData[]): Promise { const events = extensionData.flatMap(makeTimingEventWithPerformanceExtensionData).sort((e1, e2) => e1.ts - e2.ts); - return createTraceExtensionDataFromEvents(events); + return await createTraceExtensionDataFromEvents(events); } async function createTraceExtensionDataFromConsoleAPITestInput(extensionData: ConsoleAPIExtensionTestData[]): Promise { const events = extensionData.flatMap(makeTimingEventWithConsoleExtensionData).sort((e1, e2) => e1.ts - e2.ts); - return createTraceExtensionDataFromEvents(events); + return await createTraceExtensionDataFromEvents(events); } async function createTraceExtensionDataFromEvents(events: Trace.Types.Events.Event[]): diff --git a/front_end/models/trace/handlers/FramesHandler.ts b/front_end/models/trace/handlers/FramesHandler.ts index 66d07a520d..1db66f8d21 100644 --- a/front_end/models/trace/handlers/FramesHandler.ts +++ b/front_end/models/trace/handlers/FramesHandler.ts @@ -391,7 +391,7 @@ class TimelineFrame implements Types.Events.LegacyTimelineFrame { pid = Types.Events.ProcessID(-1); tid = Types.Events.ThreadID(-1); - index: number = -1; + index = -1; startTime: Types.Timing.Micro; startTimeOffset: Types.Timing.Micro; endTime: Types.Timing.Micro; diff --git a/front_end/models/trace/handlers/LayoutShiftsHandler.ts b/front_end/models/trace/handlers/LayoutShiftsHandler.ts index fb1dd0a74a..1a6e5bade7 100644 --- a/front_end/models/trace/handlers/LayoutShiftsHandler.ts +++ b/front_end/models/trace/handlers/LayoutShiftsHandler.ts @@ -417,7 +417,7 @@ async function buildLayoutShiftsClusters(): Promise { updateTraceWindowMax(cluster.clusterWindow, Types.Timing.Micro(clusterEnd)); } - let largestScore: number = 0; + let largestScore = 0; let worstShiftEvent: Types.Events.Event|null = null; for (const shift of cluster.events) { diff --git a/front_end/models/trace/handlers/MetaHandler.ts b/front_end/models/trace/handlers/MetaHandler.ts index a94b81ea63..d33d149e3b 100644 --- a/front_end/models/trace/handlers/MetaHandler.ts +++ b/front_end/models/trace/handlers/MetaHandler.ts @@ -11,8 +11,8 @@ const rendererProcessesByFrameId: FrameProcessData = new Map(); // We will often want to key data by Frame IDs, and commonly we'll care most // about the main frame's ID, so we store and expose that. -let mainFrameId: string = ''; -let mainFrameURL: string = ''; +let mainFrameId = ''; +let mainFrameURL = ''; const framesByProcessId = new Map>(); diff --git a/front_end/models/trace/lantern/simulation/Simulator.test.ts b/front_end/models/trace/lantern/simulation/Simulator.test.ts index 88a10909be..c513721cec 100644 --- a/front_end/models/trace/lantern/simulation/Simulator.test.ts +++ b/front_end/models/trace/lantern/simulation/Simulator.test.ts @@ -76,7 +76,7 @@ function cpuTask({tid, ts, duration}: { describe('DependencyGraph/Simulator', () => { // Insulate the simulator tests from DNS multiplier changes - let originalDNSMultiplier: number = 1; + let originalDNSMultiplier = 1; let trace: Lantern.Types.Trace; before(async function() { diff --git a/front_end/models/workspace/UISourceCode.ts b/front_end/models/workspace/UISourceCode.ts index 7c845697dd..047a55a08e 100644 --- a/front_end/models/workspace/UISourceCode.ts +++ b/front_end/models/workspace/UISourceCode.ts @@ -577,13 +577,13 @@ export class UILocation { this.columnNumber = columnNumber; } - linkText(skipTrim: boolean = false, showColumnNumber: boolean = false): string { + linkText(skipTrim = false, showColumnNumber = false): string { const displayName = this.uiSourceCode.displayName(skipTrim); const lineAndColumnText = this.lineAndColumnText(showColumnNumber); return lineAndColumnText ? displayName + ':' + lineAndColumnText : displayName; } - lineAndColumnText(showColumnNumber: boolean = false): string|undefined { + lineAndColumnText(showColumnNumber = false): string|undefined { let lineAndColumnText; if (this.uiSourceCode.mimeType() === 'application/wasm') { // For WebAssembly locations, we follow the conventions described in diff --git a/front_end/models/workspace_diff/WorkspaceDiff.ts b/front_end/models/workspace_diff/WorkspaceDiff.ts index 43b517c344..85943cbfb3 100644 --- a/front_end/models/workspace_diff/WorkspaceDiff.ts +++ b/front_end/models/workspace_diff/WorkspaceDiff.ts @@ -241,7 +241,7 @@ export class UISourceCodeDiff extends Common.ObjectWrapper.ObjectWrapper { const targetManager = SDK.TargetManager.TargetManager.instance(); const target = targetManager.rootTarget(); const runtimeModel = target!.model(SDK.RuntimeModel.RuntimeModel); - return getExecutionContext(runtimeModel!); + return await getExecutionContext(runtimeModel!); } async function executeForTest(action: string, throwOnSideEffect = false) { @@ -101,7 +101,7 @@ describe('FreestylerEvaluateAction', () => { return error; } }`; - return EvaluateAction.EvaluateAction.execute( + return await EvaluateAction.EvaluateAction.execute( functionDeclaration, [], await executionContextForTest(), {throwOnSideEffect}); } diff --git a/front_end/panels/ai_assistance/EvaluateAction.ts b/front_end/panels/ai_assistance/EvaluateAction.ts index 52549af3ad..2d554d1353 100644 --- a/front_end/panels/ai_assistance/EvaluateAction.ts +++ b/front_end/panels/ai_assistance/EvaluateAction.ts @@ -111,7 +111,7 @@ export class EvaluateAction { return formatError(exceptionDescription ?? 'JS exception'); } - return stringifyRemoteObject(response.object); + return await stringifyRemoteObject(response.object); } finally { executionContext.runtimeModel.releaseEvaluationResult(response); } diff --git a/front_end/panels/ai_assistance/agents/StylingAgent.ts b/front_end/panels/ai_assistance/agents/StylingAgent.ts index 949e0433f9..eca5c573a7 100644 --- a/front_end/panels/ai_assistance/agents/StylingAgent.ts +++ b/front_end/panels/ai_assistance/agents/StylingAgent.ts @@ -836,7 +836,7 @@ Please run ACTION again if the information you received is not enough to answer params, options, ) => { - return this.executeAction(params.action, options); + return await this.executeAction(params.action, options); }, }); diff --git a/front_end/panels/ai_assistance/ai_assistance-meta.ts b/front_end/panels/ai_assistance/ai_assistance-meta.ts index caa1392ab6..651a54d98f 100644 --- a/front_end/panels/ai_assistance/ai_assistance-meta.ts +++ b/front_end/panels/ai_assistance/ai_assistance-meta.ts @@ -114,7 +114,7 @@ UI.ViewManager.registerViewExtension({ condition: config => isAnyFeatureAvailable(config) && !isPolicyRestricted(config), async loadView() { const AiAssistance = await loadAiAssistanceModule(); - return AiAssistance.AiAssistancePanel.instance(); + return await AiAssistance.AiAssistancePanel.instance(); }, }); diff --git a/front_end/panels/ai_assistance/components/ChatView.ts b/front_end/panels/ai_assistance/components/ChatView.ts index 6635121a86..01e3f94245 100644 --- a/front_end/panels/ai_assistance/components/ChatView.ts +++ b/front_end/panels/ai_assistance/components/ChatView.ts @@ -973,7 +973,7 @@ function renderStepBadge({step, isLoading, isLast}: { return html``; } - let iconName: string = 'checkmark'; + let iconName = 'checkmark'; let ariaLabel: string|undefined = lockedString(UIStringsNotTranslate.completed); let role: 'button'|undefined = 'button'; if (isLast && step.sideEffect) { diff --git a/front_end/panels/ai_assistance/components/MarkdownRendererWithCodeBlock.ts b/front_end/panels/ai_assistance/components/MarkdownRendererWithCodeBlock.ts index 3d757e407e..3000ad350e 100644 --- a/front_end/panels/ai_assistance/components/MarkdownRendererWithCodeBlock.ts +++ b/front_end/panels/ai_assistance/components/MarkdownRendererWithCodeBlock.ts @@ -17,7 +17,7 @@ import type * as Lit from '../../../ui/lit/lit.js'; // } // ``` export class MarkdownRendererWithCodeBlock extends MarkdownView.MarkdownView.MarkdownInsightRenderer { - #stripLinks: boolean = false; + #stripLinks = false; constructor(opts: {stripLinks?: boolean} = {}) { super(); this.#stripLinks = Boolean(opts.stripLinks); diff --git a/front_end/panels/ai_assistance/debug.ts b/front_end/panels/ai_assistance/debug.ts index bff1f7c076..fbe0a3cc5d 100644 --- a/front_end/panels/ai_assistance/debug.ts +++ b/front_end/panels/ai_assistance/debug.ts @@ -26,5 +26,5 @@ function setDebugAiAssistanceEnabled(enabled: boolean): void { localStorage.removeItem('debugAiAssistancePanelEnabled'); } } -// @ts-ignore +// @ts-expect-error globalThis.setDebugAiAssistanceEnabled = setDebugAiAssistanceEnabled; diff --git a/front_end/panels/animation/AnimationTimeline.ts b/front_end/panels/animation/AnimationTimeline.ts index e05612c677..6136da9ab1 100644 --- a/front_end/panels/animation/AnimationTimeline.ts +++ b/front_end/panels/animation/AnimationTimeline.ts @@ -282,7 +282,7 @@ export class AnimationTimeline extends UI.Widget.VBox implements } this.#showPanelInDrawer(); - return this.selectAnimationGroup(animationGroup); + return await this.selectAnimationGroup(animationGroup); } modelAdded(animationModel: SDK.AnimationModel.AnimationModel): void { @@ -1122,9 +1122,9 @@ export class AnimationTimeline extends UI.Widget.VBox implements } if (this.#selectedGroup?.scrollOrientation() === Protocol.DOM.ScrollOrientation.Vertical) { - return node.setScrollTop(offset); + return await node.setScrollTop(offset); } - return node.setScrollLeft(offset); + return await node.setScrollLeft(offset); } private setTimelineScrubberPosition(time: number): void { diff --git a/front_end/panels/application/ApplicationPanelSidebar.test.ts b/front_end/panels/application/ApplicationPanelSidebar.test.ts index c79a668e67..4d44a59c5d 100644 --- a/front_end/panels/application/ApplicationPanelSidebar.test.ts +++ b/front_end/panels/application/ApplicationPanelSidebar.test.ts @@ -281,7 +281,7 @@ describeWithMockConnection('ApplicationPanelSidebar', () => { const sidebar = await Application.ResourcesPanel.ResourcesPanel.showAndGetSidebar(); const components = expectedCall.split('.'); assert.lengthOf(components, 2); - // @ts-ignore + // @ts-expect-error const object = sidebar[components[0]]; assert.exists(object); return sinon.spy(object, components[1]); diff --git a/front_end/panels/application/ApplicationPanelSidebar.ts b/front_end/panels/application/ApplicationPanelSidebar.ts index a05f10edaf..9bb4286221 100644 --- a/front_end/panels/application/ApplicationPanelSidebar.ts +++ b/front_end/panels/application/ApplicationPanelSidebar.ts @@ -568,8 +568,6 @@ export class ApplicationPanelSidebar extends UI.Widget.VBox implements SDK.Targe this.sharedStorageTreeElementDispatcher = new Common.ObjectWrapper.ObjectWrapper(); - // Work-around for crbug.com/1152713: Something is wrong with custom scrollbars and size containment. - // @ts-ignore this.contentElement.style.contain = 'layout style'; } diff --git a/front_end/panels/application/CookieItemsView.ts b/front_end/panels/application/CookieItemsView.ts index dd51293152..e60c70a419 100644 --- a/front_end/panels/application/CookieItemsView.ts +++ b/front_end/panels/application/CookieItemsView.ts @@ -256,7 +256,7 @@ export class CookieItemsView extends StorageItemsView { if (oldCookie && newCookie.key() !== oldCookie.key()) { await this.model.deleteCookie(oldCookie); } - return this.model.saveCookie(newCookie); + return await this.model.saveCookie(newCookie); } private deleteCookie(cookie: SDK.Cookie.Cookie, callback: () => void): void { diff --git a/front_end/panels/application/ExtensionStorageItemsView.test.ts b/front_end/panels/application/ExtensionStorageItemsView.test.ts index 6ce44f9362..b85e3d0c3f 100644 --- a/front_end/panels/application/ExtensionStorageItemsView.test.ts +++ b/front_end/panels/application/ExtensionStorageItemsView.test.ts @@ -18,8 +18,8 @@ import View = Resources.ExtensionStorageItemsView; class ExtensionStorageItemsListener { #dispatcher: Common.ObjectWrapper.ObjectWrapper; - #edited: boolean = false; - #refreshed: boolean = false; + #edited = false; + #refreshed = false; constructor(dispatcher: Common.ObjectWrapper.ObjectWrapper) { this.#dispatcher = dispatcher; diff --git a/front_end/panels/application/ServiceWorkerCacheViews.ts b/front_end/panels/application/ServiceWorkerCacheViews.ts index 56de4db300..6238a896cf 100644 --- a/front_end/panels/application/ServiceWorkerCacheViews.ts +++ b/front_end/panels/application/ServiceWorkerCacheViews.ts @@ -360,12 +360,12 @@ export class ServiceWorkerCacheView extends UI.View.SimpleView { returnCount: number, }|undefined> { if (!force && this.loadingPromise) { - return this.loadingPromise; + return await this.loadingPromise; } this.refreshButton.setEnabled(false); if (this.loadingPromise) { - return this.loadingPromise; + return await this.loadingPromise; } this.loadingPromise = new Promise(resolve => { diff --git a/front_end/panels/application/ServiceWorkerUpdateCycleView.ts b/front_end/panels/application/ServiceWorkerUpdateCycleView.ts index e42d04177e..04f06f12fe 100644 --- a/front_end/panels/application/ServiceWorkerUpdateCycleView.ts +++ b/front_end/panels/application/ServiceWorkerUpdateCycleView.ts @@ -78,10 +78,10 @@ export class ServiceWorkerUpdateCycleView { function rangesForVersion(version: SDK.ServiceWorkerManager.ServiceWorkerVersion): ServiceWorkerUpdateRange[] { let state: SDK.ServiceWorkerManager.ServiceWorkerVersionState|null = version.currentState; - let endActivateTime: number = 0; - let beginActivateTime: number = 0; - let endInstallTime: number = 0; - let beginInstallTime: number = 0; + let endActivateTime = 0; + let beginActivateTime = 0; + let endInstallTime = 0; + let beginInstallTime = 0; const currentStatus = state.status; if (currentStatus === Protocol.ServiceWorker.ServiceWorkerVersionStatus.New) { return []; diff --git a/front_end/panels/application/ServiceWorkersView.ts b/front_end/panels/application/ServiceWorkersView.ts index 82ccf95f76..fcc6e2bd0a 100644 --- a/front_end/panels/application/ServiceWorkersView.ts +++ b/front_end/panels/application/ServiceWorkersView.ts @@ -262,7 +262,7 @@ export class ServiceWorkersView extends UI.Widget.VBox implements this.updateListVisibility(); const drawerChangeHandler = (event: Event): void => { - // @ts-ignore: No support for custom event listener + // @ts-expect-error: No support for custom event listener const isDrawerOpen = event.detail && event.detail.isDrawerOpen; if (this.manager && !isDrawerOpen) { const {serviceWorkerNetworkRequestsPanelStatus: {isOpen, openedAt}} = this.manager; diff --git a/front_end/panels/application/SharedStorageItemsView.test.ts b/front_end/panels/application/SharedStorageItemsView.test.ts index aba20ea94c..5cc2fb2167 100644 --- a/front_end/panels/application/SharedStorageItemsView.test.ts +++ b/front_end/panels/application/SharedStorageItemsView.test.ts @@ -23,9 +23,9 @@ import View = Resources.SharedStorageItemsView; class SharedStorageItemsListener { #dispatcher: Common.ObjectWrapper.ObjectWrapper; - #cleared: boolean = false; - #filteredCleared: boolean = false; - #refreshed: boolean = false; + #cleared = false; + #filteredCleared = false; + #refreshed = false; #deletedKeys: String[] = []; #numEditedEvents = 0; diff --git a/front_end/panels/application/SharedStorageModel.ts b/front_end/panels/application/SharedStorageModel.ts index c18c713bc5..b494b9ca47 100644 --- a/front_end/panels/application/SharedStorageModel.ts +++ b/front_end/panels/application/SharedStorageModel.ts @@ -22,12 +22,12 @@ export class SharedStorageForOrigin extends Common.ObjectWrapper.ObjectWrapper { - return this.#model.storageAgent.invoke_getSharedStorageMetadata({ownerOrigin: this.securityOrigin}) + return await this.#model.storageAgent.invoke_getSharedStorageMetadata({ownerOrigin: this.securityOrigin}) .then(({metadata}) => metadata); } async getEntries(): Promise { - return this.#model.storageAgent.invoke_getSharedStorageEntries({ownerOrigin: this.securityOrigin}) + return await this.#model.storageAgent.invoke_getSharedStorageEntries({ownerOrigin: this.securityOrigin}) .then(({entries}) => entries); } diff --git a/front_end/panels/application/SharedStorageTreeElement.test.ts b/front_end/panels/application/SharedStorageTreeElement.test.ts index ba1cab88b9..25922a43bb 100644 --- a/front_end/panels/application/SharedStorageTreeElement.test.ts +++ b/front_end/panels/application/SharedStorageTreeElement.test.ts @@ -19,7 +19,7 @@ import * as Application from './application.js'; class SharedStorageItemsListener { #dispatcher: Common.ObjectWrapper.ObjectWrapper; - #refreshed: boolean = false; + #refreshed = false; constructor(dispatcher: Common.ObjectWrapper .ObjectWrapper) { diff --git a/front_end/panels/application/components/ProtocolHandlersView.ts b/front_end/panels/application/components/ProtocolHandlersView.ts index 2623024b7c..e9f4af26a6 100644 --- a/front_end/panels/application/components/ProtocolHandlersView.ts +++ b/front_end/panels/application/components/ProtocolHandlersView.ts @@ -96,8 +96,8 @@ export class ProtocolHandlersView extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); #protocolHandlers: ProtocolHandler[] = []; #manifestLink: Platform.DevToolsPath.UrlString = Platform.DevToolsPath.EmptyUrlString; - #selectedProtocolState: string = ''; - #queryInputState: string = ''; + #selectedProtocolState = ''; + #queryInputState = ''; set data(data: ProtocolHandlersData) { const isNewManifest = this.#manifestLink !== data.manifestLink; diff --git a/front_end/panels/application/components/SharedStorageMetadataView.ts b/front_end/panels/application/components/SharedStorageMetadataView.ts index 9d7b81e8c8..d4442abc3f 100644 --- a/front_end/panels/application/components/SharedStorageMetadataView.ts +++ b/front_end/panels/application/components/SharedStorageMetadataView.ts @@ -63,9 +63,9 @@ interface SharedStorageMetadataGetter { export class SharedStorageMetadataView extends StorageMetadataView { #sharedStorageMetadataGetter: SharedStorageMetadataGetter; #creationTime: Protocol.Network.TimeSinceEpoch|null = null; - #length: number = 0; - #bytesUsed: number = 0; - #remainingBudget: number = 0; + #length = 0; + #bytesUsed = 0; + #remainingBudget = 0; constructor(sharedStorageMetadataGetter: SharedStorageMetadataGetter, owner: string) { super(); diff --git a/front_end/panels/application/components/StackTrace.ts b/front_end/panels/application/components/StackTrace.ts index 0121164ffa..298e2d8765 100644 --- a/front_end/panels/application/components/StackTrace.ts +++ b/front_end/panels/application/components/StackTrace.ts @@ -108,7 +108,7 @@ export class StackTraceLinkButton extends HTMLElement { #onShowAllClick: () => void = () => {}; #hiddenCallFramesCount: number|null = null; - #expandedView: boolean = false; + #expandedView = false; set data(data: StackTraceLinkButtonData) { this.#onShowAllClick = data.onShowAllClick; diff --git a/front_end/panels/application/preloading/PreloadingView.test.ts b/front_end/panels/application/preloading/PreloadingView.test.ts index fb3e8ac855..cde5ce036c 100644 --- a/front_end/panels/application/preloading/PreloadingView.test.ts +++ b/front_end/panels/application/preloading/PreloadingView.test.ts @@ -28,7 +28,7 @@ const zip2 = (xs: T[], ys: S[]) => { // Holds targets and ids, and emits events. class NavigationEmulator { - private seq: number = 0; + private seq = 0; private tabTarget: SDK.Target.Target; primaryTarget: SDK.Target.Target; private frameId: Protocol.Page.FrameId; diff --git a/front_end/panels/application/preloading/PreloadingView.ts b/front_end/panels/application/preloading/PreloadingView.ts index c0e3b77d0c..6bd0dde913 100644 --- a/front_end/panels/application/preloading/PreloadingView.ts +++ b/front_end/panels/application/preloading/PreloadingView.ts @@ -84,7 +84,7 @@ const str_ = i18n.i18n.registerUIStrings('panels/application/preloading/Preloadi const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); // Used for selector, indicating no filter is specified. -const AllRuleSetRootId: symbol = Symbol('AllRuleSetRootId'); +const AllRuleSetRootId = Symbol('AllRuleSetRootId'); class PreloadingUIUtils { static status(status: SDK.PreloadingModel.PreloadingStatus): string { @@ -581,7 +581,7 @@ class PreloadingRuleSetSelector implements private onModelUpdated(): void { const ids = this.model.getAllRuleSets().map(({id}) => id); - const items = [AllRuleSetRootId, ...ids]; + const items = [AllRuleSetRootId, ...ids] as [typeof AllRuleSetRootId, ...Protocol.Preload.RuleSetId[]]; const selected = this.dropDown.getSelectedItem(); this.listModel.replaceAll(items); if (selected === null) { diff --git a/front_end/panels/application/preloading/components/RuleSetDetailsView.ts b/front_end/panels/application/preloading/components/RuleSetDetailsView.ts index e155624b81..f4ade0c6df 100644 --- a/front_end/panels/application/preloading/components/RuleSetDetailsView.ts +++ b/front_end/panels/application/preloading/components/RuleSetDetailsView.ts @@ -31,7 +31,7 @@ export type RuleSetDetailsViewData = RuleSet|null; export class RuleSetDetailsView extends LegacyWrapper.LegacyWrapper.WrappableComponent { readonly #shadow = this.attachShadow({mode: 'open'}); #data: RuleSetDetailsViewData = null; - #shouldPrettyPrint: boolean = true; + #shouldPrettyPrint = true; #editorState?: CodeMirror.EditorState; connectedCallback(): void { diff --git a/front_end/panels/autofill/AutofillView.ts b/front_end/panels/autofill/AutofillView.ts index e7b6c24286..930f37659e 100644 --- a/front_end/panels/autofill/AutofillView.ts +++ b/front_end/panels/autofill/AutofillView.ts @@ -120,7 +120,7 @@ export class AutofillView extends LegacyWrapper.LegacyWrapper.WrappableComponent readonly #renderBound = this.#render.bind(this); #autoOpenViewSetting: Common.Settings.Setting; #showTestAddressesInAutofillMenuSetting: Common.Settings.Setting; - #address: string = ''; + #address = ''; #filledFields: Protocol.Autofill.FilledField[] = []; #matches: AutofillManager.AutofillManager.Match[] = []; #highlightedMatches: AutofillManager.AutofillManager.Match[] = []; diff --git a/front_end/panels/changes/ChangesSidebar.ts b/front_end/panels/changes/ChangesSidebar.ts index 68d29c96b2..1dbdabc418 100644 --- a/front_end/panels/changes/ChangesSidebar.ts +++ b/front_end/panels/changes/ChangesSidebar.ts @@ -50,7 +50,7 @@ export class ChangesSidebar extends Common.ObjectWrapper.eventMixin { @@ -320,7 +320,7 @@ export class CoverageModel extends SDK.SDKModel.SDKModel { } const {coverage, timestamp} = await this.cpuProfilerModel.takePreciseCoverage(); this.coverageUpdateTimes.add(timestamp); - return this.backlogOrProcessJSCoverage(coverage, timestamp); + return await this.backlogOrProcessJSCoverage(coverage, timestamp); } private async backlogOrProcessJSCoverage( @@ -391,7 +391,7 @@ export class CoverageModel extends SDK.SDKModel.SDKModel { } const {coverage, timestamp} = await this.cssModel.takeCoverageDelta(); this.coverageUpdateTimes.add(timestamp); - return this.backlogOrProcessCSSCoverage(coverage, timestamp); + return await this.backlogOrProcessCSSCoverage(coverage, timestamp); } private async backlogOrProcessCSSCoverage(freshRawCoverageData: Protocol.CSS.RuleUsage[], freshTimestamp: number): @@ -859,7 +859,7 @@ export class URLCoverageInfo extends Common.ObjectWrapper.ObjectWrapper { + rangesForExport(offset = 0): Array<{start: number, end: number}> { const ranges = []; let start = 0; for (const segment of this.segments) { diff --git a/front_end/panels/css_overview/CSSOverviewCompletedView.ts b/front_end/panels/css_overview/CSSOverviewCompletedView.ts index 3a8d31f0d0..8deaf90b7f 100644 --- a/front_end/panels/css_overview/CSSOverviewCompletedView.ts +++ b/front_end/panels/css_overview/CSSOverviewCompletedView.ts @@ -686,7 +686,7 @@ export class CSSOverviewCompletedView extends UI.Widget.VBox { #groupToFragment( items: Map>, type: string, dataLabel: string, - path: string = ''): UI.Fragment.Fragment { + path = ''): UI.Fragment.Fragment { // Sort by number of items descending. const values = Array.from(items.entries()).sort((d1, d2) => { const v1Nodes = d1[1]; diff --git a/front_end/panels/developer_resources/DeveloperResourcesView.ts b/front_end/panels/developer_resources/DeveloperResourcesView.ts index 8fdd6a00b3..edecde3af8 100644 --- a/front_end/panels/developer_resources/DeveloperResourcesView.ts +++ b/front_end/panels/developer_resources/DeveloperResourcesView.ts @@ -62,7 +62,7 @@ export class DeveloperResourcesRevealer implements Common.Revealer.Revealer { diff --git a/front_end/panels/elements/ClassesPaneWidget.ts b/front_end/panels/elements/ClassesPaneWidget.ts index 54856e9fc9..d7bf3c6dac 100644 --- a/front_end/panels/elements/ClassesPaneWidget.ts +++ b/front_end/panels/elements/ClassesPaneWidget.ts @@ -168,7 +168,7 @@ export class ClassesPaneWidget extends UI.Widget.Widget { } this.classesContainer.removeChildren(); - // @ts-ignore this.input is a div, not an input element. So this line makes no sense at all + // @ts-expect-error this.input is a div, not an input element. So this line makes no sense at all this.input.disabled = !node; if (!node) { diff --git a/front_end/panels/elements/ComputedStyleModel.ts b/front_end/panels/elements/ComputedStyleModel.ts index 56a36928a0..8de5e6a3c1 100644 --- a/front_end/panels/elements/ComputedStyleModel.ts +++ b/front_end/panels/elements/ComputedStyleModel.ts @@ -178,7 +178,7 @@ export class ComputedStyleModel extends Common.ObjectWrapper.ObjectWrapper|null): ComputedStyle| diff --git a/front_end/panels/elements/ComputedStyleWidget.test.ts b/front_end/panels/elements/ComputedStyleWidget.test.ts index 86a27f55fb..ff9b889947 100644 --- a/front_end/panels/elements/ComputedStyleWidget.test.ts +++ b/front_end/panels/elements/ComputedStyleWidget.test.ts @@ -14,7 +14,7 @@ async function waitForTraceElement(treeOutline: TreeOutline.TreeOutline.TreeOutl return element; } - return new Promise(resolve => { + return await new Promise(resolve => { requestAnimationFrame(async () => { const result = await waitForTraceElement(treeOutline); resolve(result); diff --git a/front_end/panels/elements/ComputedStyleWidget.ts b/front_end/panels/elements/ComputedStyleWidget.ts index fad2711151..688d7aa748 100644 --- a/front_end/panels/elements/ComputedStyleWidget.ts +++ b/front_end/panels/elements/ComputedStyleWidget.ts @@ -356,7 +356,7 @@ export class ComputedStyleWidget extends UI.ThrottledWidget.ThrottledWidget { return null; } - return cssModel.cachedMatchedCascadeForNode(node).then(validateStyles.bind(this)); + return await cssModel.cachedMatchedCascadeForNode(node).then(validateStyles.bind(this)); function validateStyles(this: ComputedStyleWidget, matchedStyles: SDK.CSSMatchedStyles.CSSMatchedStyles|null): SDK.CSSMatchedStyles.CSSMatchedStyles|null { @@ -466,7 +466,7 @@ export class ComputedStyleWidget extends UI.ThrottledWidget.ThrottledWidget { compact: true, defaultRenderer, }; - return this.filterGroupLists(); + return await this.filterGroupLists(); } private buildTraceNode(property: SDK.CSSProperty.CSSProperty): @@ -603,7 +603,7 @@ export class ComputedStyleWidget extends UI.ThrottledWidget.ThrottledWidget { async filterComputedStyles(regex: RegExp|null): Promise { this.filterRegex = regex; if (this.groupComputedStylesSetting.get()) { - return this.filterGroupLists(); + return await this.filterGroupLists(); } return this.filterAlphabeticalList(); } diff --git a/front_end/panels/elements/ElementStatePaneWidget.test.ts b/front_end/panels/elements/ElementStatePaneWidget.test.ts index f7d013202a..d6d8b393c9 100644 --- a/front_end/panels/elements/ElementStatePaneWidget.test.ts +++ b/front_end/panels/elements/ElementStatePaneWidget.test.ts @@ -28,8 +28,7 @@ describeWithMockConnection('ElementStatePaneWidget', () => { }); const assertExpectedPseudoClasses = async ( - nodeName: string, expectedPseudoClasses: string[], formAssociated: boolean = false, - attribute?: [string, string]) => { + nodeName: string, expectedPseudoClasses: string[], formAssociated = false, attribute?: [string, string]) => { view = new Elements.ElementStatePaneWidget.ElementStatePaneWidget(); const tableUpdatedPromise = new Promise( resolve => sinon.stub(view, 'updateElementSpecificStatesTableForTest').callsFake(resolve), diff --git a/front_end/panels/elements/ElementsPanel.ts b/front_end/panels/elements/ElementsPanel.ts index ff6269a586..307633b566 100644 --- a/front_end/panels/elements/ElementsPanel.ts +++ b/front_end/panels/elements/ElementsPanel.ts @@ -1231,9 +1231,9 @@ export class ElementsPanel extends UI.Panel.Panel implements UI.SearchableView.S private static firstInspectElementNodeNameForTest = ''; } -// @ts-ignore exported for Tests.js +// @ts-expect-error exported for Tests.js globalThis.Elements = globalThis.Elements || {}; -// @ts-ignore exported for Tests.js +// @ts-expect-error exported for Tests.js globalThis.Elements.ElementsPanel = ElementsPanel; const enum SplitMode { diff --git a/front_end/panels/elements/ElementsTreeElement.ts b/front_end/panels/elements/ElementsTreeElement.ts index 645fcbb1e1..756a273e66 100644 --- a/front_end/panels/elements/ElementsTreeElement.ts +++ b/front_end/panels/elements/ElementsTreeElement.ts @@ -578,7 +578,7 @@ export class ElementsTreeElement extends UI.TreeOutline.TreeElement { override async onpopulate(): Promise { if (this.treeOutline) { - return this.treeOutline.populateTreeElement(this); + return await this.treeOutline.populateTreeElement(this); } } diff --git a/front_end/panels/elements/ElementsTreeOutline.ts b/front_end/panels/elements/ElementsTreeOutline.ts index 705005ecd0..feb312b531 100644 --- a/front_end/panels/elements/ElementsTreeOutline.ts +++ b/front_end/panels/elements/ElementsTreeOutline.ts @@ -98,7 +98,7 @@ export class ElementsTreeOutline extends private visibleWidthInternal?: number; private clipboardNodeData?: ClipboardData; private isXMLMimeTypeInternal?: boolean|null; - suppressRevealAndSelect: boolean = false; + suppressRevealAndSelect = false; private previousHoveredElement?: UI.TreeOutline.TreeElement; private treeElementBeingDragged?: ElementsTreeElement; private dragOverTreeElement?: ElementsTreeElement; @@ -377,7 +377,7 @@ export class ElementsTreeOutline extends private onCopyOrCut(isCut: boolean, event: Event): void { this.setClipboardData(null); - // @ts-ignore this bound in the main entry point + // @ts-expect-error this bound in the main entry point const originalEvent = event['original']; if (!originalEvent || !originalEvent.target) { @@ -1771,7 +1771,7 @@ export class Renderer implements UI.UIUtils.Renderer { treeOutline.element.classList.add('single-node'); } treeOutline.setVisible(true); - // @ts-ignore used in console_test_runner + // @ts-expect-error used in console_test_runner treeOutline.element.treeElementForTest = firstChild; treeOutline.setShowSelectionOnKeyboardFocus(/* show: */ true, /* preventTabOrder: */ true); return {node: treeOutline.element, tree: treeOutline}; diff --git a/front_end/panels/elements/LayersWidget.ts b/front_end/panels/elements/LayersWidget.ts index 1433cef3ea..938e6060c0 100644 --- a/front_end/panels/elements/LayersWidget.ts +++ b/front_end/panels/elements/LayersWidget.ts @@ -113,7 +113,7 @@ export class LayersWidget extends UI.Widget.Widget { ElementsPanel.instance().showToolbarPane(this, ButtonProvider.instance().item()); } await this.update(); - return this.layerTreeComponent.expandToAndSelectTreeNodeId('implicit outer layer.' + layerName); + return await this.layerTreeComponent.expandToAndSelectTreeNodeId('implicit outer layer.' + layerName); } static instance(opts: { diff --git a/front_end/panels/elements/StylePropertyTreeElement.test.ts b/front_end/panels/elements/StylePropertyTreeElement.test.ts index a074ee8b39..30d8ea1fdd 100644 --- a/front_end/panels/elements/StylePropertyTreeElement.test.ts +++ b/front_end/panels/elements/StylePropertyTreeElement.test.ts @@ -1114,10 +1114,10 @@ describeWithMockConnection('StylePropertyTreeElement', () => { getChildren(): CodeMirror.SyntaxNode[] { throw new Error('Method not implemented.'); } - from: number = 0; - to: number = 0; + from = 0; + to = 0; type = new CodeMirror.NodeType(); - name: string = ''; + name = ''; tree: CodeMirror.Tree|null = null; node: CodeMirror.SyntaxNode = this; matchContext(): boolean { diff --git a/front_end/panels/elements/StylesSidebarPane.ts b/front_end/panels/elements/StylesSidebarPane.ts index a619992531..5220602e98 100644 --- a/front_end/panels/elements/StylesSidebarPane.ts +++ b/front_end/panels/elements/StylesSidebarPane.ts @@ -491,7 +491,7 @@ export class StylesSidebarPane extends Common.ObjectWrapper.eventMixin { const parentRule = style.parentRule; @@ -2116,7 +2116,7 @@ export class CSSPropertyPrompt extends UI.TextPrompt.TextPrompt { const lowerQuery = query.toLowerCase(); const editingVariable = !this.isEditingName && expression.trim().endsWith('var('); if (!query && !force && !editingVariable && (this.isEditingName || expression)) { - return Promise.resolve([]); + return await Promise.resolve([]); } const prefixResults: CompletionResult[] = []; @@ -2243,7 +2243,7 @@ export class CSSPropertyPrompt extends UI.TextPrompt.TextPrompt { return a.isCSSVariableColor ? -1 : 1; }); } - return Promise.resolve(results); + return await Promise.resolve(results); function filterCompletions( this: CSSPropertyPrompt, completion: string, variable: boolean, nameValue?: boolean): void { diff --git a/front_end/panels/elements/TopLayerContainer.test.ts b/front_end/panels/elements/TopLayerContainer.test.ts index b022a51bf2..93d415e2cc 100644 --- a/front_end/panels/elements/TopLayerContainer.test.ts +++ b/front_end/panels/elements/TopLayerContainer.test.ts @@ -31,7 +31,7 @@ describeWithMockConnection('TopLayerContainer', () => { const topLayerDOMNode2 = stubTopLayerDOMNode('div', 2, stubDocument); const domModel = { target: () => createTarget(), - getTopLayerElements: async () => Promise.resolve([1 as Protocol.DOM.NodeId, 2 as Protocol.DOM.NodeId]), + getTopLayerElements: async () => await Promise.resolve([1 as Protocol.DOM.NodeId, 2 as Protocol.DOM.NodeId]), idToDOMNode: new Map([ [1, topLayerDOMNode1], [2, topLayerDOMNode2], diff --git a/front_end/panels/elements/components/CSSQuery.ts b/front_end/panels/elements/components/CSSQuery.ts index 9f79c77f4f..c69b6b33e8 100644 --- a/front_end/panels/elements/components/CSSQuery.ts +++ b/front_end/panels/elements/components/CSSQuery.ts @@ -30,9 +30,9 @@ export interface CSSQueryData { export class CSSQuery extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); - #queryPrefix: string = ''; + #queryPrefix = ''; #queryName?: string; - #queryText: string = ''; + #queryText = ''; #onQueryTextClick?: (event: Event) => void; #jslogContext?: string; diff --git a/front_end/panels/elements/components/StylePropertyEditor.ts b/front_end/panels/elements/components/StylePropertyEditor.ts index b2bddb0769..fa25259ca0 100644 --- a/front_end/panels/elements/components/StylePropertyEditor.ts +++ b/front_end/panels/elements/components/StylePropertyEditor.ts @@ -126,7 +126,7 @@ export class StylePropertyEditor extends HTMLElement { `; } - #renderButton(propertyValue: string, propertyName: string, selected: boolean = false): Lit.TemplateResult { + #renderButton(propertyValue: string, propertyName: string, selected = false): Lit.TemplateResult { const query = `${propertyName}: ${propertyValue}`; const iconInfo = this.findIcon(query, this.#computedProperties); if (!iconInfo) { diff --git a/front_end/panels/emulation/AdvancedApp.ts b/front_end/panels/emulation/AdvancedApp.ts index d943276b9e..532d6ff64d 100644 --- a/front_end/panels/emulation/AdvancedApp.ts +++ b/front_end/panels/emulation/AdvancedApp.ts @@ -183,9 +183,9 @@ export class AdvancedApp implements Common.App.App { } // Export required for usage in toolbox.ts -// @ts-ignore Exported for Tests.js +// @ts-expect-error Exported for Tests.js globalThis.Emulation = globalThis.Emulation || {}; -// @ts-ignore Exported for Tests.js +// @ts-expect-error Exported for Tests.js globalThis.Emulation.AdvancedApp = AdvancedApp; let advancedAppProviderInstance: AdvancedAppProvider; diff --git a/front_end/panels/event_listeners/EventListenersUtils.ts b/front_end/panels/event_listeners/EventListenersUtils.ts index 95214e9177..b08d03da2a 100644 --- a/front_end/panels/event_listeners/EventListenersUtils.ts +++ b/front_end/panels/event_listeners/EventListenersUtils.ts @@ -13,7 +13,7 @@ export async function frameworkEventListeners(object: SDK.RemoteObject.RemoteObj } const listenersResult = {internalHandlers: null, eventListeners: []} as FrameworkEventListenersObject; - return object.callFunction(frameworkEventListenersImpl, undefined) + return await object.callFunction(frameworkEventListenersImpl, undefined) .then(assertCallFunctionResult) .then(getOwnProperties) .then(createEventListeners) @@ -218,9 +218,9 @@ export async function frameworkEventListeners(object: SDK.RemoteObject.RemoteObj let internalHandlers: Array<() => void> = []; let fetchers = [jQueryFetcher]; try { - // @ts-ignore Here because of layout tests. + // @ts-expect-error Here because of layout tests. if (self.devtoolsFrameworkEventListeners && isArrayLike(self.devtoolsFrameworkEventListeners)) { - // @ts-ignore Here because of layout tests. + // @ts-expect-error Here because of layout tests. fetchers = fetchers.concat(self.devtoolsFrameworkEventListeners); } } catch (e) { @@ -298,8 +298,8 @@ export async function frameworkEventListeners(object: SDK.RemoteObject.RemoteObj return false; } - function checkEventListener(eventListener: PossibleEventListenerObjectInInspectedPage| - null): EventListenerObjectInInspectedPage|null { + function checkEventListener(eventListener: PossibleEventListenerObjectInInspectedPage|null): + EventListenerObjectInInspectedPage|null { try { let errorString = ''; if (!eventListener) { @@ -445,8 +445,7 @@ export async function frameworkEventListeners(object: SDK.RemoteObject.RemoteObj return; } const jQueryFunction = jQuery as (arg0: Node) => { - off: - Function, + off: Function, }; jQueryFunction(node).off(type, selector, handler); } diff --git a/front_end/panels/event_listeners/EventListenersView.ts b/front_end/panels/event_listeners/EventListenersView.ts index 280593dfac..f3d162fd51 100644 --- a/front_end/panels/event_listeners/EventListenersView.ts +++ b/front_end/panels/event_listeners/EventListenersView.ts @@ -126,7 +126,7 @@ export class EventListenersView extends UI.Widget.VBox { if (!frameworkEventListenersObject.internalHandlers) { return; } - return frameworkEventListenersObject.internalHandlers.object() + return await frameworkEventListenersObject.internalHandlers.object() .callFunctionJSON(isInternalEventListener as (this: Object) => boolean[], eventListeners.map(handlerArgument)) .then(setIsInternal); diff --git a/front_end/panels/issues/IssueView.ts b/front_end/panels/issues/IssueView.ts index 58e5ef17a2..474b3896b5 100644 --- a/front_end/panels/issues/IssueView.ts +++ b/front_end/panels/issues/IssueView.ts @@ -224,7 +224,7 @@ export class IssueView extends UI.TreeOutline.TreeElement { #throttle: Common.Throttler.Throttler; #needsUpdateOnExpand = true; #hiddenIssuesMenu?: Components.HideIssuesMenu.HideIssuesMenu; - #contentCreated: boolean = false; + #contentCreated = false; constructor(issue: AggregatedIssue, description: IssuesManager.MarkdownIssueDescription.IssueDescription) { super(); diff --git a/front_end/panels/layer_viewer/Layers3DView.ts b/front_end/panels/layer_viewer/Layers3DView.ts index bdd8752e01..97153e08d5 100644 --- a/front_end/panels/layer_viewer/Layers3DView.ts +++ b/front_end/panels/layer_viewer/Layers3DView.ts @@ -798,7 +798,7 @@ export class Layers3DView extends Common.ObjectWrapper.eventMixin implements Pro override async resumeModel(): Promise { if (!this.enabled) { - return Promise.resolve(); + return await Promise.resolve(); } await this.agent.invoke_enable(); } diff --git a/front_end/panels/media/TickingFlameChart.ts b/front_end/panels/media/TickingFlameChart.ts index d72d2c29cb..1c376fff6e 100644 --- a/front_end/panels/media/TickingFlameChart.ts +++ b/front_end/panels/media/TickingFlameChart.ts @@ -318,7 +318,7 @@ export class TickingFlameChart extends UI.Widget.VBox { this.ticking = true; } - private stop(permanently: boolean = false): void { + private stop(permanently = false): void { window.clearInterval(this.intervalTimer); this.intervalTimer = 0; if (permanently) { diff --git a/front_end/panels/mobile_throttling/ThrottlingPresets.ts b/front_end/panels/mobile_throttling/ThrottlingPresets.ts index bed99c92c8..6b1e3c0731 100644 --- a/front_end/panels/mobile_throttling/ThrottlingPresets.ts +++ b/front_end/panels/mobile_throttling/ThrottlingPresets.ts @@ -188,9 +188,9 @@ export class ThrottlingPresets { ]; } -// @ts-ignore exported for Tests.js +// @ts-expect-error exported for Tests.js globalThis.MobileThrottling = globalThis.MobileThrottling || {}; -// @ts-ignore exported for Tests.js +// @ts-expect-error exported for Tests.js globalThis.MobileThrottling.networkPresets = ThrottlingPresets.networkPresets; export interface Conditions { diff --git a/front_end/panels/network/RequestPayloadView.ts b/front_end/panels/network/RequestPayloadView.ts index 458d723f97..8aab123074 100644 --- a/front_end/panels/network/RequestPayloadView.ts +++ b/front_end/panels/network/RequestPayloadView.ts @@ -461,7 +461,7 @@ export class RequestPayloadView extends UI.Widget.VBox { // `editable` is not a valid property for `ObjectUI.ObjectPropertiesSection.RootElement`. Only for // `ObjectUI.ObjectPropertiesSection.ObjectPropertiesSection`. We do not know if this assignment is // safe to delete. - // @ts-ignore + // @ts-expect-error section.editable = false; rootListItem.childrenListElement.classList.add('source-code', 'object-properties-section'); diff --git a/front_end/panels/network/components/EditableSpan.ts b/front_end/panels/network/components/EditableSpan.ts index 6a136f8d38..acab82c791 100644 --- a/front_end/panels/network/components/EditableSpan.ts +++ b/front_end/panels/network/components/EditableSpan.ts @@ -19,7 +19,7 @@ export interface EditableSpanData { export class EditableSpan extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); readonly #boundRender = this.#render.bind(this); - #value: string = ''; + #value = ''; connectedCallback(): void { this.#shadow.adoptedStyleSheets = [editableSpanStyles]; diff --git a/front_end/panels/network/components/RequestHeadersView.ts b/front_end/panels/network/components/RequestHeadersView.ts index f5ebe7b362..aedc499ac8 100644 --- a/front_end/panels/network/components/RequestHeadersView.ts +++ b/front_end/panels/network/components/RequestHeadersView.ts @@ -199,7 +199,7 @@ export class RequestHeadersView extends LegacyWrapper.LegacyWrapper.WrappableCom return; } - return RenderCoordinator.write(() => { + return await RenderCoordinator.write(() => { // Disabled until https://crbug.com/1079231 is fixed. // clang-format off render(html` diff --git a/front_end/panels/network/components/ResponseHeaderSection.test.ts b/front_end/panels/network/components/ResponseHeaderSection.test.ts index 70e9b91b36..8e20133e75 100644 --- a/front_end/panels/network/components/ResponseHeaderSection.test.ts +++ b/front_end/panels/network/components/ResponseHeaderSection.test.ts @@ -96,7 +96,7 @@ async function setupHeaderEditing( setAssociatedData: () => {}, } as unknown as SDK.NetworkRequest.NetworkRequest; - return setupHeaderEditingWithRequest(headerOverridesFileContent, request); + return await setupHeaderEditingWithRequest(headerOverridesFileContent, request); } async function setupHeaderEditingWithRequest( @@ -125,8 +125,8 @@ async function setupHeaderEditingWithRequest( function checkHeaderSectionRow( row: NetworkComponents.HeaderSectionRow.HeaderSectionRow, headerName: string, headerValue: string, - isOverride: boolean, isNameEditable: boolean, isValueEditable: boolean, isHighlighted: boolean = false, - isDeleted: boolean = false): void { + isOverride: boolean, isNameEditable: boolean, isValueEditable: boolean, isHighlighted = false, + isDeleted = false): void { assert.isNotNull(row.shadowRoot); const rowElement = row.shadowRoot.querySelector('.row'); assert.strictEqual(rowElement?.classList.contains('header-overridden'), isOverride); diff --git a/front_end/panels/performance_monitor/PerformanceMonitor.ts b/front_end/panels/performance_monitor/PerformanceMonitor.ts index 94d6a3bced..8ab2571976 100644 --- a/front_end/panels/performance_monitor/PerformanceMonitor.ts +++ b/front_end/panels/performance_monitor/PerformanceMonitor.ts @@ -75,7 +75,7 @@ export class PerformanceMonitorImpl extends UI.Widget.HBox implements private startTimestamp?: number; private pollTimer?: number; - constructor(pollIntervalMs: number = 500) { + constructor(pollIntervalMs = 500) { super(true); this.registerRequiredCSS(performanceMonitorStyles); @@ -289,7 +289,7 @@ export class PerformanceMonitorImpl extends UI.Widget.HBox implements } const width = this.width; const startTime = performance.now() - this.pollIntervalMs - width / this.pixelsPerMs; - let max: number = -Infinity; + let max = -Infinity; for (const metricInfo of chartInfo.metrics) { for (let i = this.metricsBuffer.length - 1; i >= 0; --i) { const metrics = this.metricsBuffer[i]; diff --git a/front_end/panels/profiler/HeapDetachedElementsDataGrid.ts b/front_end/panels/profiler/HeapDetachedElementsDataGrid.ts index 5be1c0ef51..aed4755012 100644 --- a/front_end/panels/profiler/HeapDetachedElementsDataGrid.ts +++ b/front_end/panels/profiler/HeapDetachedElementsDataGrid.ts @@ -86,7 +86,7 @@ export class HeapDetachedElementsDataGridNode extends DataGrid.DataGrid.DataGrid } #getNodeSize(detachedElementInfo: Protocol.DOM.DetachedElementInfo): number { - let count: number = 1; + let count = 1; const queue: Protocol.DOM.Node[] = []; let node: Protocol.DOM.Node|undefined; queue.push(detachedElementInfo.treeNode); @@ -117,7 +117,7 @@ export class HeapDetachedElementsDataGridNode extends DataGrid.DataGrid.DataGrid treeOutline.element.classList.add('single-node'); } treeOutline.setVisible(true); - // @ts-ignore used in console_test_runner + // @ts-expect-error used in console_test_runner treeOutline.element.treeElementForTest = firstChild; treeOutline.setShowSelectionOnKeyboardFocus(/* show: */ true, /* preventTabOrder: */ true); diff --git a/front_end/panels/profiler/HeapSnapshotDataGrids.ts b/front_end/panels/profiler/HeapSnapshotDataGrids.ts index 6e522d29bb..7b8bc930e9 100644 --- a/front_end/panels/profiler/HeapSnapshotDataGrids.ts +++ b/front_end/panels/profiler/HeapSnapshotDataGrids.ts @@ -155,9 +155,9 @@ const adjacencyMap = new WeakMap {} -export class HeapSnapshotSortableDataGrid extends - Common.ObjectWrapper.eventMixin( - HeapSnapshotSortableDataGridBase) { +export class HeapSnapshotSortableDataGrid extends Common.ObjectWrapper + .eventMixin( + HeapSnapshotSortableDataGridBase) { snapshot: HeapSnapshotProxy|null; override selectedNode: HeapSnapshotGridNode|null; readonly heapProfilerModelInternal: SDK.HeapProfilerModel.HeapProfilerModel|null; @@ -322,9 +322,9 @@ export class HeapSnapshotSortableDataGrid extends function sortByTwoFields( nodeA: DataGrid.DataGrid.DataGridNode, nodeB: DataGrid.DataGrid.DataGridNode): number { - // @ts-ignore + // @ts-expect-error let field1 = nodeA[sortFields.fieldName1]; - // @ts-ignore + // @ts-expect-error let field2 = nodeB[sortFields.fieldName1]; let result: number|(0 | 1 | -1) = field1 < field2 ? -1 : (field1 > field2 ? 1 : 0); if (!sortFields.ascending1) { @@ -333,9 +333,9 @@ export class HeapSnapshotSortableDataGrid extends if (result !== 0) { return result; } - // @ts-ignore + // @ts-expect-error field1 = nodeA[sortFields.fieldName2]; - // @ts-ignore + // @ts-expect-error field2 = nodeB[sortFields.fieldName2]; result = field1 < field2 ? -1 : (field1 > field2 ? 1 : 0); if (!sortFields.ascending2) { @@ -835,7 +835,7 @@ export class HeapSnapshotConstructorsDataGrid extends HeapSnapshotViewportDataGr } const nodes = await parent.populateNodeBySnapshotObjectId(parseInt(id, 10)); - return nodes.length ? this.revealTreeNode(nodes) : null; + return nodes.length ? await this.revealTreeNode(nodes) : null; } clear(): void { @@ -1071,11 +1071,11 @@ export class AllocationDataGrid extends HeapSnapshotViewportDataGrid { const fieldName = this.sortColumnId(); const compareResult = (this.sortOrder() === DataGrid.DataGrid.Order.Ascending) ? +1 : -1; function compare(a: Object, b: Object): number { - // @ts-ignore + // @ts-expect-error if (a[fieldName] > b[fieldName]) { return compareResult; } - // @ts-ignore + // @ts-expect-error if (a[fieldName] < b[fieldName]) { return -compareResult; } diff --git a/front_end/panels/profiler/HeapSnapshotView.ts b/front_end/panels/profiler/HeapSnapshotView.ts index fad74ce841..12feb9f163 100644 --- a/front_end/panels/profiler/HeapSnapshotView.ts +++ b/front_end/panels/profiler/HeapSnapshotView.ts @@ -326,7 +326,7 @@ export class HeapSnapshotView extends UI.View.SimpleView implements DataDisplayD readonly searchThrottler: Common.Throttler.Throttler; baseProfile!: HeapProfileHeader|null; trackingOverviewGrid?: HeapTimelineOverview; - currentSearchResultIndex: number = -1; + currentSearchResultIndex = -1; currentQuery?: HeapSnapshotModel.HeapSnapshotModel.SearchConfig; constructor(dataDisplayDelegate: DataDisplayDelegate, profile: HeapProfileHeader) { super(i18nString(UIStrings.heapSnapshot)); @@ -1681,7 +1681,7 @@ export class HeapProfileHeader extends ProfileHeader { if (!this.snapshotProxy) { return null; } - return this.snapshotProxy.getLocation(nodeIndex); + return await this.snapshotProxy.getLocation(nodeIndex); } override createSidebarTreeElement(dataDisplayDelegate: DataDisplayDelegate): ProfileSidebarTreeElement { diff --git a/front_end/panels/profiler/ProfileDataGrid.ts b/front_end/panels/profiler/ProfileDataGrid.ts index 7ec8d6ea0e..a754f89484 100644 --- a/front_end/panels/profiler/ProfileDataGrid.ts +++ b/front_end/panels/profiler/ProfileDataGrid.ts @@ -348,7 +348,7 @@ export class ProfileDataGridTree implements UI.SearchableView.Searchable { }>; savedTotal?: number; savedChildren?: ProfileDataGridNode[]|null; - searchResultIndex: number = -1; + searchResultIndex = -1; constructor(formatter: Formatter, searchableView: UI.SearchableView.SearchableView, total: number) { this.tree = this; diff --git a/front_end/panels/profiler/ProfileFlameChartDataProvider.ts b/front_end/panels/profiler/ProfileFlameChartDataProvider.ts index c7c1348970..96e8a658df 100644 --- a/front_end/panels/profiler/ProfileFlameChartDataProvider.ts +++ b/front_end/panels/profiler/ProfileFlameChartDataProvider.ts @@ -151,7 +151,7 @@ export class ProfileFlameChart extends entrySelected: boolean; readonly dataProvider: ProfileFlameChartDataProvider; searchResults: number[]; - searchResultIndex: number = -1; + searchResultIndex = -1; constructor(searchableView: UI.SearchableView.SearchableView, dataProvider: ProfileFlameChartDataProvider) { super(); diff --git a/front_end/panels/profiler/ProfileView.ts b/front_end/panels/profiler/ProfileView.ts index 239cefa0ca..e1a363a80d 100644 --- a/front_end/panels/profiler/ProfileView.ts +++ b/front_end/panels/profiler/ProfileView.ts @@ -342,7 +342,7 @@ export class ProfileView extends UI.View.SimpleView implements UI.SearchableView if (selectedProfileNode) { // TODO(crbug.com/1011811): Cleanup the added `selected` property to this SDK class. - // @ts-ignore + // @ts-expect-error selectedProfileNode.selected = true; } } @@ -627,7 +627,7 @@ export class WritableProfileHeader extends ProfileHeader implements Common.Strin } this.updateStatus(i18nString(UIStrings.parsing), true); - let error: null = null; + let error = null; try { this.profile = (JSON.parse(this.jsonifiedProfile) as Protocol.Profiler.Profile); this.setProfile((this.profile)); diff --git a/front_end/panels/protocol_monitor/JSONEditor.ts b/front_end/panels/protocol_monitor/JSONEditor.ts index 042a8d10e5..2682b2645e 100644 --- a/front_end/panels/protocol_monitor/JSONEditor.ts +++ b/front_end/panels/protocol_monitor/JSONEditor.ts @@ -146,7 +146,7 @@ export class JSONEditor extends Common.ObjectWrapper.eventMixin>; #parameters: Parameter[] = []; #targets: SDK.Target.Target[] = []; - #command: string = ''; + #command = ''; #targetId?: string; #hintPopoverHelper?: UI.PopoverHelper.PopoverHelper; diff --git a/front_end/panels/protocol_monitor/ProtocolMonitor.ts b/front_end/panels/protocol_monitor/ProtocolMonitor.ts index 6a3e6bcaeb..5be417430b 100644 --- a/front_end/panels/protocol_monitor/ProtocolMonitor.ts +++ b/front_end/panels/protocol_monitor/ProtocolMonitor.ts @@ -498,7 +498,7 @@ export class ProtocolMonitorDataGrid extends Common.ObjectWrapper.eventMixin {}, sessionId); } @@ -515,16 +515,11 @@ export class ProtocolMonitorDataGrid extends Common.ObjectWrapper.eventMixin>; static async defaultByAttribute(_state: DeepImmutable, attribute: keyof typeof defaultValuesByAttribute): Promise { - return this.#puppeteer.run(puppeteer => { + return await this.#puppeteer.run(puppeteer => { switch (attribute) { case 'assertedEvents': { return immutableDeepAssign(defaultValuesByAttribute.assertedEvents, new ArrayAssignments({ @@ -401,7 +401,7 @@ export class EditorState { const state = structuredClone(step) as EditorState; for (const key of ['parameters', 'properties'] as Array<'properties'>) { if (key in step && step[key] !== undefined) { - // @ts-ignore Potential infinite type instantiation. + // @ts-expect-error Potential infinite type instantiation. state[key] = JSON.stringify(step[key]); } } diff --git a/front_end/panels/recorder/models/RecordingPlayer.ts b/front_end/panels/recorder/models/RecordingPlayer.ts index eb8922df1a..a70706b9b2 100644 --- a/front_end/panels/recorder/models/RecordingPlayer.ts +++ b/front_end/panels/recorder/models/RecordingPlayer.ts @@ -47,7 +47,7 @@ export class RecordingPlayer extends Common.ObjectWrapper.ObjectWrapper; - steppingOver: boolean = false; + steppingOver = false; aborted = false; abortPromise: Promise; #abortResolveFn?: Function; diff --git a/front_end/panels/recorder/models/RecordingStorage.ts b/front_end/panels/recorder/models/RecordingStorage.ts index eb2c66127d..1d5340bfc4 100644 --- a/front_end/panels/recorder/models/RecordingStorage.ts +++ b/front_end/panels/recorder/models/RecordingStorage.ts @@ -14,7 +14,6 @@ interface IdGenerator { class UUIDGenerator implements IdGenerator { next(): string { - // @ts-ignore return crypto.randomUUID(); } } diff --git a/front_end/panels/recorder/util/util.ts b/front_end/panels/recorder/util/util.ts index c1950feee7..0ab277a028 100644 --- a/front_end/panels/recorder/util/util.ts +++ b/front_end/panels/recorder/util/util.ts @@ -18,7 +18,7 @@ class InjectedScript { )) .text(); } - return this.#injectedScript; + return await this.#injectedScript; } } diff --git a/front_end/panels/screencast/ScreencastView.ts b/front_end/panels/screencast/ScreencastView.ts index 49614a7e9b..9ba8b74249 100644 --- a/front_end/panels/screencast/ScreencastView.ts +++ b/front_end/panels/screencast/ScreencastView.ts @@ -132,7 +132,7 @@ export class ScreencastView extends UI.Widget.VBox implements SDK.OverlayModel.H private mouseInputToggleIcon?: IconButton.Icon.Icon; private historyIndex?: number; private historyEntries?: Protocol.Page.NavigationEntry[]; - private isCasting: boolean = false; + private isCasting = false; private screencastOperationId?: number; constructor(screenCaptureModel: SDK.ScreenCaptureModel.ScreenCaptureModel) { super(); diff --git a/front_end/panels/security/CookieReportView.test.ts b/front_end/panels/security/CookieReportView.test.ts index 4c1165a16c..b2868ab660 100644 --- a/front_end/panels/security/CookieReportView.test.ts +++ b/front_end/panels/security/CookieReportView.test.ts @@ -60,7 +60,7 @@ describeWithMockConnection('CookieReportView', () => { }); it('should have row when there was a preexisting cookie issue', async () => { - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest(getTestCookieIssue()); const view = new Security.CookieReportView.CookieReportView(undefined, mockView); @@ -75,7 +75,7 @@ describeWithMockConnection('CookieReportView', () => { assert.lengthOf(mockView.lastCall.firstArg.cookieRows, 0); - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest(getTestCookieIssue()); await view.updateComplete; @@ -85,7 +85,7 @@ describeWithMockConnection('CookieReportView', () => { it('should ignore non-third-party-cookie related exclusionReason', async () => { const view = new Security.CookieReportView.CookieReportView(undefined, mockView); - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest( getTestCookieIssue(undefined, Protocol.Audits.CookieExclusionReason.ExcludeSameSiteNoneInsecure)); await view.updateComplete; @@ -93,7 +93,7 @@ describeWithMockConnection('CookieReportView', () => { assert.lengthOf(mockView.lastCall.firstArg.cookieRows, 0); // Make sure ExcludeThirdPartyPhaseout (default) is added. - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest(getTestCookieIssue()); await view.updateComplete; @@ -104,7 +104,7 @@ describeWithMockConnection('CookieReportView', () => { it('should ignore non-third-party-cookie related warningReason', async () => { const view = new Security.CookieReportView.CookieReportView(undefined, mockView); - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest( getTestCookieIssue(undefined, undefined, Protocol.Audits.CookieWarningReason.WarnSameSiteLaxCrossDowngradeLax)); await view.updateComplete; @@ -112,13 +112,13 @@ describeWithMockConnection('CookieReportView', () => { assert.lengthOf(mockView.lastCall.firstArg.cookieRows, 0); // Make sure warning 3pc warning reasons are added - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest(getTestCookieIssue( undefined, undefined, Protocol.Audits.CookieWarningReason.WarnDeprecationTrialMetadata, 'metadata')); - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest(getTestCookieIssue( undefined, undefined, Protocol.Audits.CookieWarningReason.WarnThirdPartyCookieHeuristic, 'heuristic')); - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest(getTestCookieIssue( undefined, undefined, Protocol.Audits.CookieWarningReason.WarnThirdPartyPhaseout, 'phaseout')); await view.updateComplete; @@ -135,9 +135,9 @@ describeWithMockConnection('CookieReportView', () => { it('should only have a single entry for same cookie with a read and a write operations', async () => { const view = new Security.CookieReportView.CookieReportView(undefined, mockView); - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest(getTestCookieIssue(true)); - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest(getTestCookieIssue(false)); await view.updateComplete; @@ -147,7 +147,7 @@ describeWithMockConnection('CookieReportView', () => { it('should have zero entries after the primary page was changed', async () => { const view = new Security.CookieReportView.CookieReportView(undefined, mockView); - // @ts-ignore + // @ts-expect-error globalThis.addIssueForTest(getTestCookieIssue(true)); await view.updateComplete; diff --git a/front_end/panels/security/SecurityPanelSidebarTreeElement.ts b/front_end/panels/security/SecurityPanelSidebarTreeElement.ts index 21f067a242..3b2270445a 100644 --- a/front_end/panels/security/SecurityPanelSidebarTreeElement.ts +++ b/front_end/panels/security/SecurityPanelSidebarTreeElement.ts @@ -4,7 +4,7 @@ import * as UI from '../../ui/legacy/legacy.js'; export class SecurityPanelSidebarTreeElement extends UI.TreeOutline.TreeElement { - constructor(title: string = '', expandable: boolean = false, jslogContext?: string|number) { + constructor(title = '', expandable = false, jslogContext?: string|number) { super(title, expandable, jslogContext); UI.ARIAUtils.setLabel(this.listItemElement, title); } diff --git a/front_end/panels/settings/SettingsScreen.ts b/front_end/panels/settings/SettingsScreen.ts index 6b4e530418..dc5a1b0c39 100644 --- a/front_end/panels/settings/SettingsScreen.ts +++ b/front_end/panels/settings/SettingsScreen.ts @@ -177,10 +177,6 @@ export class SettingsScreen extends UI.Widget.VBox implements UI.View.ViewLocati settingsScreen.show(dialog.contentElement); dialog.setEscapeKeyCallback(settingsScreen.onEscapeKeyPressed.bind(settingsScreen)); dialog.setMarginBehavior(UI.GlassPane.MarginBehavior.NO_MARGIN); - // UI.Dialog extends GlassPane and overrides the `show` method with a wider - // accepted type. However, TypeScript uses the supertype declaration to - // determine the full type, which requires a `!Document`. - // @ts-ignore dialog.show(); return settingsScreen; diff --git a/front_end/panels/settings/emulation/components/UserAgentClientHintsForm.ts b/front_end/panels/settings/emulation/components/UserAgentClientHintsForm.ts index e33710e228..cc0c34f741 100644 --- a/front_end/panels/settings/emulation/components/UserAgentClientHintsForm.ts +++ b/front_end/panels/settings/emulation/components/UserAgentClientHintsForm.ts @@ -210,12 +210,12 @@ const DEFAULT_METADATA = { export class UserAgentClientHintsForm extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); - #isFormOpened: boolean = false; - #isFormDisabled: boolean = false; + #isFormOpened = false; + #isFormDisabled = false; #metaData: Protocol.Emulation.UserAgentMetadata = DEFAULT_METADATA; - #showMobileCheckbox: boolean = false; - #showSubmitButton: boolean = false; - #useragentModifiedAriaMessage: string = ''; + #showMobileCheckbox = false; + #showSubmitButton = false; + #useragentModifiedAriaMessage = ''; connectedCallback(): void { this.#shadow.adoptedStyleSheets = [Input.checkboxStyles, userAgentClientHintsFormStyles]; diff --git a/front_end/panels/settings/emulation/utils/StructuredHeaders.ts b/front_end/panels/settings/emulation/utils/StructuredHeaders.ts index 407fd5654b..2f1809ba11 100644 --- a/front_end/panels/settings/emulation/utils/StructuredHeaders.ts +++ b/front_end/panels/settings/emulation/utils/StructuredHeaders.ts @@ -146,8 +146,8 @@ const CHAR_PIPE: number = '|'.charCodeAt(0); const CHAR_TILDE: number = '~'.charCodeAt(0); // ASCII printable range. -const CHAR_MIN_ASCII_PRINTABLE: number = 0x20; -const CHAR_MAX_ASCII_PRINTABLE: number = 0x7e; +const CHAR_MIN_ASCII_PRINTABLE = 0x20; +const CHAR_MAX_ASCII_PRINTABLE = 0x7e; // Note: structured headers operates over ASCII, not unicode, so these are // all indeed supposed to return false on things outside 32-127 range regardless @@ -415,7 +415,7 @@ function parseParameters(input: Input): Parameters|Error { // 4.2.3.3. Parsing a Key function parseKey(input: Input): ParamName|Error { - let outputString: string = ''; + let outputString = ''; const first = input.peekCharCode(); if (first !== CHAR_STAR && !isLcAlpha(first)) { return makeError(); @@ -437,7 +437,7 @@ function parseKey(input: Input): ParamName|Error { // 4.2.4. Parsing an Integer or Decimal function parseIntegerOrDecimal(input: Input): Integer|Decimal|Error { let resultKind = ResultKind.INTEGER; - let sign: number = 1; + let sign = 1; let inputNumber = ''; if (input.peek() === '-') { input.eat(); diff --git a/front_end/panels/sources/AddSourceMapURLDialog.ts b/front_end/panels/sources/AddSourceMapURLDialog.ts index 54ced53411..b37a23089a 100644 --- a/front_end/panels/sources/AddSourceMapURLDialog.ts +++ b/front_end/panels/sources/AddSourceMapURLDialog.ts @@ -63,10 +63,6 @@ export class AddDebugInfoURLDialog extends UI.Widget.HBox { override show(): void { super.show(this.dialog.contentElement); - // UI.Dialog extends GlassPane and overrides the `show` method with a wider - // accepted type. However, TypeScript uses the supertype declaration to - // determine the full type, which requires a `!Document`. - // @ts-ignore this.dialog.show(); } diff --git a/front_end/panels/sources/CSSPlugin.ts b/front_end/panels/sources/CSSPlugin.ts index 1b64fe9214..41af0e92a7 100644 --- a/front_end/panels/sources/CSSPlugin.ts +++ b/front_end/panels/sources/CSSPlugin.ts @@ -463,7 +463,7 @@ export class CSSPlugin extends Plugin implements SDK.TargetManager.SDKModelObser override: [async(cx: CodeMirror.CompletionContext): Promise => { - return (await specificCssCompletion(cx, uiSourceCode, cssModel)) || cssCompletionSource(cx); + return await ((await specificCssCompletion(cx, uiSourceCode, cssModel)) || cssCompletionSource(cx)); }], }); } diff --git a/front_end/panels/sources/DebuggerPlugin.ts b/front_end/panels/sources/DebuggerPlugin.ts index c28ad838a7..d8cb82c423 100644 --- a/front_end/panels/sources/DebuggerPlugin.ts +++ b/front_end/panels/sources/DebuggerPlugin.ts @@ -205,7 +205,7 @@ export class DebuggerPlugin extends Plugin { private executionLocation: Workspace.UISourceCode.UILocation|null = null; // Track state of the control key because holding it makes debugger // target locations show up in the editor - private controlDown: boolean = false; + private controlDown = false; private controlTimeout: number|undefined = undefined; private sourceMapInfobar: UI.Infobar.Infobar|null = null; private readonly scriptsPanel: SourcesPanel; @@ -713,7 +713,7 @@ export class DebuggerPlugin extends Plugin { return { box, show: async (popover: UI.GlassPane.GlassPane) => { - let resolvedText: string = ''; + let resolvedText = ''; if (selectedCallFrame.script.isJavaScript()) { const nameMap = await SourceMapScopes.NamesResolver.allVariablesInCallFrame(selectedCallFrame); try { @@ -2509,20 +2509,20 @@ function lineNumberArrow(color: string, outline: string): string { encodeURIComponent(color)}" stroke="${encodeURIComponent(outline)}"/>') 1 3 1 1`; } -function inlineBreakpointArrow(color: string, outline: string, opacity: string = '1'): string { +function inlineBreakpointArrow(color: string, outline: string, opacity = '1'): string { return `url('data:image/svg+xml,')`; } -function inlineConditionalBreakpointArrow(color: string, outline: string, opacity: string = '1'): string { +function inlineConditionalBreakpointArrow(color: string, outline: string, opacity = '1'): string { return `url('data:image/svg+xml,')`; } -function inlineLogpointArrow(color: string, outline: string, opacity: string = '1'): string { +function inlineLogpointArrow(color: string, outline: string, opacity = '1'): string { return `url('data:image/svg+xml, { - return Promise.all(this.paints.map(paint => paint.picture())).then(pictures => { + return await Promise.all(this.paints.map(paint => paint.picture())).then(pictures => { const filteredPictures = (pictures.filter(picture => picture && rectsOverlap(picture.rect, targetRect)) as Array<{ rect: number[], serializedPicture: string, diff --git a/front_end/panels/timeline/components/FieldSettingsDialog.ts b/front_end/panels/timeline/components/FieldSettingsDialog.ts index f8d78f8543..4bd512ffbc 100644 --- a/front_end/panels/timeline/components/FieldSettingsDialog.ts +++ b/front_end/panels/timeline/components/FieldSettingsDialog.ts @@ -112,8 +112,8 @@ export class FieldSettingsDialog extends HTMLElement { #configSetting = CrUXManager.CrUXManager.instance().getConfigSetting(); - #urlOverride: string = ''; - #urlOverrideEnabled: boolean = false; + #urlOverride = ''; + #urlOverrideEnabled = false; #urlOverrideWarning = ''; #originMap?: OriginMap; diff --git a/front_end/panels/timeline/components/LiveMetricsView.ts b/front_end/panels/timeline/components/LiveMetricsView.ts index 433b1c00e9..3707847121 100644 --- a/front_end/panels/timeline/components/LiveMetricsView.ts +++ b/front_end/panels/timeline/components/LiveMetricsView.ts @@ -300,7 +300,7 @@ const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class LiveMetricsView extends LegacyWrapper.LegacyWrapper.WrappableComponent { readonly #shadow = this.attachShadow({mode: 'open'}); - #isNode: boolean = false; + #isNode = false; #lcpValue?: LiveMetrics.LcpValue; #clsValue?: LiveMetrics.ClsValue; diff --git a/front_end/panels/timeline/components/insights/CLSCulprits.ts b/front_end/panels/timeline/components/insights/CLSCulprits.ts index cf7b0f0cdb..bf2cdbc2b2 100644 --- a/front_end/panels/timeline/components/insights/CLSCulprits.ts +++ b/front_end/panels/timeline/components/insights/CLSCulprits.ts @@ -17,7 +17,7 @@ const {html} = Lit; export class CLSCulprits extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-cls-culprits`; - override internalName: string = 'cls-culprits'; + override internalName = 'cls-culprits'; override createOverlays(): Overlays.Overlays.TimelineOverlay[] { const clustersByScore = diff --git a/front_end/panels/timeline/components/insights/DOMSize.ts b/front_end/panels/timeline/components/insights/DOMSize.ts index ebfd541b62..e122686adf 100644 --- a/front_end/panels/timeline/components/insights/DOMSize.ts +++ b/front_end/panels/timeline/components/insights/DOMSize.ts @@ -21,7 +21,7 @@ const {html} = Lit; export class DOMSize extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-dom-size`; - override internalName: string = 'dom-size'; + override internalName = 'dom-size'; override createOverlays(): Overlays.Overlays.TimelineOverlay[] { if (!this.model) { diff --git a/front_end/panels/timeline/components/insights/DocumentLatency.ts b/front_end/panels/timeline/components/insights/DocumentLatency.ts index a527e6cbdf..677795dfdc 100644 --- a/front_end/panels/timeline/components/insights/DocumentLatency.ts +++ b/front_end/panels/timeline/components/insights/DocumentLatency.ts @@ -17,7 +17,7 @@ const {html} = Lit; export class DocumentLatency extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-document-latency`; - override internalName: string = 'document-latency'; + override internalName = 'document-latency'; override createOverlays(): Overlays.Overlays.TimelineOverlay[] { if (!this.model?.data?.documentRequest) { diff --git a/front_end/panels/timeline/components/insights/FontDisplay.ts b/front_end/panels/timeline/components/insights/FontDisplay.ts index edfb7d6bbd..7784ef0f7b 100644 --- a/front_end/panels/timeline/components/insights/FontDisplay.ts +++ b/front_end/panels/timeline/components/insights/FontDisplay.ts @@ -20,7 +20,7 @@ const {html} = Lit; export class FontDisplay extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-font-display`; - override internalName: string = 'font-display'; + override internalName = 'font-display'; #overlayForRequest = new Map(); diff --git a/front_end/panels/timeline/components/insights/ForcedReflow.ts b/front_end/panels/timeline/components/insights/ForcedReflow.ts index 74ded4a80d..f28574145d 100644 --- a/front_end/panels/timeline/components/insights/ForcedReflow.ts +++ b/front_end/panels/timeline/components/insights/ForcedReflow.ts @@ -22,7 +22,7 @@ const {html} = Lit; export class ForcedReflow extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-forced-reflow`; - override internalName: string = 'forced-reflow'; + override internalName = 'forced-reflow'; #linkifyUrl(callFrame: Trace.Types.Events.CallFrame|Protocol.Runtime.CallFrame): Lit.LitTemplate { const linkifier = new LegacyComponents.Linkifier.Linkifier(); diff --git a/front_end/panels/timeline/components/insights/ImageDelivery.ts b/front_end/panels/timeline/components/insights/ImageDelivery.ts index bcc61ee5ed..cbbb58e7ae 100644 --- a/front_end/panels/timeline/components/insights/ImageDelivery.ts +++ b/front_end/panels/timeline/components/insights/ImageDelivery.ts @@ -22,7 +22,7 @@ const MAX_REQUESTS = 10; export class ImageDelivery extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-image-delivery`; - override internalName: string = 'image-delivery'; + override internalName = 'image-delivery'; override createOverlays(): Overlays.Overlays.TimelineOverlay[] { if (!this.model) { diff --git a/front_end/panels/timeline/components/insights/InteractionToNextPaint.ts b/front_end/panels/timeline/components/insights/InteractionToNextPaint.ts index 842bedb889..ca6023fae8 100644 --- a/front_end/panels/timeline/components/insights/InteractionToNextPaint.ts +++ b/front_end/panels/timeline/components/insights/InteractionToNextPaint.ts @@ -19,7 +19,7 @@ const {html} = Lit; export class InteractionToNextPaint extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-inp`; - override internalName: string = 'inp'; + override internalName = 'inp'; override createOverlays(): Overlays.Overlays.TimelineOverlay[] { if (!this.model) { diff --git a/front_end/panels/timeline/components/insights/LCPDiscovery.ts b/front_end/panels/timeline/components/insights/LCPDiscovery.ts index 4a46aacf14..e87b41f9ad 100644 --- a/front_end/panels/timeline/components/insights/LCPDiscovery.ts +++ b/front_end/panels/timeline/components/insights/LCPDiscovery.ts @@ -61,7 +61,7 @@ function getImageData(model: LCPDiscoveryInsightModel): LCPImageDiscoveryData|nu export class LCPDiscovery extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-lcp-discovery`; - override internalName: string = 'lcp-discovery'; + override internalName = 'lcp-discovery'; #renderDiscoveryDelay(delay: Trace.Types.Timing.Micro): Element { const timeWrapper = document.createElement('span'); diff --git a/front_end/panels/timeline/components/insights/LCPPhases.ts b/front_end/panels/timeline/components/insights/LCPPhases.ts index 298e45fd13..e14c6eadbb 100644 --- a/front_end/panels/timeline/components/insights/LCPPhases.ts +++ b/front_end/panels/timeline/components/insights/LCPPhases.ts @@ -24,7 +24,7 @@ interface PhaseData { export class LCPPhases extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-lcp-by-phases`; - override internalName: string = 'lcp-by-phase'; + override internalName = 'lcp-by-phase'; #overlay: Overlays.Overlays.TimespanBreakdown|null = null; #getPhaseData(): PhaseData[] { diff --git a/front_end/panels/timeline/components/insights/NetworkDependencyTree.ts b/front_end/panels/timeline/components/insights/NetworkDependencyTree.ts index 33e7cc29d4..abb45ccad1 100644 --- a/front_end/panels/timeline/components/insights/NetworkDependencyTree.ts +++ b/front_end/panels/timeline/components/insights/NetworkDependencyTree.ts @@ -26,7 +26,7 @@ networkDependencyTreeInsightComponentStyles.replaceSync(networkDependencyTreeIns export class NetworkDependencyTree extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-long-critical-network-tree`; - override internalName: string = 'long-critical-network-tree'; + override internalName = 'long-critical-network-tree'; override connectedCallback(): void { super.connectedCallback(); diff --git a/front_end/panels/timeline/components/insights/NodeLink.ts b/front_end/panels/timeline/components/insights/NodeLink.ts index c4b4f6830d..31facadf4d 100644 --- a/front_end/panels/timeline/components/insights/NodeLink.ts +++ b/front_end/panels/timeline/components/insights/NodeLink.ts @@ -67,7 +67,7 @@ export class NodeLink extends HTMLElement { // TODO: it'd be nice if we could specify what attributes to render, // ex for the Viewport insight: (instead of just ) - return Common.Linkifier.Linkifier.linkify(node, this.#options); + return await Common.Linkifier.Linkifier.linkify(node, this.#options); } async #render(): Promise { diff --git a/front_end/panels/timeline/components/insights/RenderBlocking.ts b/front_end/panels/timeline/components/insights/RenderBlocking.ts index 9224db6f50..b9a9fef957 100644 --- a/front_end/panels/timeline/components/insights/RenderBlocking.ts +++ b/front_end/panels/timeline/components/insights/RenderBlocking.ts @@ -20,7 +20,7 @@ const {html} = Lit; export class RenderBlocking extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-render-blocking-requests`; - override internalName: string = 'render-blocking-requests'; + override internalName = 'render-blocking-requests'; override createOverlays(): Overlays.Overlays.TimelineOverlay[] { if (!this.model) { diff --git a/front_end/panels/timeline/components/insights/SlowCSSSelector.ts b/front_end/panels/timeline/components/insights/SlowCSSSelector.ts index 8e23ae9200..01f3fea95a 100644 --- a/front_end/panels/timeline/components/insights/SlowCSSSelector.ts +++ b/front_end/panels/timeline/components/insights/SlowCSSSelector.ts @@ -24,7 +24,7 @@ const {html} = Lit; export class SlowCSSSelector extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-slow-css-selector`; - override internalName: string = 'slow-css-selector'; + override internalName = 'slow-css-selector'; #selectorLocations = new Map(); override createOverlays(): Overlays.Overlays.TimelineOverlay[] { diff --git a/front_end/panels/timeline/components/insights/Table.ts b/front_end/panels/timeline/components/insights/Table.ts index ab1fa1ee5d..43061401f0 100644 --- a/front_end/panels/timeline/components/insights/Table.ts +++ b/front_end/panels/timeline/components/insights/Table.ts @@ -60,7 +60,7 @@ export class Table extends HTMLElement { #state?: TableState; #headers?: string[]; #rows?: TableDataRow[]; - #interactive: boolean = false; + #interactive = false; #currentHoverIndex: number|null = null; set data(data: TableData) { diff --git a/front_end/panels/timeline/components/insights/ThirdParties.ts b/front_end/panels/timeline/components/insights/ThirdParties.ts index bdb15d784b..01fca74112 100644 --- a/front_end/panels/timeline/components/insights/ThirdParties.ts +++ b/front_end/panels/timeline/components/insights/ThirdParties.ts @@ -19,7 +19,7 @@ const {html} = Lit; export class ThirdParties extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-third-parties`; - override internalName: string = 'third-parties'; + override internalName = 'third-parties'; #overlaysForEntity = new Map(); diff --git a/front_end/panels/timeline/components/insights/Viewport.ts b/front_end/panels/timeline/components/insights/Viewport.ts index 6eb64bba69..38a73145d7 100644 --- a/front_end/panels/timeline/components/insights/Viewport.ts +++ b/front_end/panels/timeline/components/insights/Viewport.ts @@ -15,7 +15,7 @@ const {html} = Lit; export class Viewport extends BaseInsightComponent { static override readonly litTagName = Lit.StaticHtml.literal`devtools-performance-viewport`; - override internalName: string = 'viewport'; + override internalName = 'viewport'; override createOverlays(): Overlays.Overlays.TimelineOverlay[] { // TODO(b/351757418): create overlay for synthetic input delay events diff --git a/front_end/panels/timeline/overlays/components/EntriesLinkOverlay.ts b/front_end/panels/timeline/overlays/components/EntriesLinkOverlay.ts index 2cbb8d9b2f..155db980ac 100644 --- a/front_end/panels/timeline/overlays/components/EntriesLinkOverlay.ts +++ b/front_end/panels/timeline/overlays/components/EntriesLinkOverlay.ts @@ -44,17 +44,17 @@ export class EntriesLinkOverlay extends HTMLElement { #entryToWrapper: HTMLElement|null = null; #entryFromConnector: SVGCircleElement|null = null; #entryToConnector: SVGCircleElement|null = null; - #entryFromVisible: boolean = true; - #entryToVisible: boolean = true; + #entryFromVisible = true; + #entryToVisible = true; #canvasRect: DOMRect|null = null; // These flags let us know if the entry we are drawing from/to are the // originals, or if they are the parent, which can happen if an entry is // collapsed. We care about this because if the entry is not the source, we // draw the border as dashed, not solid. - #fromEntryIsSource: boolean = true; - #toEntryIsSource: boolean = true; - #arrowHidden: boolean = false; + #fromEntryIsSource = true; + #toEntryIsSource = true; + #arrowHidden = false; #linkState: Trace.Types.File.EntriesLinkState; constructor( diff --git a/front_end/panels/timeline/overlays/components/EntryLabelOverlay.ts b/front_end/panels/timeline/overlays/components/EntryLabelOverlay.ts index 5fa2dd1aa0..74ea16ddd2 100644 --- a/front_end/panels/timeline/overlays/components/EntryLabelOverlay.ts +++ b/front_end/panels/timeline/overlays/components/EntryLabelOverlay.ts @@ -66,11 +66,11 @@ export class EntryLabelOverlay extends HTMLElement { // can fire, and that triggers a second removal. So we set this flag after // the first removal to avoid a duplicate event firing which is a no-op but // causes errors when we try to delete an already deleted annotation. - #isPendingRemoval: boolean = false; + #isPendingRemoval = false; // The label is set to editable when it is double clicked. If the user clicks away from the label box // element, the label is set to not editable until it double clicked.s - #isLabelEditable: boolean = true; + #isLabelEditable = true; #entryLabelVisibleHeight: number|null = null; #labelPartsWrapper: HTMLElement|null = null; @@ -99,7 +99,7 @@ export class EntryLabelOverlay extends HTMLElement { * Otherwise, the entry label overlay object only gets repositioned. */ - constructor(label: string, shouldDrawBelowEntry: boolean = false) { + constructor(label: string, shouldDrawBelowEntry = false) { super(); this.#render(); this.#shouldDrawBelowEntry = shouldDrawBelowEntry; diff --git a/front_end/panels/timeline/overlays/components/TimeRangeOverlay.ts b/front_end/panels/timeline/overlays/components/TimeRangeOverlay.ts index 80d3286820..8ab37e9748 100644 --- a/front_end/panels/timeline/overlays/components/TimeRangeOverlay.ts +++ b/front_end/panels/timeline/overlays/components/TimeRangeOverlay.ts @@ -47,7 +47,7 @@ export class TimeRangeOverlay extends HTMLElement { // The label is set to editable and in focus anytime the label is empty and when the label it is double clicked. // If the user clicks away from the selected range element and the label is not empty, the label is set to not editable until it is double clicked. - #isLabelEditable: boolean = true; + #isLabelEditable = true; #rangeContainer: HTMLElement|null = null; #labelBox: HTMLElement|null = null; diff --git a/front_end/panels/timeline/utils/ImageCache.test.ts b/front_end/panels/timeline/utils/ImageCache.test.ts index 649c94cbbe..c453e87c13 100644 --- a/front_end/panels/timeline/utils/ImageCache.test.ts +++ b/front_end/panels/timeline/utils/ImageCache.test.ts @@ -78,7 +78,7 @@ describe('ImageCache', () => { }, {once: true}); assert.isNull(getOrQueue(syntheticScreenshot1)); - return promise; + return await promise; }); it('getOrQueue should return null (immediately and eventually) for an invalid image', async () => { @@ -96,7 +96,7 @@ describe('ImageCache', () => { resolve(null); }, {once: true}); - return promise; + return await promise; }); it('preload should load all screenshots', async () => { diff --git a/front_end/panels/web_audio/WebAudioModel.ts b/front_end/panels/web_audio/WebAudioModel.ts index 01a885985d..97a41bb0c8 100644 --- a/front_end/panels/web_audio/WebAudioModel.ts +++ b/front_end/panels/web_audio/WebAudioModel.ts @@ -40,7 +40,7 @@ export class WebAudioModel extends SDK.SDKModel.SDKModel implements override async resumeModel(): Promise { if (!this.enabled) { - return Promise.resolve(); + return await Promise.resolve(); } await this.agent.invoke_enable(); } diff --git a/front_end/panels/webauthn/WebauthnPane.ts b/front_end/panels/webauthn/WebauthnPane.ts index 386c32ed12..d1c240acee 100644 --- a/front_end/panels/webauthn/WebauthnPane.ts +++ b/front_end/panels/webauthn/WebauthnPane.ts @@ -768,7 +768,7 @@ export class WebauthnPaneImpl extends UI.Widget.VBox implements return; } - // @ts-ignore dataGrid node type is indeterminate. + // @ts-expect-error dataGrid node type is indeterminate. dataGrid.rootNode() .children.find((n: DataGrid.DataGrid.DataGridNode) => n.data.credentialId === credentialId) .remove(); diff --git a/front_end/panels/whats_new/ReleaseNoteView.ts b/front_end/panels/whats_new/ReleaseNoteView.ts index 9f1917c854..cf88a712ef 100644 --- a/front_end/panels/whats_new/ReleaseNoteView.ts +++ b/front_end/panels/whats_new/ReleaseNoteView.ts @@ -116,7 +116,7 @@ export class ReleaseNoteView extends UI.Widget.VBox { const url = new URL('./resources/WNDT.md', import.meta.url); try { const response = await fetch(url.toString()); - return response.text(); + return await response.text(); } catch { throw new Error(`Markdown file ${ url.toString()} not found. Make sure it is correctly listed in the relevant BUILD.gn files.`); diff --git a/front_end/panels/whats_new/WhatsNewImpl.ts b/front_end/panels/whats_new/WhatsNewImpl.ts index aac948fc0f..a034097b3f 100644 --- a/front_end/panels/whats_new/WhatsNewImpl.ts +++ b/front_end/panels/whats_new/WhatsNewImpl.ts @@ -11,7 +11,7 @@ import {getReleaseNote} from './ReleaseNoteText.js'; export const releaseVersionSeen = 'releaseNoteVersionSeen'; -export const releaseNoteViewId: string = 'release-note'; +export const releaseNoteViewId = 'release-note'; let releaseNoteVersionSetting: Common.Settings.Setting; diff --git a/front_end/testing/DOMHelpers.ts b/front_end/testing/DOMHelpers.ts index 09e6b33464..4207bfd90c 100644 --- a/front_end/testing/DOMHelpers.ts +++ b/front_end/testing/DOMHelpers.ts @@ -248,11 +248,11 @@ export function getEventPromise(element: HTMLElement, eventName } export async function doubleRaf() { - return new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); + return await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))); } export async function raf() { - return new Promise(resolve => requestAnimationFrame(resolve)); + return await new Promise(resolve => requestAnimationFrame(resolve)); } /** diff --git a/front_end/testing/MockConnection.ts b/front_end/testing/MockConnection.ts index 1864531c40..a9d760a7e4 100644 --- a/front_end/testing/MockConnection.ts +++ b/front_end/testing/MockConnection.ts @@ -134,7 +134,7 @@ async function disable() { throw new Error('MockConnection still has pending listeners. All promises should be awaited.'); } await deinitializeGlobalVars(); - // @ts-ignore Setting back to undefined as a hard reset. + // @ts-expect-error Setting back to undefined as a hard reset. ProtocolClient.InspectorBackend.Connection.setFactory(undefined); } diff --git a/front_end/testing/MockScopeChain.ts b/front_end/testing/MockScopeChain.ts index c6788330d1..9b0ca68596 100644 --- a/front_end/testing/MockScopeChain.ts +++ b/front_end/testing/MockScopeChain.ts @@ -56,7 +56,7 @@ export class MockProtocolBackend { } dispatchDebuggerPause( - script: SDK.Script.Script, reason: Protocol.Debugger.PausedEventReason, functionName: string = '', + script: SDK.Script.Script, reason: Protocol.Debugger.PausedEventReason, functionName = '', scopeChain: Protocol.Debugger.Scope[] = []): void { const target = script.debuggerModel.target(); if (reason === Protocol.Debugger.PausedEventReason.Instrumentation) { diff --git a/front_end/testing/MutationHelpers.ts b/front_end/testing/MutationHelpers.ts index d89736baa1..cb53eb7a42 100644 --- a/front_end/testing/MutationHelpers.ts +++ b/front_end/testing/MutationHelpers.ts @@ -240,7 +240,7 @@ export const withNoMutations = async(element: T, fn: (shadowRoot }; export const someMutations = async(element: T) => { - return new Promise(resolve => { + return await new Promise(resolve => { const observer = new MutationObserver(() => { resolve(); observer.disconnect(); diff --git a/front_end/testing/ResourceTreeHelpers.ts b/front_end/testing/ResourceTreeHelpers.ts index 20666432bc..80eff6957d 100644 --- a/front_end/testing/ResourceTreeHelpers.ts +++ b/front_end/testing/ResourceTreeHelpers.ts @@ -55,7 +55,7 @@ export async function getInitializedResourceTreeModel(target: SDK.Target.Target) const resourceTreeModel = target.model(SDK.ResourceTreeModel.ResourceTreeModel)!; return resourceTreeModel.cachedResourcesLoaded() ? resourceTreeModel : - resourceTreeModel.once(SDK.ResourceTreeModel.Events.CachedResourcesLoaded); + await resourceTreeModel.once(SDK.ResourceTreeModel.Events.CachedResourcesLoaded); } function getEffectivePayload( diff --git a/front_end/testing/TraceHelpers.ts b/front_end/testing/TraceHelpers.ts index a8a1613589..ea9f90efda 100644 --- a/front_end/testing/TraceHelpers.ts +++ b/front_end/testing/TraceHelpers.ts @@ -200,8 +200,7 @@ export function prettyPrint( tree: Trace.Helpers.TreeHelpers.TraceEntryTree, predicate: (node: Trace.Helpers.TreeHelpers.TraceEntryNode, event: Trace.Types.Events.Event) => boolean = () => true, - indentation: number = 2, delimiter: string = ' ', prefix: string = '-', newline: string = '\n', - out: string = ''): string { + indentation = 2, delimiter = ' ', prefix = '-', newline = '\n', out = ''): string { let skipped = false; return printNodes(tree.roots); function printNodes(nodes: Set| @@ -231,8 +230,7 @@ export function prettyPrint( * Builds a mock Complete. */ export function makeCompleteEvent( - name: string, ts: number, dur: number, cat: string = '*', pid: number = 0, - tid: number = 0): Trace.Types.Events.Complete { + name: string, ts: number, dur: number, cat = '*', pid = 0, tid = 0): Trace.Types.Events.Complete { return { args: {}, cat, @@ -248,8 +246,8 @@ export function makeCompleteEvent( export function makeAsyncStartEvent( name: string, ts: number, - pid: number = 0, - tid: number = 0, + pid = 0, + tid = 0, ): Trace.Types.Events.Async { return { args: {}, @@ -264,8 +262,8 @@ export function makeAsyncStartEvent( export function makeAsyncEndEvent( name: string, ts: number, - pid: number = 0, - tid: number = 0, + pid = 0, + tid = 0, ): Trace.Types.Events.Async { return { args: {}, @@ -282,9 +280,9 @@ export function makeAsyncEndEvent( * Builds a mock flow phase event. */ export function makeFlowPhaseEvent( - name: string, ts: number, cat: string = '*', + name: string, ts: number, cat = '*', ph: Trace.Types.Events.Phase.FLOW_START|Trace.Types.Events.Phase.FLOW_END|Trace.Types.Events.Phase.FLOW_STEP, - id: number = 0, pid: number = 0, tid: number = 0): Trace.Types.Events.FlowEvent { + id = 0, pid = 0, tid = 0): Trace.Types.Events.FlowEvent { return { args: {}, cat, @@ -302,7 +300,7 @@ export function makeFlowPhaseEvent( * Builds flow phase events for a list of events belonging to the same * flow. `events` must be ordered. */ -export function makeFlowEvents(events: Trace.Types.Events.Event[], flowId: number = 0): Trace.Types.Events.FlowEvent[] { +export function makeFlowEvents(events: Trace.Types.Events.Event[], flowId = 0): Trace.Types.Events.FlowEvent[] { const lastEvent = events.at(-1); const firstEvent = events.at(0); if (!lastEvent || !firstEvent) { @@ -328,7 +326,7 @@ export function makeFlowEvents(events: Trace.Types.Events.Event[], flowId: numbe * Builds a mock Instant. */ export function makeInstantEvent( - name: string, tsMicroseconds: number, cat: string = '', pid: number = 0, tid: number = 0, + name: string, tsMicroseconds: number, cat = '', pid = 0, tid = 0, s: Trace.Types.Events.Scope = Trace.Types.Events.Scope.THREAD): Trace.Types.Events.Instant { return { args: {}, @@ -345,8 +343,7 @@ export function makeInstantEvent( /** * Builds a mock Begin. */ -export function makeBeginEvent( - name: string, ts: number, cat: string = '*', pid: number = 0, tid: number = 0): Trace.Types.Events.Begin { +export function makeBeginEvent(name: string, ts: number, cat = '*', pid = 0, tid = 0): Trace.Types.Events.Begin { return { args: {}, cat, @@ -361,8 +358,7 @@ export function makeBeginEvent( /** * Builds a mock End. */ -export function makeEndEvent( - name: string, ts: number, cat: string = '*', pid: number = 0, tid: number = 0): Trace.Types.Events.End { +export function makeEndEvent(name: string, ts: number, cat = '*', pid = 0, tid = 0): Trace.Types.Events.End { return { args: {}, cat, @@ -375,8 +371,8 @@ export function makeEndEvent( } export function makeProfileCall( - functionName: string, tsUs: number, durUs: number, pid: number = 0, tid: number = 0, nodeId: number = 0, - url: string = ''): Trace.Types.Events.SyntheticProfileCall { + functionName: string, tsUs: number, durUs: number, pid = 0, tid = 0, nodeId = 0, + url = ''): Trace.Types.Events.SyntheticProfileCall { return { cat: '', name: 'ProfileCall', @@ -404,8 +400,8 @@ export const DevToolsTimelineCategory = 'disabled-by-default-devtools.timeline'; * Mocks an object compatible with the return type of the * RendererHandler using only an array of ordered entries. */ -export function makeMockRendererHandlerData(entries: Trace.Types.Events.Event[], pid: number = 1, tid: number = 1): - Trace.Handlers.ModelHandlers.Renderer.RendererHandlerData { +export function makeMockRendererHandlerData( + entries: Trace.Types.Events.Event[], pid = 1, tid = 1): Trace.Handlers.ModelHandlers.Renderer.RendererHandlerData { const {tree, entryToNode} = Trace.Helpers.TreeHelpers.treify(entries, {filter: {has: () => true}}); const mockThread: Trace.Handlers.ModelHandlers.Renderer.RendererThread = { tree, diff --git a/front_end/testing/TraceLoader.ts b/front_end/testing/TraceLoader.ts index b148801927..0c7155e585 100644 --- a/front_end/testing/TraceLoader.ts +++ b/front_end/testing/TraceLoader.ts @@ -212,7 +212,7 @@ export class TraceLoader { }> { const events = 'traceEvents' in contents ? contents.traceEvents : contents; const metadata = 'metadata' in contents ? contents.metadata : {}; - return new Promise((resolve, reject) => { + return await new Promise((resolve, reject) => { const model = Trace.TraceModel.Model.createWithAllHandlers(traceEngineConfig); model.addEventListener(Trace.TraceModel.ModelUpdateEvent.eventName, (event: Event) => { const {data} = event as Trace.TraceModel.ModelUpdateEvent; diff --git a/front_end/testing/UISourceCodeHelpers.ts b/front_end/testing/UISourceCodeHelpers.ts index ceacfe76f0..7eea15e42e 100644 --- a/front_end/testing/UISourceCodeHelpers.ts +++ b/front_end/testing/UISourceCodeHelpers.ts @@ -139,7 +139,7 @@ export function createFileSystemUISourceCode(options: { return {uiSourceCode, project}; } -export function setupMockedUISourceCode(url: string = 'https://example.com/') { +export function setupMockedUISourceCode(url = 'https://example.com/') { const projectStub = sinon.createStubInstance(Bindings.ContentProviderBasedProject.ContentProviderBasedProject); const urlStringTagExample = urlString`${url}`; const contentTypeStub = sinon.createStubInstance(Common.ResourceType.ResourceType); diff --git a/front_end/ui/components/chrome_link/ChromeLink.ts b/front_end/ui/components/chrome_link/ChromeLink.ts index 68581db78a..7967393bc3 100644 --- a/front_end/ui/components/chrome_link/ChromeLink.ts +++ b/front_end/ui/components/chrome_link/ChromeLink.ts @@ -23,7 +23,7 @@ declare global { export class ChromeLink extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); readonly #boundRender = this.#render.bind(this); - #href: string = ''; + #href = ''; connectedCallback(): void { void ComponentHelpers.ScheduledRender.scheduleRender(this, this.#boundRender); diff --git a/front_end/ui/components/docs/tree_outline/lazy-children.ts b/front_end/ui/components/docs/tree_outline/lazy-children.ts index 36f0400869..8c1528d509 100644 --- a/front_end/ui/components/docs/tree_outline/lazy-children.ts +++ b/front_end/ui/components/docs/tree_outline/lazy-children.ts @@ -33,7 +33,7 @@ async function loadInSomeNodes(): Promise { + return await new Promise(resolve => { setTimeout(() => resolve(europeanOffices), 250); }); } diff --git a/front_end/ui/components/icon_button/IconButton.ts b/front_end/ui/components/icon_button/IconButton.ts index a0f2b3bd64..5ee9b2dc53 100644 --- a/front_end/ui/components/icon_button/IconButton.ts +++ b/front_end/ui/components/icon_button/IconButton.ts @@ -32,9 +32,9 @@ export class IconButton extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); #clickHandler: undefined|(() => void) = undefined; #groups: IconWithTextData[] = []; - #compact: boolean = false; - #leadingText: string = ''; - #trailingText: string = ''; + #compact = false; + #leadingText = ''; + #trailingText = ''; #accessibleName: string|undefined; set data(data: IconButtonData) { diff --git a/front_end/ui/components/issue_counter/IssueCounter.ts b/front_end/ui/components/issue_counter/IssueCounter.ts index c812163564..e8f70fb139 100644 --- a/front_end/ui/components/issue_counter/IssueCounter.ts +++ b/front_end/ui/components/issue_counter/IssueCounter.ts @@ -81,7 +81,7 @@ const listFormatter = (function defineFormatter() { })(); export function getIssueCountsEnumeration( - issuesManager: IssuesManager.IssuesManager.IssuesManager, omitEmpty: boolean = true): string { + issuesManager: IssuesManager.IssuesManager.IssuesManager, omitEmpty = true): string { const counts: [number, number, number] = [ issuesManager.numberOfIssues(IssuesManager.Issue.IssueKind.PAGE_ERROR), issuesManager.numberOfIssues(IssuesManager.Issue.IssueKind.BREAKING_CHANGE), @@ -99,7 +99,7 @@ export class IssueCounter extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); #clickHandler: undefined|(() => void) = undefined; #tooltipCallback: undefined|(() => void) = undefined; - #leadingText: string = ''; + #leadingText = ''; #throttler: undefined|Common.Throttler.Throttler; #counts: [number, number, number] = [0, 0, 0]; #displayMode: DisplayMode = DisplayMode.OMIT_EMPTY; diff --git a/front_end/ui/components/markdown_view/MarkdownLink.ts b/front_end/ui/components/markdown_view/MarkdownLink.ts index 3143b473be..ee4e283fd7 100644 --- a/front_end/ui/components/markdown_view/MarkdownLink.ts +++ b/front_end/ui/components/markdown_view/MarkdownLink.ts @@ -27,8 +27,8 @@ export interface MarkdownLinkData { export class MarkdownLink extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); - #linkText: string = ''; - #linkUrl: string = ''; + #linkText = ''; + #linkUrl = ''; connectedCallback(): void { this.#shadow.adoptedStyleSheets = [markdownLinkStyles]; diff --git a/front_end/ui/components/menus/SelectMenu.ts b/front_end/ui/components/menus/SelectMenu.ts index 11e506bafc..85b3e2d1c9 100644 --- a/front_end/ui/components/menus/SelectMenu.ts +++ b/front_end/ui/components/menus/SelectMenu.ts @@ -89,7 +89,7 @@ export class SelectMenu extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); readonly #renderBound = this.#render.bind(this); #button: SelectMenuButton|null = null; - #open: boolean = false; + #open = false; #props: SelectMenuData = { buttonTitle: '', position: Dialogs.Dialog.DialogVerticalPosition.BOTTOM, diff --git a/front_end/ui/components/node_text/NodeText.ts b/front_end/ui/components/node_text/NodeText.ts index 3ea514d2ee..b810c1ccc9 100644 --- a/front_end/ui/components/node_text/NodeText.ts +++ b/front_end/ui/components/node_text/NodeText.ts @@ -21,7 +21,7 @@ export interface NodeTextData { export class NodeText extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); - #nodeTitle: string = ''; + #nodeTitle = ''; #nodeId?: string = ''; #nodeClasses?: string[] = []; diff --git a/front_end/ui/components/panel_feedback/PreviewToggle.ts b/front_end/ui/components/panel_feedback/PreviewToggle.ts index 6ebae9ee5b..670e00cc40 100644 --- a/front_end/ui/components/panel_feedback/PreviewToggle.ts +++ b/front_end/ui/components/panel_feedback/PreviewToggle.ts @@ -49,7 +49,7 @@ export class PreviewToggle extends HTMLElement { #helperText: string|null = null; #feedbackURL: string|null = null; #learnMoreURL: string|undefined; - #experiment: string = ''; + #experiment = ''; #onChangeCallback?: (checked: boolean) => void; connectedCallback(): void { diff --git a/front_end/ui/components/render_coordinator/render_coordinator.test.ts b/front_end/ui/components/render_coordinator/render_coordinator.test.ts index b9e64fae59..f47f69701f 100644 --- a/front_end/ui/components/render_coordinator/render_coordinator.test.ts +++ b/front_end/ui/components/render_coordinator/render_coordinator.test.ts @@ -128,7 +128,7 @@ describe('RenderCoordinator', () => { }, timeout)); }; - void RenderCoordinator.write(async () => delayedSet(expected, 100)); + void RenderCoordinator.write(async () => await delayedSet(expected, 100)); await RenderCoordinator.done(); assert.strictEqual(targetValue, expected); diff --git a/front_end/ui/components/render_coordinator/render_coordinator.ts b/front_end/ui/components/render_coordinator/render_coordinator.ts index 20bd5bd00d..629c420824 100644 --- a/front_end/ui/components/render_coordinator/render_coordinator.ts +++ b/front_end/ui/components/render_coordinator/render_coordinator.ts @@ -116,10 +116,10 @@ export async function read( if (!callback) { throw new Error('Read called with label but no callback'); } - return enqueueHandler(ACTION.READ, labelOrCallback, callback); + return await enqueueHandler(ACTION.READ, labelOrCallback, callback); } - return enqueueHandler(ACTION.READ, UNNAMED_READ, labelOrCallback); + return await enqueueHandler(ACTION.READ, UNNAMED_READ, labelOrCallback); } /** @@ -136,10 +136,10 @@ export async function write( if (!callback) { throw new Error('Write called with label but no callback'); } - return enqueueHandler(ACTION.WRITE, labelOrCallback, callback); + return await enqueueHandler(ACTION.WRITE, labelOrCallback, callback); } - return enqueueHandler(ACTION.WRITE, UNNAMED_WRITE, labelOrCallback); + return await enqueueHandler(ACTION.WRITE, UNNAMED_WRITE, labelOrCallback); } export function takeLoggingRecords(): LoggingRecord[] { @@ -164,10 +164,10 @@ export async function scroll( if (!callback) { throw new Error('Scroll called with label but no callback'); } - return enqueueHandler(ACTION.READ, labelOrCallback, callback); + return await enqueueHandler(ACTION.READ, labelOrCallback, callback); } - return enqueueHandler(ACTION.READ, UNNAMED_SCROLL, labelOrCallback); + return await enqueueHandler(ACTION.READ, UNNAMED_SCROLL, labelOrCallback); } function enqueueHandler(action: ACTION, label: string, callback: CoordinatorCallback): Promise { diff --git a/front_end/ui/components/report_view/ReportView.ts b/front_end/ui/components/report_view/ReportView.ts index 0cd069b8bf..00e54a01b8 100644 --- a/front_end/ui/components/report_view/ReportView.ts +++ b/front_end/ui/components/report_view/ReportView.ts @@ -59,7 +59,7 @@ export interface ReportData { } export class Report extends HTMLElement { readonly #shadow = this.attachShadow({mode: 'open'}); - #reportTitle: string = ''; + #reportTitle = ''; set data({reportTitle}: ReportData) { this.#reportTitle = reportTitle; diff --git a/front_end/ui/components/request_link_icon/RequestLinkIcon.test.ts b/front_end/ui/components/request_link_icon/RequestLinkIcon.test.ts index 5bd6a10168..57bf100726 100644 --- a/front_end/ui/components/request_link_icon/RequestLinkIcon.test.ts +++ b/front_end/ui/components/request_link_icon/RequestLinkIcon.test.ts @@ -261,7 +261,7 @@ describeWithEnvironment('RequestLinkIcon', () => { before(() => { UI.ViewManager.resetViewRegistration(); UI.ViewManager.registerViewExtension({ - // @ts-ignore + // @ts-expect-error location: 'mock-location', id: 'network', title: () => 'Network' as Platform.UIString.LocalizedString, diff --git a/front_end/ui/components/request_link_icon/RequestLinkIcon.ts b/front_end/ui/components/request_link_icon/RequestLinkIcon.ts index fed1624c14..af91c30325 100644 --- a/front_end/ui/components/request_link_icon/RequestLinkIcon.ts +++ b/front_end/ui/components/request_link_icon/RequestLinkIcon.ts @@ -70,7 +70,7 @@ export class RequestLinkIcon extends HTMLElement { #request?: SDK.NetworkRequest.NetworkRequest|null; #highlightHeader?: {section: NetworkForward.UIRequestLocation.UIHeaderSection, name: string}; #requestResolver?: Logs.RequestResolver.RequestResolver; - #displayURL: boolean = false; + #displayURL = false; #urlToDisplay?: string; #networkTab?: NetworkForward.UIRequestLocation.UIRequestTabs; #affectedRequest?: {requestId?: Protocol.Network.RequestId, url?: string}; @@ -180,7 +180,7 @@ export class RequestLinkIcon extends HTMLElement { } async #render(): Promise { - return RenderCoordinator.write(() => { + return await RenderCoordinator.write(() => { // By default we render just the URL for the request link. If we also know // the concrete network request, or at least its request ID, we surround // the URL with a button, that opens the request in the Network panel. diff --git a/front_end/ui/components/text_editor/AutocompleteHistory.ts b/front_end/ui/components/text_editor/AutocompleteHistory.ts index cce9f3d297..dbd5e4f34f 100644 --- a/front_end/ui/components/text_editor/AutocompleteHistory.ts +++ b/front_end/ui/components/text_editor/AutocompleteHistory.ts @@ -17,8 +17,8 @@ export class AutocompleteHistory { #data: string[] = []; /** 1-based entry in the history stack. */ - #historyOffset: number = 1; - #uncommittedIsTop: boolean = false; + #historyOffset = 1; + #uncommittedIsTop = false; /** * Creates a new settings-backed history. The class assumes it has sole diff --git a/front_end/ui/components/text_editor/TextEditor.test.ts b/front_end/ui/components/text_editor/TextEditor.test.ts index d82fc03181..1041d5dc6d 100644 --- a/front_end/ui/components/text_editor/TextEditor.test.ts +++ b/front_end/ui/components/text_editor/TextEditor.test.ts @@ -142,7 +142,7 @@ describeWithEnvironment('TextEditor', () => { code: string, pos: number, type?: TextEditor.JavaScript.QueryType, - range: string = '', + range = '', related?: string, ): Promise { const state = makeState(code, CodeMirror.javascript.javascriptLanguage); diff --git a/front_end/ui/components/text_editor/TextEditor.ts b/front_end/ui/components/text_editor/TextEditor.ts index 7a5cdb1a06..7214bada6d 100644 --- a/front_end/ui/components/text_editor/TextEditor.ts +++ b/front_end/ui/components/text_editor/TextEditor.ts @@ -182,7 +182,7 @@ export class TextEditor extends HTMLElement { } } - revealPosition(selection: CodeMirror.EditorSelection, highlight: boolean = true): void { + revealPosition(selection: CodeMirror.EditorSelection, highlight = true): void { const view = this.#activeEditor; if (!view) { return; diff --git a/front_end/ui/components/text_editor/javascript.ts b/front_end/ui/components/text_editor/javascript.ts index 209f1c34ea..620fac1508 100644 --- a/front_end/ui/components/text_editor/javascript.ts +++ b/front_end/ui/components/text_editor/javascript.ts @@ -18,7 +18,7 @@ export function completion(): CodeMirror.Extension { } export async function completeInContext( - textBefore: string, query: string, force: boolean = false): Promise { + textBefore: string, query: string, force = false): Promise { const state = CodeMirror.EditorState.create({ doc: textBefore + query, selection: {anchor: textBefore.length}, @@ -330,13 +330,13 @@ async function maybeCompleteKeysFromMap(objectVariable: string): Promise { const cache = PropertyCache.instance(); if (!quoted) { const cached = cache.get(expression); if (cached) { - return cached; + return await cached; } } const context = getExecutionContext(); @@ -347,14 +347,14 @@ async function completeProperties( if (!quoted) { cache.set(expression, result); } - return result; + return await result; } async function completePropertiesInner( expression: string, context: SDK.RuntimeModel.ExecutionContext, quoted?: string, - hasBracket: boolean = false, + hasBracket = false, ): Promise { const result = new CompletionSet(); if (!context) { @@ -425,7 +425,7 @@ async function completeExpressionGlobal(): Promise { const cache = PropertyCache.instance(); const cached = cache.get(''); if (cached) { - return cached; + return await cached; } const context = getExecutionContext(); @@ -446,7 +446,7 @@ async function completeExpressionGlobal(): Promise { }); }); cache.set('', fetchNames); - return fetchNames; + return await fetchNames; } export async function isExpressionComplete(expression: string): Promise { @@ -528,9 +528,9 @@ async function getArgumentsForExpression( if (!first || callee.name !== 'MemberExpression') { return null; } - return evaluateExpression(context, doc.sliceString(first.from, first.to), 'argumentsHint'); + return await evaluateExpression(context, doc.sliceString(first.from, first.to), 'argumentsHint'); }; - return getArgumentsForFunctionValue(result, objGetter, expression) + return await getArgumentsForFunctionValue(result, objGetter, expression) .finally(() => context.runtimeModel.releaseObjectGroup('argumentsHint')); } diff --git a/front_end/ui/components/tree_outline/TreeOutline.ts b/front_end/ui/components/tree_outline/TreeOutline.ts index c635dca7fd..e661dd29a7 100644 --- a/front_end/ui/components/tree_outline/TreeOutline.ts +++ b/front_end/ui/components/tree_outline/TreeOutline.ts @@ -187,7 +187,7 @@ export class TreeOutline extends HTMLElement { * Takes a TreeNode, expands the outline to reveal it, and focuses it. */ async expandToAndSelectTreeNode(targetTreeNode: TreeNode): Promise { - return this.expandToAndSelectTreeNodeId(targetTreeNode.id); + return await this.expandToAndSelectTreeNodeId(targetTreeNode.id); } /** @@ -546,7 +546,7 @@ export class TreeOutline extends HTMLElement { // to ensure we're not rendering any stale UI. if (this.#enqueuedRender) { this.#enqueuedRender = false; - return this.#render(); + return await this.#render(); } } } diff --git a/front_end/ui/legacy/ContextMenu.ts b/front_end/ui/legacy/ContextMenu.ts index 678697900a..89ee6a951c 100644 --- a/front_end/ui/legacy/ContextMenu.ts +++ b/front_end/ui/legacy/ContextMenu.ts @@ -410,7 +410,7 @@ export class SubMenu extends Item { } } - private static uniqueSectionName: number = 0; + private static uniqueSectionName = 0; } export interface ContextMenuOptions { diff --git a/front_end/ui/legacy/Geometry.ts b/front_end/ui/legacy/Geometry.ts index 1b0e3e7263..bd0210ef5e 100644 --- a/front_end/ui/legacy/Geometry.ts +++ b/front_end/ui/legacy/Geometry.ts @@ -29,7 +29,7 @@ */ import * as SDK from '../../core/sdk/sdk.js'; -const EPS: number = 1e-5; +const EPS = 1e-5; export class Vector { x: number; diff --git a/front_end/ui/legacy/GlassPane.ts b/front_end/ui/legacy/GlassPane.ts index a68e73f6f0..c61f02b8ad 100644 --- a/front_end/ui/legacy/GlassPane.ts +++ b/front_end/ui/legacy/GlassPane.ts @@ -23,7 +23,7 @@ export class GlassPane { private anchorBehavior: AnchorBehavior; private sizeBehavior: SizeBehavior; private marginBehavior: MarginBehavior; - #ignoreLeftMargin: boolean = false; + #ignoreLeftMargin = false; constructor(jslog?: string) { this.widgetInternal = new Widget(true); diff --git a/front_end/ui/legacy/InspectorView.ts b/front_end/ui/legacy/InspectorView.ts index 904674f3b6..56dd2387f6 100644 --- a/front_end/ui/legacy/InspectorView.ts +++ b/front_end/ui/legacy/InspectorView.ts @@ -313,7 +313,7 @@ export class InspectorView extends VBox implements ViewLocationResolver { if (!view) { throw new Error(`Expected view for panel '${panelName}'`); } - return view.widget() as Promise; + return await (view.widget() as Promise); } onSuspendStateChanged(allTargetsSuspended: boolean): void { diff --git a/front_end/ui/legacy/KeyboardShortcut.ts b/front_end/ui/legacy/KeyboardShortcut.ts index 262c7e861b..2a0c38abc6 100644 --- a/front_end/ui/legacy/KeyboardShortcut.ts +++ b/front_end/ui/legacy/KeyboardShortcut.ts @@ -118,7 +118,7 @@ export class KeyboardShortcut { } // Use either a real or a synthetic keyCode (for events originating from extensions). - // @ts-ignore ExtensionServer.js installs '__keyCode' on some events. + // @ts-expect-error ExtensionServer.js installs '__keyCode' on some events. const keyCode = keyboardEvent.keyCode || keyboardEvent['__keyCode']; return KeyboardShortcut.makeKeyFromCodeAndModifiers(keyCode, modifiers); } diff --git a/front_end/ui/legacy/ListWidget.ts b/front_end/ui/legacy/ListWidget.ts index 57948cd870..3351d7adc9 100644 --- a/front_end/ui/legacy/ListWidget.ts +++ b/front_end/ui/legacy/ListWidget.ts @@ -62,7 +62,7 @@ export class ListWidget extends VBox { private editElement: Element|null; private emptyPlaceholder: Element|null; private isTable: boolean; - constructor(delegate: Delegate, delegatesFocus: boolean|undefined = true, isTable: boolean = false) { + constructor(delegate: Delegate, delegatesFocus: boolean|undefined = true, isTable = false) { super(true, delegatesFocus); this.registerRequiredCSS(listWidgetStyles); this.delegate = delegate; diff --git a/front_end/ui/legacy/Panel.ts b/front_end/ui/legacy/Panel.ts index ef1844a3f3..b8d8456a2f 100644 --- a/front_end/ui/legacy/Panel.ts +++ b/front_end/ui/legacy/Panel.ts @@ -48,12 +48,12 @@ export class Panel extends VBox { this.element.classList.add(name); this.panelName = name; - // @ts-ignore: Legacy global. Requires rewriting tests to get rid of. + // @ts-expect-error: Legacy global. Requires rewriting tests to get rid of. // For testing. self.UI = self.UI || {}; - // @ts-ignore + // @ts-expect-error self.UI.panels = self.UI.panels || {}; - // @ts-ignore + // @ts-expect-error UI.panels[name] = this; } diff --git a/front_end/ui/legacy/ShortcutRegistry.ts b/front_end/ui/legacy/ShortcutRegistry.ts index b53bd5ce77..51b374a2ef 100644 --- a/front_end/ui/legacy/ShortcutRegistry.ts +++ b/front_end/ui/legacy/ShortcutRegistry.ts @@ -431,7 +431,7 @@ export class ShortcutTreeNode { private chordsInternal: Map; private readonly depth: number; - constructor(key: number, depth: number = 0) { + constructor(key: number, depth = 0) { this.keyInternal = key; this.actionsInternal = []; this.chordsInternal = new Map(); diff --git a/front_end/ui/legacy/SuggestBox.ts b/front_end/ui/legacy/SuggestBox.ts index dcd58ccbdb..7df63509e0 100644 --- a/front_end/ui/legacy/SuggestBox.ts +++ b/front_end/ui/legacy/SuggestBox.ts @@ -134,7 +134,7 @@ export class SuggestBox implements ListDelegate { return kMaxWidth; } let maxItem; - let maxLength: number = -Infinity; + let maxLength = -Infinity; for (let i = 0; i < items.length; i++) { const length = (items[i].title || items[i].text).length + (items[i].subtitle || '').length; if (length > maxLength) { diff --git a/front_end/ui/legacy/Toolbar.ts b/front_end/ui/legacy/Toolbar.ts index 4420c7994f..9e0c1131ef 100644 --- a/front_end/ui/legacy/Toolbar.ts +++ b/front_end/ui/legacy/Toolbar.ts @@ -85,7 +85,7 @@ const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export class Toolbar extends HTMLElement { #shadowRoot = this.attachShadow({mode: 'open'}); private items: ToolbarItem[] = []; - enabled: boolean = true; + enabled = true; private compactLayout = false; constructor() { @@ -492,7 +492,7 @@ export class ToolbarItem extends C } applyEnabledState(enabled: boolean): void { - // @ts-ignore: Ignoring in favor of an `instanceof` check for all the different + // @ts-expect-error: Ignoring in favor of an `instanceof` check for all the different // kind of HTMLElement classes that have a disabled attribute. this.element.disabled = !enabled; } @@ -531,7 +531,7 @@ export class ToolbarItemWithCompactLayout extends ToolbarItem { - constructor(text: string = '') { + constructor(text = '') { const element = document.createElement('div'); element.classList.add('toolbar-text'); super(element); @@ -943,7 +943,7 @@ export class ToolbarMenuButton extends ToolbarCombobox { private readonly contextMenuHandler: (arg0: ContextMenu) => void; private readonly useSoftMenu: boolean; private triggerTimeoutId?: number; - #triggerDelay: number = 200; + #triggerDelay = 200; constructor( contextMenuHandler: (arg0: ContextMenu) => void, isIconDropdown?: boolean, useSoftMenu?: boolean, diff --git a/front_end/ui/legacy/Treeoutline.ts b/front_end/ui/legacy/Treeoutline.ts index a1405b928f..3e6623281c 100644 --- a/front_end/ui/legacy/Treeoutline.ts +++ b/front_end/ui/legacy/Treeoutline.ts @@ -457,7 +457,7 @@ export class TreeElement { expanded: boolean; selected: boolean; private expandable!: boolean; - #expandRecursively: boolean = true; + #expandRecursively = true; private collapsible: boolean; toggleOnClick: boolean; button: Buttons.Button.Button|null; diff --git a/front_end/ui/legacy/UIUtils.test.ts b/front_end/ui/legacy/UIUtils.test.ts index 430811d224..c4017c985d 100644 --- a/front_end/ui/legacy/UIUtils.test.ts +++ b/front_end/ui/legacy/UIUtils.test.ts @@ -54,7 +54,7 @@ describe('UIUtils', () => { const el = document.createElement('div'); const callback = sinon.spy(); const controller = new UI.UIUtils.LongClickController(el, callback); - // @ts-ignore + // @ts-expect-error const setTimeout = sinon.stub(window, 'setTimeout').callsFake(cb => cb()); el.dispatchEvent(new PointerEvent('pointerdown')); diff --git a/front_end/ui/legacy/UIUtils.ts b/front_end/ui/legacy/UIUtils.ts index 04591091c0..8d0409a3dc 100644 --- a/front_end/ui/legacy/UIUtils.ts +++ b/front_end/ui/legacy/UIUtils.ts @@ -1707,7 +1707,7 @@ export abstract class Renderer { return null; } const renderer = await extension.loadRenderer(); - return renderer.render(object, options); + return await renderer.render(object, options); } } diff --git a/front_end/ui/legacy/View.test.ts b/front_end/ui/legacy/View.test.ts index c1a025a715..4171d1983a 100644 --- a/front_end/ui/legacy/View.test.ts +++ b/front_end/ui/legacy/View.test.ts @@ -14,7 +14,7 @@ describe('View', () => { before(async () => { ['first', 'second', 'third', 'fourth'].forEach(title => { UI.ViewManager.registerViewExtension({ - // @ts-ignore + // @ts-expect-error location: 'mock-location', id: title as Lowercase, title: () => title as Platform.UIString.LocalizedString, diff --git a/front_end/ui/legacy/components/cookie_table/CookiesTable.ts b/front_end/ui/legacy/components/cookie_table/CookiesTable.ts index 9e848b2f01..aa0f0b967f 100644 --- a/front_end/ui/legacy/components/cookie_table/CookiesTable.ts +++ b/front_end/ui/legacy/components/cookie_table/CookiesTable.ts @@ -470,7 +470,7 @@ export class CookiesTable extends UI.Widget.VBox { private createCookieData(cookie: SDK.Cookie.Cookie): CookieData { // See https://tc39.es/ecma262/#sec-time-values-and-time-range - const maxTime: number = 8640000000000000; + const maxTime = 8640000000000000; const isRequest = cookie.type() === SDK.Cookie.Type.REQUEST; const data: CookieData = {name: cookie.name(), value: cookie.value()}; for (const attribute diff --git a/front_end/ui/legacy/components/data_grid/DataGrid.ts b/front_end/ui/legacy/components/data_grid/DataGrid.ts index d240317aee..cede4c50b5 100644 --- a/front_end/ui/legacy/components/data_grid/DataGrid.ts +++ b/front_end/ui/legacy/components/data_grid/DataGrid.ts @@ -534,7 +534,7 @@ export class DataGridImpl extends Common.ObjectWrapper.ObjectWrapper { parent: DataGridNode|null; previousSibling: DataGridNode|null; nextSibling: DataGridNode|null; - #disclosureToggleHitBoxWidth: number = 20; + #disclosureToggleHitBoxWidth = 20; selectable: boolean; isRoot: boolean; nodeAccessibleText: string; diff --git a/front_end/ui/legacy/components/data_grid/DataGridElement.test.ts b/front_end/ui/legacy/components/data_grid/DataGridElement.test.ts index d5fd5e5556..7a62aa0701 100644 --- a/front_end/ui/legacy/components/data_grid/DataGridElement.test.ts +++ b/front_end/ui/legacy/components/data_grid/DataGridElement.test.ts @@ -56,11 +56,11 @@ describeWithEnvironment('DataGrid', () => { } async function renderDataGridContent(template: Lit.TemplateResult): Promise { - return renderDataGrid(html`${template}`); + return await renderDataGrid(html`${template}`); } async function renderDataGridWithData(columns: Lit.TemplateResult, rows: Lit.TemplateResult): Promise { - return renderDataGridContent(html`${columns}${rows}
`); + return await renderDataGridContent(html`${columns}${rows}
`); } it('can be configured from template', async () => { diff --git a/front_end/ui/legacy/components/data_grid/ViewportDataGrid.ts b/front_end/ui/legacy/components/data_grid/ViewportDataGrid.ts index 1b85a53eb4..bf300e55cc 100644 --- a/front_end/ui/legacy/components/data_grid/ViewportDataGrid.ts +++ b/front_end/ui/legacy/components/data_grid/ViewportDataGrid.ts @@ -19,11 +19,11 @@ export class ViewportDataGrid extends Common.ObjectWrapper.eventMixin(HTMLElement) { private readonly shadow = this.attachShadow({mode: 'open'}); - private colorMixText: string = ''; // color-mix(in srgb, hotpink, white) - private firstColorText: string = ''; // hotpink - private secondColorText: string = ''; // white + private colorMixText = ''; // color-mix(in srgb, hotpink, white) + private firstColorText = ''; // hotpink + private secondColorText = ''; // white #registerPopoverCallback: undefined|((swatch: ColorMixSwatch) => void); constructor() { diff --git a/front_end/ui/legacy/components/inline_editor/ColorSwatch.ts b/front_end/ui/legacy/components/inline_editor/ColorSwatch.ts index 7cf9e61f0d..a9c5e1fa4c 100644 --- a/front_end/ui/legacy/components/inline_editor/ColorSwatch.ts +++ b/front_end/ui/legacy/components/inline_editor/ColorSwatch.ts @@ -48,7 +48,7 @@ export class ColorSwatch extends HTMLElement { private readonly shadow = this.attachShadow({mode: 'open'}); private tooltip: string = i18nString(UIStrings.shiftclickToChangeColorFormat); private color: Common.Color.Color|null = null; - private readonly: boolean = false; + private readonly = false; constructor(tooltip?: string) { super(); diff --git a/front_end/ui/legacy/components/object_ui/JavaScriptREPL.ts b/front_end/ui/legacy/components/object_ui/JavaScriptREPL.ts index 9c9e30144f..6396b1bdba 100644 --- a/front_end/ui/legacy/components/object_ui/JavaScriptREPL.ts +++ b/front_end/ui/legacy/components/object_ui/JavaScriptREPL.ts @@ -47,7 +47,7 @@ export class JavaScriptREPL { static async evaluateAndBuildPreview( text: string, throwOnSideEffect: boolean, replMode: boolean, timeout?: number, allowErrors?: boolean, - objectGroup?: string, awaitPromise: boolean = false, silent: boolean = false): Promise<{ + objectGroup?: string, awaitPromise = false, silent = false): Promise<{ preview: DocumentFragment, result: SDK.RuntimeModel.EvaluationResult|null, }> { @@ -113,4 +113,4 @@ export class JavaScriptREPL { } } -const maxLengthForEvaluation: number = 2000; +const maxLengthForEvaluation = 2000; diff --git a/front_end/ui/legacy/components/object_ui/ObjectPropertiesSection.ts b/front_end/ui/legacy/components/object_ui/ObjectPropertiesSection.ts index 2ad87de95b..c4c65b9469 100644 --- a/front_end/ui/legacy/components/object_ui/ObjectPropertiesSection.ts +++ b/front_end/ui/legacy/components/object_ui/ObjectPropertiesSection.ts @@ -673,7 +673,7 @@ export class RootElement extends UI.TreeOutline.TreeElement { override async onpopulate(): Promise { const treeOutline = (this.treeOutline as ObjectPropertiesSection | null); const skipProto = treeOutline ? Boolean(treeOutline.skipProtoInternal) : false; - return ObjectPropertyTreeElement.populate( + return await ObjectPropertyTreeElement.populate( this, this.object, skipProto, false, this.linkifier, this.emptyPlaceholder, this.propertiesMode, this.extraProperties, this.targetObject); } @@ -848,9 +848,6 @@ export class ObjectPropertyTreeElement extends UI.TreeOutline.TreeElement { function onInvokeGetterClick(event: Event): void { event.consume(); if (object) { - // The definition of callFunction expects an unknown, and setting to `any` causes Closure to fail. - // However, leaving this as unknown also causes TypeScript to fail, so for now we leave this as unchecked. - // @ts-ignore TODO(crbug.com/1011811): Fix after Closure is removed. void object.callFunction(invokeGetter, [{value: JSON.stringify(propertyPath)}]).then(callback); } } @@ -859,7 +856,7 @@ export class ObjectPropertyTreeElement extends UI.TreeOutline.TreeElement { let result: Object = this; const properties = JSON.parse(arrayStr); for (let i = 0, n = properties.length; i < n; ++i) { - // @ts-ignore callFunction expects this to be a generic Object, so while this works we can't be more specific on types. + // @ts-expect-error callFunction expects this to be a generic Object, so while this works we can't be more specific on types. result = result[properties[i]]; } return result; @@ -1047,7 +1044,7 @@ export class ObjectPropertyTreeElement extends UI.TreeOutline.TreeElement { function invokeGetter(getter) { return Reflect.apply(getter, this, []); }`; - // @ts-ignore No way to teach TypeScript to preserve the Function-ness of `getter`. + // @ts-expect-error No way to teach TypeScript to preserve the Function-ness of `getter`. // Also passing a string instead of a Function to avoid coverage implementation messing with it. void object.callFunction(invokeGetter, [SDK.RemoteObject.RemoteObject.toCallArgument(getter)]) .then(this.onInvokeGetterClick.bind(this)); @@ -1433,7 +1430,7 @@ export class ArrayGroupingTreeElement extends UI.TreeOutline.TreeElement { const ranges = (result.ranges); if (ranges.length === 1) { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) - // @ts-ignore + // @ts-expect-error await ArrayGroupingTreeElement.populateAsFragment(treeNode, object, ranges[0][0], ranges[0][1], linkifier); } else { for (let i = 0; i < ranges.length; ++i) { @@ -1442,7 +1439,7 @@ export class ArrayGroupingTreeElement extends UI.TreeOutline.TreeElement { const count = ranges[i][2]; if (fromIndex === toIndex) { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) - // @ts-ignore + // @ts-expect-error await ArrayGroupingTreeElement.populateAsFragment(treeNode, object, fromIndex, toIndex, linkifier); } else { treeNode.appendChild(new ArrayGroupingTreeElement(object, fromIndex, toIndex, count, linkifier)); @@ -1451,7 +1448,7 @@ export class ArrayGroupingTreeElement extends UI.TreeOutline.TreeElement { } if (topLevel) { // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) - // @ts-ignore + // @ts-expect-error await ArrayGroupingTreeElement.populateNonIndexProperties(treeNode, object, linkifier); } } @@ -1532,7 +1529,7 @@ export class ArrayGroupingTreeElement extends UI.TreeOutline.TreeElement { return; } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration) - // @ts-ignore + // @ts-expect-error await ArrayGroupingTreeElement.populateAsFragment(this, this.object, this.fromIndex, this.toIndex, this.linkifier); } diff --git a/front_end/ui/legacy/components/perf_ui/BrickBreaker.ts b/front_end/ui/legacy/components/perf_ui/BrickBreaker.ts index 214debc617..1cc1eae079 100644 --- a/front_end/ui/legacy/components/perf_ui/BrickBreaker.ts +++ b/front_end/ui/legacy/components/perf_ui/BrickBreaker.ts @@ -115,7 +115,7 @@ export class BrickBreaker extends HTMLElement { #helperCanvas: HTMLCanvasElement; #helperCanvasCtx: CanvasRenderingContext2D; #scorePanel: HTMLElement; - #trackTimelineOffset: number = 0; + #trackTimelineOffset = 0; #visibleEntries = new Set(); #brokenBricks = new Map(); #keyDownHandlerBound = this.#keyDownHandler.bind(this); @@ -125,7 +125,7 @@ export class BrickBreaker extends HTMLElement { #mouseMoveHandlerBound = this.#mouseMoveHandler.bind(this); #boundingElement = WindowBounds.WindowBoundsService.WindowBoundsServiceImpl.instance().getDevToolsBoundingElement(); // Value by which we moved the game up relative to the viewport - #gameViewportOffset: number = 0; + #gameViewportOffset = 0; #running = false; #initialDPR = devicePixelRatio; #ballX = 0; diff --git a/front_end/ui/legacy/components/perf_ui/CanvasHelper.ts b/front_end/ui/legacy/components/perf_ui/CanvasHelper.ts index 044b69c925..6c1755111e 100644 --- a/front_end/ui/legacy/components/perf_ui/CanvasHelper.ts +++ b/front_end/ui/legacy/components/perf_ui/CanvasHelper.ts @@ -36,7 +36,7 @@ export function drawExpansionArrow(context: CanvasRenderingContext2D, x: number, export function drawIcon( context: CanvasRenderingContext2D, x: number, y: number, width: number, pathData: string, - iconColor: string = '--sys-color-on-surface'): void { + iconColor = '--sys-color-on-surface'): void { const p = new Path2D(pathData); context.save(); diff --git a/front_end/ui/legacy/components/perf_ui/FlameChart.ts b/front_end/ui/legacy/components/perf_ui/FlameChart.ts index 1d7568acdc..8a3b18f02b 100644 --- a/front_end/ui/legacy/components/perf_ui/FlameChart.ts +++ b/front_end/ui/legacy/components/perf_ui/FlameChart.ts @@ -319,13 +319,13 @@ export class FlameChart extends Common.ObjectWrapper.eventMixin= startLevel && timelineData.entryLevels[index] < endLevel && barWidth > 10; }; - let wideEntryExists: boolean = false; + let wideEntryExists = false; for (const [{color, outline}, {indexes}] of drawBatches) { if (!wideEntryExists) { wideEntryExists = indexes.some(entryIndexIsInTrack); @@ -2832,7 +2832,7 @@ export class FlameChart extends Common.ObjectWrapper.eventMixin= 0; --m) { const entryIndex = markerIndices[m]; @@ -3098,7 +3098,7 @@ export class FlameChart extends Common.ObjectWrapper.eventMixin time - entryStartTimes[entryIndex]) - 1; - let lastDrawOffset: number = Infinity; + let lastDrawOffset = Infinity; for (let entryIndexOnLevel = rightIndexOnLevel; entryIndexOnLevel >= 0; --entryIndexOnLevel) { const entryIndex = levelIndexes[entryIndexOnLevel]; diff --git a/front_end/ui/legacy/components/perf_ui/OverviewGrid.ts b/front_end/ui/legacy/components/perf_ui/OverviewGrid.ts index 048b181722..182a4b5329 100644 --- a/front_end/ui/legacy/components/perf_ui/OverviewGrid.ts +++ b/front_end/ui/legacy/components/perf_ui/OverviewGrid.ts @@ -178,8 +178,8 @@ export class Window extends Common.ObjectWrapper.ObjectWrapper { private resizeEnabled?: boolean; private clickHandler?: ((arg0: Event) => boolean)|null; private resizerParentOffsetLeft?: number; - #breadcrumbsEnabled: boolean = false; - #mouseOverGridOverview: boolean = false; + #breadcrumbsEnabled = false; + #mouseOverGridOverview = false; constructor(parentElement: HTMLElement, dividersLabelBarElement?: Element, calculator?: Calculator) { super(); this.parentElement = parentElement; diff --git a/front_end/ui/legacy/components/perf_ui/TimelineOverviewCalculator.ts b/front_end/ui/legacy/components/perf_ui/TimelineOverviewCalculator.ts index 6415842c22..24aebf9ed3 100644 --- a/front_end/ui/legacy/components/perf_ui/TimelineOverviewCalculator.ts +++ b/front_end/ui/legacy/components/perf_ui/TimelineOverviewCalculator.ts @@ -10,7 +10,7 @@ export class TimelineOverviewCalculator implements Calculator { #minimumBoundary: Trace.Types.Timing.Milli = Trace.Types.Timing.Milli(0); #maximumBoundary: Trace.Types.Timing.Milli = Trace.Types.Timing.Milli(100); - #displayWidth: number = 0; + #displayWidth = 0; private navStartTimes?: readonly Trace.Types.Events.NavigationStart[]; /** diff --git a/front_end/ui/legacy/components/quick_open/FilteredListWidget.ts b/front_end/ui/legacy/components/quick_open/FilteredListWidget.ts index cd50fb2ce7..2f3f540e8f 100644 --- a/front_end/ui/legacy/components/quick_open/FilteredListWidget.ts +++ b/front_end/ui/legacy/components/quick_open/FilteredListWidget.ts @@ -176,7 +176,6 @@ export class FilteredListWidget extends Common.ObjectWrapper.eventMixin { this.dispatchEventToListeners(Events.HIDDEN); }); - // @ts-ignore this.dialog.show(); } diff --git a/front_end/ui/legacy/components/utils/ImagePreview.ts b/front_end/ui/legacy/components/utils/ImagePreview.ts index ad0d62bb82..4069f3c91d 100644 --- a/front_end/ui/legacy/components/utils/ImagePreview.ts +++ b/front_end/ui/legacy/components/utils/ImagePreview.ts @@ -100,7 +100,7 @@ export class ImagePreview { const resourceSize = contentSize ? contentSize : Platform.StringUtilities.base64ToSize(content); const resourceSizeText = resourceSize > 0 ? i18n.ByteUtilities.bytesToString(resourceSize) : ''; - return new Promise(resolve => { + return await new Promise(resolve => { const imageElement = document.createElement('img'); imageElement.addEventListener('load', buildContent, false); imageElement.addEventListener('error', () => resolve(null), false); diff --git a/front_end/ui/legacy/components/utils/Linkifier.ts b/front_end/ui/legacy/components/utils/Linkifier.ts index 9df30976e1..524ecbaec0 100644 --- a/front_end/ui/legacy/components/utils/Linkifier.ts +++ b/front_end/ui/legacy/components/utils/Linkifier.ts @@ -595,7 +595,7 @@ export class Linkifier extends Common.ObjectWrapper.ObjectWrapper im UI.Tooltip.Tooltip.install(link, title); } if (href) { - // @ts-ignore + // @ts-expect-error link.href = href; } link.setAttribute('jslog', `${VisualLogging.link(jslogContext).track({click: true})}`); diff --git a/front_end/ui/legacy/components/utils/TargetDetachedDialog.ts b/front_end/ui/legacy/components/utils/TargetDetachedDialog.ts index dd653c338c..4bff800eff 100644 --- a/front_end/ui/legacy/components/utils/TargetDetachedDialog.ts +++ b/front_end/ui/legacy/components/utils/TargetDetachedDialog.ts @@ -52,10 +52,6 @@ export class TargetDetachedDialog extends SDK.SDKModel.SDKModel implements }) .show(dialog.contentElement); - // UI.Dialog extends GlassPane and overrides the `show` method with a wider - // accepted type. However, TypeScript uses the supertype declaration to - // determine the full type, which requires a `!Document`. - // @ts-ignore dialog.show(); } diff --git a/front_end/ui/visual_logging/Debugging.ts b/front_end/ui/visual_logging/Debugging.ts index f8eadc718b..658482136c 100644 --- a/front_end/ui/visual_logging/Debugging.ts +++ b/front_end/ui/visual_logging/Debugging.ts @@ -34,7 +34,7 @@ export function setVeDebuggingEnabled(enabled: boolean, inspect?: (query: string } } -// @ts-ignore +// @ts-expect-error globalThis.setVeDebuggingEnabled = setVeDebuggingEnabled; export function processForDebugging(loggable: Loggable): void { @@ -686,7 +686,7 @@ export async function expectVeEvents(expectedEvents: TestLogEntry[]): Promise { + return await promise.finally(() => { clearTimeout(timeout); }); } @@ -724,17 +724,17 @@ function getUnmatchedVeEvents(): string { .join('\n'); } -// @ts-ignore +// @ts-expect-error globalThis.setVeDebugLoggingEnabled = setVeDebugLoggingEnabled; -// @ts-ignore +// @ts-expect-error globalThis.getUnmatchedVeEvents = getUnmatchedVeEvents; -// @ts-ignore +// @ts-expect-error globalThis.veDebugEventsLog = veDebugEventsLog; -// @ts-ignore +// @ts-expect-error globalThis.findVeDebugImpression = findVeDebugImpression; -// @ts-ignore +// @ts-expect-error globalThis.exportAdHocAnalysisLogForSql = exportAdHocAnalysisLogForSql; -// @ts-ignore +// @ts-expect-error globalThis.buildStateFlow = buildStateFlow; -// @ts-ignore +// @ts-expect-error globalThis.expectVeEvents = expectVeEvents; diff --git a/front_end/ui/visual_logging/LoggingEvents.test.ts b/front_end/ui/visual_logging/LoggingEvents.test.ts index add06f3ef9..481a6eb559 100644 --- a/front_end/ui/visual_logging/LoggingEvents.test.ts +++ b/front_end/ui/visual_logging/LoggingEvents.test.ts @@ -53,7 +53,7 @@ describe('LoggingEvents', () => { Host.InspectorFrontendHost.InspectorFrontendHostInstance, 'recordClick', ); - // @ts-ignore + // @ts-expect-error const event = new MouseEvent('click', {button: 0, sourceCapabilities: new InputDeviceCapabilities()}); VisualLogging.LoggingEvents.logClick(throttler)(element, event); await assertThrottled(recordClick); diff --git a/front_end/ui/visual_logging/visual_logging.ts b/front_end/ui/visual_logging/visual_logging.ts index e3f51c68ff..a82ca36587 100644 --- a/front_end/ui/visual_logging/visual_logging.ts +++ b/front_end/ui/visual_logging/visual_logging.ts @@ -17,7 +17,7 @@ export const logClick = (loggable: Loggable, event: Event, options: {doubleClick export const logResize = (l: Loggable, s: DOMRect): void => LoggingEvents.logResize(l, s); export const logKeyDown = async(l: Loggable|null, e: Event, context?: string): Promise => - LoggingEvents.logKeyDown(LoggingDriver.keyboardLogThrottler)(l, e, context); + await LoggingEvents.logKeyDown(LoggingDriver.keyboardLogThrottler)(l, e, context); export {registerParentProvider, setMappedParent} from './LoggingState.js'; export function registerLoggable(loggable: Loggable, config: string, parent: Loggable|null): void { diff --git a/inspector_overlay/common.ts b/inspector_overlay/common.ts index 42c154c5d1..f7d1d0c646 100644 --- a/inspector_overlay/common.ts +++ b/inspector_overlay/common.ts @@ -61,8 +61,8 @@ export class Overlay { protected scrollY = 0; protected style: CSSStyleSheet[]; protected canvas?: HTMLCanvasElement; - protected canvasWidth: number = 0; - protected canvasHeight: number = 0; + protected canvasWidth = 0; + protected canvasHeight = 0; protected platform?: string; // eslint-disable-next-line @typescript-eslint/naming-convention private _window?: Window; diff --git a/inspector_overlay/highlight_common.ts b/inspector_overlay/highlight_common.ts index e84debc854..afd7fcb354 100644 --- a/inspector_overlay/highlight_common.ts +++ b/inspector_overlay/highlight_common.ts @@ -60,7 +60,7 @@ export const enum LinePattern { } export function drawPathWithLineStyle( - context: CanvasRenderingContext2D, path: Path2D, lineStyle?: LineStyle, lineWidth: number = 1) { + context: CanvasRenderingContext2D, path: Path2D, lineStyle?: LineStyle, lineWidth = 1) { if (lineStyle && lineStyle.color) { context.save(); context.translate(0.5, 0.5); @@ -171,7 +171,7 @@ export function applyMatrixToPoint(point: {x: number, y: number}, matrix: DOMMat const HATCH_LINE_LENGTH = 5; const HATCH_LINE_GAP = 3; let hatchLinePattern: CanvasPattern; -let hatchLineColor: string = ''; +let hatchLineColor = ''; /** * Draw line hatching at a 45 degree angle for a given diff --git a/inspector_overlay/main.ts b/inspector_overlay/main.ts index 8756da87ce..c0b1f307ff 100644 --- a/inspector_overlay/main.ts +++ b/inspector_overlay/main.ts @@ -2,33 +2,31 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -// @ts-ignore Importing CSS is handled in Rollup. +// @ts-expect-error Importing CSS is handled in Rollup. import commonStyle from './common.css'; import {adoptStyleSheet} from './common.js'; import {gridStyle} from './highlight_grid_common.js'; import {DistancesOverlay} from './tool_distances.js'; -// @ts-ignore Importing CSS is handled in Rollup. +// @ts-expect-error Importing CSS is handled in Rollup. import highlightGridStyle from './tool_grid.css'; -// @ts-ignore Importing CSS is handled in Rollup. +// @ts-expect-error Importing CSS is handled in Rollup. import highlightStyle from './tool_highlight.css'; import {HighlightOverlay} from './tool_highlight.js'; -// @ts-ignore Importing CSS is handled in Rollup. +// @ts-expect-error Importing CSS is handled in Rollup. import pausedStyle from './tool_paused.css'; import {PausedOverlay, type PausedToolMessage} from './tool_paused.js'; import {PersistentOverlay, type PersistentToolMessage} from './tool_persistent.js'; -// @ts-ignore Importing CSS is handled in Rollup. +// @ts-expect-error Importing CSS is handled in Rollup. import screenshotStyle from './tool_screenshot.css'; import {ScreenshotOverlay, type ScreenshotToolMessage} from './tool_screenshot.js'; -// @ts-ignore Importing CSS is handled in Rollup. +// @ts-expect-error Importing CSS is handled in Rollup. import sourceOrderStyle from './tool_source_order.css'; import {SourceOrderOverlay} from './tool_source_order.js'; import {ViewportSizeOverlay} from './tool_viewport_size.js'; -// @ts-ignore Importing CSS is handled in Rollup. +// @ts-expect-error Importing CSS is handled in Rollup. import wcoStyle from './tool_window_controls.css'; import {WindowControlsOverlay} from './tool_window_controls.js'; -// @ts-ignore Importing CSS is handled in Rollup. - declare global { interface Window { // eslint-disable-next-line @typescript-eslint/naming-convention diff --git a/scripts/ai_assistance/auto-run.js b/scripts/ai_assistance/auto-run.js index 281ab61a5d..dbf89e3873 100644 --- a/scripts/ai_assistance/auto-run.js +++ b/scripts/ai_assistance/auto-run.js @@ -13,7 +13,9 @@ const {parseComment} = require('./auto-run-helpers'); const DEFAULT_FOLLOW_UP_QUERY = 'Fix the issue using JavaScript code execution.'; const startTime = performance.now(); -const numberFormatter = new Intl.NumberFormat('en-EN', {maximumSignificantDigits: 3}); +const numberFormatter = new Intl.NumberFormat('en-EN', { + maximumSignificantDigits: 3, +}); const acquiredDevToolsTargets = new WeakMap(); function formatElapsedTime() { return `${numberFormatter.format((performance.now() - startTime) / 1000)}s`; @@ -102,7 +104,9 @@ class TraceDownloader { }, traceUrl); const foundFile = await TraceDownloader.ensureDownloadExists(fileName); if (!foundFile) { - console.error(`Could not find '${fileName}' in download location (${TraceDownloader.LOCATION}). Aborting.`); + console.error( + `Could not find '${fileName}' in download location (${TraceDownloader.LOCATION}). Aborting.`, + ); } example.log(`Downloaded performance trace: ${fileName}`); return fileName; @@ -122,7 +126,10 @@ class Logger { } #updateElapsedTime() { - this.#logs['elapsedTime'] = {index: 999, text: `\nElapsed time: ${formatElapsedTime()}`}; + this.#logs['elapsedTime'] = { + index: 999, + text: `\nElapsed time: ${formatElapsedTime()}`, + }; this.#flushLogs(); } @@ -208,7 +215,9 @@ class Example { const tracePath = path.join(TraceDownloader.LOCATION, fileName); await fileUploader.uploadFile(tracePath); this.log(`[Info]: imported ${fileName} to performance panel`); - const canvas = await devtoolsPage.waitForSelector(':scope >>> canvas.flame-chart-canvas'); + const canvas = await devtoolsPage.waitForSelector( + ':scope >>> canvas.flame-chart-canvas', + ); if (!canvas) { throw new Error('Could not find canvas.'); } @@ -246,10 +255,7 @@ class Example { * @return {Array<{comment: string, commentElement: Comment, targetElement: Element|null}>} */ function collectComments(root) { - const walker = document.createTreeWalker( - root, - NodeFilter.SHOW_COMMENT, - ); + const walker = document.createTreeWalker(root, NodeFilter.SHOW_COMMENT); const results = []; while (walker.nextNode()) { const comment = walker.currentNode; @@ -288,10 +294,13 @@ class Example { * @returns {Promise>} - the prompt from the annotation, if it exists, or undefined if one was not found. */ async #lookForAnnotatedPerformanceEvent(devtoolsPage) { - const elem = await devtoolsPage.$('devtools-entry-label-overlay >>> [aria-label="Entry label"]'); + const elem = await devtoolsPage.$( + 'devtools-entry-label-overlay >>> [aria-label="Entry label"]', + ); if (!elem) { throw new Error( - 'Could not find annotated event in the performance panel. Only traces that have one entry label annotation are supported.'); + 'Could not find annotated event in the performance panel. Only traces that have one entry label annotation are supported.', + ); } const overlay = /** @type{puppeteer.ElementHandle} */ (elem); @@ -315,7 +324,9 @@ class Example { } const commentStringsFromPage = await this.#getCommentStringsFromPage(page); - const comments = commentStringsFromPage.map(comment => parseComment(comment)); + const comments = commentStringsFromPage.map( + comment => parseComment(comment), + ); // Only get the first comment for now. const comment = comments[0]; const queries = [comment.prompt]; @@ -354,7 +365,7 @@ class Example { const devtoolsTarget = await this.#browser.waitForTarget(target => { const isAcquiredBefore = acquiredDevToolsTargets.has(target); - return target.type() === 'other' && target.url().startsWith('devtools://') && !isAcquiredBefore; + return (target.type() === 'other' && target.url().startsWith('devtools://') && !isAcquiredBefore); }); acquiredDevToolsTargets.set(devtoolsTarget, true); @@ -371,7 +382,7 @@ class Example { // Strip comments to prevent LLM from seeing it. await page.evaluate(() => { // @ts-expect-error we don't type globalThis.__commentElements - for (const {commentElement} of (globalThis.__commentElements ?? [])) { + for (const {commentElement} of globalThis.__commentElements ?? []) { commentElement.remove(); } }); @@ -399,7 +410,9 @@ class Example { this.log('[Info]: Locating console'); await devtoolsPage.locator(':scope >>> #tab-console').click(); await devtoolsPage.locator('aria/Console prompt').click(); - await devtoolsPage.keyboard.type(`inspect(globalThis.__commentElements[${idx}].targetElement)`); + await devtoolsPage.keyboard.type( + `inspect(globalThis.__commentElements[${idx}].targetElement)`, + ); await devtoolsPage.keyboard.press('Enter'); // Once we are done with the console, go back to the elements tab. @@ -412,7 +425,9 @@ class Example { // Clicking on the annotation will also have the side-effect of selecting the event await performanceAnnotation.click(); // Wait until the event is selected (confirming via the HTML in the details drawer) - await devtoolsPage.waitForSelector(':scope >>> .timeline-details-chip-title'); + await devtoolsPage.waitForSelector( + ':scope >>> .timeline-details-chip-title', + ); } this.log('[Info]: Locating AI assistance tab'); @@ -434,7 +449,9 @@ class Example { this.#ready = true; } catch (err) { this.#ready = false; - this.error(`Preparation failed.\n${err instanceof Error ? logger.formatError(err) : err}`); + this.error( + `Preparation failed.\n${err instanceof Error ? logger.formatError(err) : err}`, + ); } } @@ -466,7 +483,7 @@ class Example { }); await this.#devtoolsPage.evaluate(() => { - // @ts-ignore this is run in the DevTools page context where this function does exist. + // @ts-expect-error this is run in the DevTools page context where this function does exist. setDebugAiAssistanceEnabled(true); }); @@ -506,11 +523,15 @@ class Example { const done = this.#devtoolsPage.evaluate(() => { return /** @type {Promise} */ (new Promise(resolve => { - window.addEventListener('aiassistancedone', () => { - resolve(); - }, { - once: true, - }); + window.addEventListener( + 'aiassistancedone', + () => { + resolve(); + }, + { + once: true, + }, + ); })); }); @@ -531,17 +552,24 @@ class Example { }; for (const query of this.#queries) { - this.log(`[Info]: Running the user prompt "${query}" (This step might take long time)`); + this.log( + `[Info]: Running the user prompt "${query}" (This step might take long time)`, + ); const result = await prompt(query); results.push(...result); } await this.#page.close(); - const elapsedTime = numberFormatter.format((performance.now() - executionStartTime) / 1000); + const elapsedTime = numberFormatter.format( + (performance.now() - executionStartTime) / 1000, + ); this.log(`Finished (${elapsedTime}s)`); /** @type {import('./types').ExecutedExample} */ - return {results, metadata: {exampleId: this.id(), explanation: this.#explanation}}; + return { + results, + metadata: {exampleId: this.id(), explanation: this.#explanation}, + }; } /** @@ -550,8 +578,10 @@ class Example { log(text) { const indexOfExample = userArgs.exampleUrls.indexOf(this.#url); logger.log( - this.#url, indexOfExample, - `\x1b[33m[${indexOfExample + 1}/${userArgs.exampleUrls.length}] ${this.id()}:\x1b[0m ${text}`); + this.#url, + indexOfExample, + `\x1b[33m[${indexOfExample + 1}/${userArgs.exampleUrls.length}] ${this.id()}:\x1b[0m ${text}`, + ); } /** @@ -560,8 +590,10 @@ class Example { error(text) { const indexOfExample = userArgs.exampleUrls.indexOf(this.#url); logger.log( - this.#url, indexOfExample, - `\x1b[33m[${indexOfExample + 1}/${userArgs.exampleUrls.length}] ${this.id()}:\x1b[0m \x1b[31m${text}\x1b[0m`); + this.#url, + indexOfExample, + `\x1b[33m[${indexOfExample + 1}/${userArgs.exampleUrls.length}] ${this.id()}:\x1b[0m \x1b[31m${text}\x1b[0m`, + ); } } @@ -582,15 +614,19 @@ async function runInParallel(examples) { const allExampleResults = []; /** @type {Array} **/ const metadata = []; - await Promise.all(examples.filter(example => example.isReady()).map(async example => { - try { - const {results, metadata: singleMetadata} = await example.execute(); - allExampleResults.push(...results); - metadata.push(singleMetadata); - } catch (err) { - example.error(`There is an error, skipping it.\n${err instanceof Error ? logger.formatError(err) : err}`); - } - })); + await Promise.all( + examples.filter(example => example.isReady()).map(async example => { + try { + const {results, metadata: singleMetadata} = await example.execute(); + allExampleResults.push(...results); + metadata.push(singleMetadata); + } catch (err) { + example.error( + `There is an error, skipping it.\n${err instanceof Error ? logger.formatError(err) : err}`, + ); + } + }), + ); return {allExampleResults, metadata}; } @@ -617,7 +653,9 @@ async function runSequentially(examples) { allExampleResults.push(...results); metadata.push(singleMetadata); } catch (err) { - example.error(`There is an error, skipping it.\n${err instanceof Error ? logger.formatError(err) : err}`); + example.error( + `There is an error, skipping it.\n${err instanceof Error ? logger.formatError(err) : err}`, + ); } } @@ -641,7 +679,8 @@ async function main() { // Close any non about:blank pages. There should be only one // about:blank page and DevTools should be closed manually for it. logger.head( - 'Getting browser pages... (If stuck in here, please close all the tabs in the connected Chrome manually.)'); + 'Getting browser pages... (If stuck in here, please close all the tabs in the connected Chrome manually.)', + ); try { for (const page of await browser.pages()) { if (page.url() === 'about:blank') { @@ -650,11 +689,15 @@ async function main() { await page.close(); } } catch (err) { - logger.head(`There was an error closing pages\n${err instanceof Error ? err.stack : err}`); + logger.head( + `There was an error closing pages\n${err instanceof Error ? err.stack : err}`, + ); } logger.head('Preparing examples...'); - const examples = userArgs.exampleUrls.map(exampleUrl => new Example(exampleUrl, browser)); + const examples = userArgs.exampleUrls.map( + exampleUrl => new Example(exampleUrl, browser), + ); /** @type {import('./types').IndividualPromptRequestResponse[]} */ let allExampleResults = []; /** @type {import('./types').ExampleMetadata[]} */ @@ -682,12 +725,17 @@ async function main() { }; const dateSuffix = new Date().toISOString().slice(0, 19); - const outputPath = path.resolve(OUTPUT_DIR, `${userArgs.label}-${dateSuffix}.json`); + const outputPath = path.resolve( + OUTPUT_DIR, + `${userArgs.label}-${dateSuffix}.json`, + ); if (!fs.existsSync(OUTPUT_DIR)) { fs.mkdirSync(OUTPUT_DIR); } fs.writeFileSync(outputPath, JSON.stringify(output, null, 2)); - console.info(`\n[Info]: Finished exporting results to ${outputPath}, it took ${formatElapsedTime()}`); + console.info( + `\n[Info]: Finished exporting results to ${outputPath}, it took ${formatElapsedTime()}`, + ); logger.destroy(); } diff --git a/scripts/build/code_generator_frontend.py b/scripts/build/code_generator_frontend.py index 4046c3af9e..bdddb7aa8a 100644 --- a/scripts/build/code_generator_frontend.py +++ b/scripts/build/code_generator_frontend.py @@ -198,7 +198,7 @@ class Templates: * ): void, * }} */ -// @ts-ignore typedef +// @ts-expect-error typedef export let InspectorBackendAPI; /** diff --git a/scripts/protocol_typescript/protocol_dts_generator.ts b/scripts/protocol_typescript/protocol_dts_generator.ts index 1989f4b69f..86efdb7715 100644 --- a/scripts/protocol_typescript/protocol_dts_generator.ts +++ b/scripts/protocol_typescript/protocol_dts_generator.ts @@ -158,7 +158,7 @@ const emitProperty = (interfaceName: string, prop: Protocol.PropertyType) => { emitLine(`${getPropertyDef(interfaceName, prop)};`); }; -const emitInterface = (interfaceName: string, props?: Protocol.PropertyType[], optionalExtendsClause: string = '') => { +const emitInterface = (interfaceName: string, props?: Protocol.PropertyType[], optionalExtendsClause = '') => { emitOpenBlock(`export interface ${interfaceName}${optionalExtendsClause}`); props ? props.forEach(prop => emitProperty(interfaceName, prop)) : emitLine('[key: string]: string;'); emitCloseBlock(); diff --git a/test/conductor/mocha-interface-helpers.ts b/test/conductor/mocha-interface-helpers.ts index 5833c7fad5..e2857e5acb 100644 --- a/test/conductor/mocha-interface-helpers.ts +++ b/test/conductor/mocha-interface-helpers.ts @@ -95,7 +95,7 @@ export function makeInstrumentedTestFunction(fn: Mocha.AsyncFunc, label: string) // AbortSignal for the current test function. AsyncScope.abortSignal = abortController.signal; // Promisify the function in case it is sync. - const promise = (async () => fn.call(this))(); + const promise = (async () => await fn.call(this))(); const actualTimeout = this.timeout(); // Disable test timeout. this.timeout(0); @@ -131,6 +131,6 @@ export function makeInstrumentedTestFunction(fn: Mocha.AsyncFunc, label: string) clearTimeout(t); this.timeout(actualTimeout); }); - return testPromise; + return await testPromise; }; } diff --git a/test/conductor/pool.ts b/test/conductor/pool.ts index 39a20a8036..17a00274f1 100644 --- a/test/conductor/pool.ts +++ b/test/conductor/pool.ts @@ -72,7 +72,7 @@ export class FrontendTargetPool { // used to resolve the `pair` promise of the `takeTabPair` call. void this.addTabPairToPool(); - return pair; + return await pair; } } diff --git a/test/conductor/screenshot-error.ts b/test/conductor/screenshot-error.ts index 39904ee2ab..f2ca49047e 100644 --- a/test/conductor/screenshot-error.ts +++ b/test/conductor/screenshot-error.ts @@ -28,13 +28,13 @@ export class ScreenshotError extends Error { // To show Diffs mocha Spec reporter expects some properties. // See node_modules/mocha/lib/reporters/base.js. - // @ts-ignore forwarding error properties for Mocha. + // @ts-expect-error forwarding error properties for Mocha. this.showDiff = cause?.showDiff; - // @ts-ignore forwarding error properties for Mocha. + // @ts-expect-error forwarding error properties for Mocha. this.actual = cause?.actual; - // @ts-ignore forwarding error properties for Mocha. + // @ts-expect-error forwarding error properties for Mocha. this.expected = cause?.expected; - // @ts-ignore forwarding error properties for Mocha. + // @ts-expect-error forwarding error properties for Mocha. this.operator = cause?.operator; } diff --git a/test/e2e/ai_assistance/ai_assistance_test.ts b/test/e2e/ai_assistance/ai_assistance_test.ts index 0232a9fe2d..06513c341f 100644 --- a/test/e2e/ai_assistance/ai_assistance_test.ts +++ b/test/e2e/ai_assistance/ai_assistance_test.ts @@ -67,7 +67,7 @@ describe('AI Assistance', function() { await frontend.bringToFront(); await frontend.evaluate(messages => { let call = 0; - // @ts-ignore devtools context. + // @ts-expect-error devtools context. globalThis.InspectorFrontendHost.doAidaConversation = async (request, streamId, cb) => { const response = JSON.stringify([ { @@ -81,7 +81,7 @@ describe('AI Assistance', function() { let first = true; for (const chunk of response.split(',{')) { await new Promise(resolve => setTimeout(resolve, 0)); - // @ts-ignore devtools context. + // @ts-expect-error devtools context. globalThis.InspectorFrontendAPI.streamWrite(streamId, first ? chunk : ',{' + chunk); first = false; } @@ -128,7 +128,7 @@ describe('AI Assistance', function() { return 'setDebugAiAssistanceEnabled' in window; }); await frontend.evaluate(() => { - // @ts-ignore + // @ts-expect-error setDebugAiAssistanceEnabled(true); }); } @@ -331,9 +331,9 @@ STOP`, const {target} = getBrowserAndPages(); await target.bringToFront(); await target.waitForFunction(() => { - // @ts-ignore page context. + // @ts-expect-error page context. return window.getComputedStyle(document.querySelector('div')).backgroundColor === 'rgb(0, 0, 255)' && - // @ts-ignore page context. + // @ts-expect-error page context. window.getComputedStyle(document.querySelector('body')).backgroundColor === 'rgb(0, 128, 0)'; }); }); @@ -355,7 +355,7 @@ STOP`, const {target} = getBrowserAndPages(); await target.bringToFront(); await target.waitForFunction(() => { - // @ts-ignore page context. + // @ts-expect-error page context. return window.getComputedStyle(document.querySelector('div')).backgroundColor === 'rgb(0, 0, 255)'; }); @@ -374,7 +374,7 @@ STOP`, await target.bringToFront(); await target.waitForFunction(() => { - // @ts-ignore page context. + // @ts-expect-error page context. return window.getComputedStyle(document.querySelector('button')).backgroundColor === 'rgb(0, 128, 0)'; }); }); @@ -398,7 +398,7 @@ STOP`, const {target} = getBrowserAndPages(); await target.bringToFront(); await target.waitForFunction(() => { - // @ts-ignore page context. + // @ts-expect-error page context. return window.getComputedStyle(document.querySelector('login-element').shadowRoot.querySelector('button')) .backgroundColor === 'rgb(0, 0, 255)'; }); @@ -420,7 +420,7 @@ STOP`, await target.bringToFront(); await target.waitForFunction(() => { const buttonStyles = - // @ts-ignore page context. + // @ts-expect-error page context. window.getComputedStyle(document.querySelector('login-element').shadowRoot.querySelector('button')); return buttonStyles.backgroundColor === 'rgb(0, 0, 255)' && buttonStyles.color === 'rgb(0, 128, 0)'; }); @@ -472,7 +472,7 @@ STOP`, const {target} = getBrowserAndPages(); await target.bringToFront(); await target.waitForFunction(() => { - // @ts-ignore page context. + // @ts-expect-error page context. return window.getComputedStyle(document.querySelector('div')).backgroundColor === 'rgba(0, 0, 0, 0)'; }); @@ -501,7 +501,7 @@ STOP`, await target.bringToFront(); await target.waitForFunction(() => { - // @ts-ignore page context. + // @ts-expect-error page context. return window.getComputedStyle(document.querySelector('div')).backgroundColor === 'rgb(0, 128, 0)'; }); }); diff --git a/test/e2e/application/storage_test.ts b/test/e2e/application/storage_test.ts index aecf22112c..fff47696ef 100644 --- a/test/e2e/application/storage_test.ts +++ b/test/e2e/application/storage_test.ts @@ -33,11 +33,11 @@ describe('The Application Tab', () => { for (let i = 0; i < 20000; i++) { array.push(i % 10); } - // @ts-ignore + // @ts-expect-error await new Promise(resolve => createDatabase(resolve, 'Database1')); - // @ts-ignore + // @ts-expect-error await new Promise(resolve => createObjectStore(resolve, 'Database1', 'Store1', 'id', true)); - // @ts-ignore + // @ts-expect-error await new Promise(resolve => addIDBValue(resolve, 'Database1', 'Store1', {key: 1, value: array}, '')); }); @@ -62,11 +62,11 @@ describe('The Application Tab', () => { for (let i = 0; i < 20000; i++) { array.push(i % 10); } - // @ts-ignore + // @ts-expect-error await new Promise(resolve => createDatabase(resolve, 'Database1')); - // @ts-ignore + // @ts-expect-error await new Promise(resolve => createObjectStore(resolve, 'Database1', 'Store1', 'id', true)); - // @ts-ignore + // @ts-expect-error await new Promise(resolve => addIDBValue(resolve, 'Database1', 'Store1', {key: 1, value: array}, '')); }); diff --git a/test/e2e/emulation/custom-devices_test.ts b/test/e2e/emulation/custom-devices_test.ts index 15e365df7b..8784dbca32 100644 --- a/test/e2e/emulation/custom-devices_test.ts +++ b/test/e2e/emulation/custom-devices_test.ts @@ -40,7 +40,7 @@ async function targetTextContent(selector: string): Promise { if (!handle) { assert.fail(`targetTextContent: could not find element for ${selector}`); } - return elementTextContent(handle); + return await elementTextContent(handle); } describe('Custom devices', () => { diff --git a/test/e2e/helpers/application-helpers.ts b/test/e2e/helpers/application-helpers.ts index 9bc9b0e8c4..80afd89890 100644 --- a/test/e2e/helpers/application-helpers.ts +++ b/test/e2e/helpers/application-helpers.ts @@ -201,17 +201,17 @@ export async function getDataGridData(selector: string, columns: string[]) { export async function getTrimmedTextContent(selector: string) { const elements = await $$(selector); - return Promise.all(elements.map(element => element.evaluate(e => { + return await Promise.all(elements.map(element => element.evaluate(e => { return (e.textContent || '').trim().replace(/[ \n]{2,}/gm, ''); // remove multiple consecutive whitespaces }))); } export async function getFrameTreeTitles() { const treeTitles = await $$('[aria-label="Resources Section"] ~ ol .tree-element-title'); - return Promise.all(treeTitles.map(node => node.evaluate(e => e.textContent))); + return await Promise.all(treeTitles.map(node => node.evaluate(e => e.textContent))); } -export async function getStorageItemsData(columns: string[], leastExpected: number = 1) { +export async function getStorageItemsData(columns: string[], leastExpected = 1) { const gridData = await waitForFunction(async () => { const values = await getDataGridData('.storage-view table', columns); if (values.length >= leastExpected) { diff --git a/test/e2e/helpers/changes-helpers.ts b/test/e2e/helpers/changes-helpers.ts index b1bd1e2506..9e19e57cfa 100644 --- a/test/e2e/helpers/changes-helpers.ts +++ b/test/e2e/helpers/changes-helpers.ts @@ -45,7 +45,7 @@ export async function getChangesList() { const root = await waitFor(PANEL_ROOT_SELECTOR); const items = await $$('.tree-element-title', root); - return Promise.all(items.map(node => { + return await Promise.all(items.map(node => { return node.evaluate(node => node.textContent as string); })); } @@ -53,7 +53,7 @@ export async function getChangesList() { export async function waitForNewChanges(initialChanges: string[]) { let newChanges = []; - return waitForFunction(async () => { + return await waitForFunction(async () => { newChanges = await getChangesList(); return newChanges.length !== initialChanges.length; }); diff --git a/test/e2e/helpers/console-helpers.ts b/test/e2e/helpers/console-helpers.ts index a54b289ff0..76d2e7cebf 100644 --- a/test/e2e/helpers/console-helpers.ts +++ b/test/e2e/helpers/console-helpers.ts @@ -116,7 +116,7 @@ export async function getConsoleMessages(testName: string, withAnchor = false, c // Have the target load the page. await goToResource(`console/${testName}.html`); - return getCurrentConsoleMessages(withAnchor, Level.All, callback); + return await getCurrentConsoleMessages(withAnchor, Level.All, callback); } export async function getCurrentConsoleMessages(withAnchor = false, level = Level.All, callback?: () => Promise) { @@ -154,7 +154,7 @@ export async function getCurrentConsoleMessages(withAnchor = false, level = Leve }, selector); } -export async function getLastConsoleMessages(offset: number = 0) { +export async function getLastConsoleMessages(offset = 0) { return (await getCurrentConsoleMessages()).at(-1 - offset); } @@ -392,19 +392,18 @@ export async function clickOnContextMenu(selectorForNode: string, jslogContext: * Creates a function that runs a command and checks the nth output from the * bottom (checks last message by default) */ -export function checkCommandResultFunction(offset: number = 0) { +export function checkCommandResultFunction(offset = 0) { return async function(command: string, expected: string, message?: string) { await typeIntoConsoleAndWaitForResult(command); assert.strictEqual(await getLastConsoleMessages(offset), expected, message); }; } -export async function getLastConsoleStacktrace(offset: number = 0) { +export async function getLastConsoleStacktrace(offset = 0) { return (await getStructuredConsoleMessages()).at(-1 - offset)?.stackPreview as string; } -export async function checkCommandStacktrace( - command: string, expected: string, leastMessages: number = 1, offset: number = 0) { +export async function checkCommandStacktrace(command: string, expected: string, leastMessages = 1, offset = 0) { await typeIntoConsoleAndWaitForResult(command, leastMessages); await unifyLogVM(await getLastConsoleStacktrace(offset), expected); } diff --git a/test/e2e/helpers/coverage-helpers.ts b/test/e2e/helpers/coverage-helpers.ts index 2dcf324fcf..4cbc80f3f1 100644 --- a/test/e2e/helpers/coverage-helpers.ts +++ b/test/e2e/helpers/coverage-helpers.ts @@ -37,9 +37,9 @@ export async function clearCoverageContent() { export async function getCoverageData(expectedCount: number) { const rows = await waitForMany('.data-grid-data-grid-node', expectedCount, await waitFor('.coverage-results')); - return Promise.all(rows.map(r => r.evaluate((r: Element) => ({ - url: r.querySelector('.url-column')?.textContent, - total: r.querySelector('.size-column')?.textContent, - unused: r.querySelector('.unused-size-column span')?.textContent, - })))); + return await Promise.all(rows.map(r => r.evaluate((r: Element) => ({ + url: r.querySelector('.url-column')?.textContent, + total: r.querySelector('.size-column')?.textContent, + unused: r.querySelector('.unused-size-column span')?.textContent, + })))); } diff --git a/test/e2e/helpers/datagrid-helpers.ts b/test/e2e/helpers/datagrid-helpers.ts index 31fcd53714..364f7e4f5f 100644 --- a/test/e2e/helpers/datagrid-helpers.ts +++ b/test/e2e/helpers/datagrid-helpers.ts @@ -9,7 +9,7 @@ import {$$, waitFor, waitForFunction} from '../../shared/helper.js'; export async function getDataGridRows( expectedNumberOfRows: number, root?: ElementHandle, - matchExactNumberOfRows: boolean = true): Promise>>> { + matchExactNumberOfRows = true): Promise>>> { const dataGrid = !root ? await waitFor('devtools-data-grid') : root; const handlers = await (async () => { if (matchExactNumberOfRows) { @@ -24,7 +24,7 @@ export async function getDataGridRows( }); })(); - return Promise.all(handlers.map(handler => $$('td[jslog]:not(.hidden)', handler))); + return await Promise.all(handlers.map(handler => $$('td[jslog]:not(.hidden)', handler))); } export async function getDataGrid(root?: ElementHandle) { @@ -42,7 +42,7 @@ export async function getDataGrid(root?: ElementHandle) { export async function getInnerTextOfDataGridCells( dataGridElement: ElementHandle, expectedNumberOfRows: number, - matchExactNumberOfRows: boolean = true): Promise { + matchExactNumberOfRows = true): Promise { const gridRows = await getDataGridRows(expectedNumberOfRows, dataGridElement, matchExactNumberOfRows); const table: string[][] = []; for (const row of gridRows) { diff --git a/test/e2e/helpers/elements-helpers.ts b/test/e2e/helpers/elements-helpers.ts index 62c1b1dd60..95211e2b93 100644 --- a/test/e2e/helpers/elements-helpers.ts +++ b/test/e2e/helpers/elements-helpers.ts @@ -239,10 +239,10 @@ export const waitForChildrenOfSelectedElementNode = async () => { }; export const waitForAndClickTreeElementWithPartialText = async (text: string) => - waitForFunction(async () => clickTreeElementWithPartialText(text)); + await waitForFunction(async () => await clickTreeElementWithPartialText(text)); export const waitForElementWithPartialText = async (text: string) => { - return waitForFunction(async () => elementWithPartialText(text)); + return await waitForFunction(async () => await elementWithPartialText(text)); }; const elementWithPartialText = async (text: string) => { @@ -471,12 +471,12 @@ export const getComputedStylesForDomNode = export const waitForNumberOfComputedProperties = async (numberToWaitFor: number) => { const computedPane = await getComputedPanel(); - return waitForFunction( + return await waitForFunction( async () => numberToWaitFor === await computedPane.$$eval('pierce/' + COMPUTED_PROPERTY_SELECTOR, properties => properties.length)); }; -export const getComputedPanel = async () => waitFor(COMPUTED_STYLES_PANEL_SELECTOR); +export const getComputedPanel = async () => await waitFor(COMPUTED_STYLES_PANEL_SELECTOR); export const filterComputedProperties = async (filterString: string) => { const initialContent = await getContentOfComputedPane(); @@ -554,7 +554,7 @@ export const getComputedStyleProperties = async () => { export const getDisplayedCSSDeclarations = async () => { const cssDeclarations = await $$(CSS_DECLARATION_SELECTOR); - return Promise.all(cssDeclarations.map(async node => await node.evaluate(n => n.textContent?.trim()))); + return await Promise.all(cssDeclarations.map(async node => await node.evaluate(n => n.textContent?.trim()))); }; export const getDisplayedStyleRulesCompact = async () => { @@ -682,7 +682,7 @@ export const getHiddenFontEditorButtons = async () => { export const getStyleSectionSubtitles = async () => { const subtitles = await $$(SECTION_SUBTITLE_SELECTOR); - return Promise.all(subtitles.map(node => node.evaluate(n => n.textContent))); + return await Promise.all(subtitles.map(node => node.evaluate(n => n.textContent))); }; export const getCSSPropertyInRule = diff --git a/test/e2e/helpers/extension-helpers.ts b/test/e2e/helpers/extension-helpers.ts index 26857763fc..8e1d35c037 100644 --- a/test/e2e/helpers/extension-helpers.ts +++ b/test/e2e/helpers/extension-helpers.ts @@ -43,7 +43,7 @@ export async function loadExtension(name: string, startPage?: string, allowFileA // Because the injected script is shared across calls for the target, we cannot run multiple instances concurrently. const load = loadExtensionPromise.then(() => doLoad(frontend, extensionInfo)); loadExtensionPromise = load.catch(() => {}); - return load; + return await load; async function doLoad(frontend: puppeteer.Page, extensionInfo: {startPage: string, name: string}) { const session = (frontend as unknown as CdpPage)._client(); diff --git a/test/e2e/helpers/issues-helpers.ts b/test/e2e/helpers/issues-helpers.ts index 300e457e33..a814def0a7 100644 --- a/test/e2e/helpers/issues-helpers.ts +++ b/test/e2e/helpers/issues-helpers.ts @@ -103,7 +103,7 @@ export async function getIssueByTitle(issueMessage: string): Promise node.textContent); assert.strictEqual(selectedIssueMessage, issueMessage); - return getIssueByTitleElement(issueMessageElement); + return await getIssueByTitleElement(issueMessageElement); } // Works also if there are multiple issues. @@ -121,7 +121,7 @@ export async function getAndExpandSpecificIssueByTitle(issueMessage: string): }); await clickElement(issueMessageElement); await waitFor('.message'); - return getIssueByTitleElement(issueMessageElement); + return await getIssueByTitleElement(issueMessageElement); } export async function getIssueHeaderByTitle(issueMessage: string): diff --git a/test/e2e/helpers/lighthouse-helpers.ts b/test/e2e/helpers/lighthouse-helpers.ts index 344c548740..a7d8f8f4db 100644 --- a/test/e2e/helpers/lighthouse-helpers.ts +++ b/test/e2e/helpers/lighthouse-helpers.ts @@ -45,7 +45,7 @@ export async function navigateToLighthouseTab(path?: string): Promise { + return await waitForFunction(async () => { return await waitForMany('.player-entry-player-title', count); }); } diff --git a/test/e2e/helpers/memory-helpers.ts b/test/e2e/helpers/memory-helpers.ts index 0d948cad4a..74e9303a57 100644 --- a/test/e2e/helpers/memory-helpers.ts +++ b/test/e2e/helpers/memory-helpers.ts @@ -66,7 +66,7 @@ export async function takeAllocationTimelineProfile({recordStacks}: {recordStack await waitFor('.heap-snapshot-sidebar-tree-item.selected'); } -export async function takeHeapSnapshot(name: string = 'Snapshot 1') { +export async function takeHeapSnapshot(name = 'Snapshot 1') { await click(NEW_HEAP_SNAPSHOT_BUTTON); await waitForNone('.heap-snapshot-sidebar-tree-item.wait'); await waitForFunction(async () => { @@ -154,7 +154,7 @@ export async function waitForSearchResultNumber(results: number) { return await waitForFunction(findMatch); } -export async function findSearchResult(searchResult: string, pollIntrerval: number = 500) { +export async function findSearchResult(searchResult: string, pollIntrerval = 500) { const {frontend} = getBrowserAndPages(); const match = await waitFor('#profile-views table.data'); const matches = await waitFor(' .search-results-matches'); @@ -182,7 +182,7 @@ export async function findSearchResult(searchResult: string, pollIntrerval: numb setTimeout(resolve, pollIntrerval, false); }), ]); - return result; + return await result; }); } } @@ -344,7 +344,7 @@ export async function getSizesFromSelectedRow() { return await getSizesFromRow(row); } -export async function getCategoryRow(text: string, wait: boolean = true) { +export async function getCategoryRow(text: string, wait = true) { const selector = `//td[text()="${text}"]/ancestor::tr`; return await (wait ? waitFor(selector, undefined, undefined, 'xpath') : $(selector, undefined, 'xpath')); } diff --git a/test/e2e/helpers/sensors-helpers.ts b/test/e2e/helpers/sensors-helpers.ts index ee29acc126..c5881f9a6b 100644 --- a/test/e2e/helpers/sensors-helpers.ts +++ b/test/e2e/helpers/sensors-helpers.ts @@ -16,10 +16,10 @@ export async function getInputFieldValue(field: ElementHandle): Promise } export async function getOrientationInputs() { - return waitForMany('.orientation-axis-input-container input', 3); + return await waitForMany('.orientation-axis-input-container input', 3); } export async function getOrientationValues() { - return Promise.all( + return await Promise.all( (await getOrientationInputs()).map(i => i.evaluate(i => parseInt((i as HTMLInputElement).value, 10)))); } diff --git a/test/e2e/helpers/settings-helpers.ts b/test/e2e/helpers/settings-helpers.ts index 8f33b2158b..a1d383ffb9 100644 --- a/test/e2e/helpers/settings-helpers.ts +++ b/test/e2e/helpers/settings-helpers.ts @@ -25,7 +25,7 @@ export const openPanelViaMoreTools = async (panelTitle: string) => { await waitForFunction(async () => { // Open the “More Tools” option. await hover('aria/More tools[role="menuitem"]'); - return $(`${panelTitle}[role="menuitem"]`, undefined, 'aria'); + return await $(`${panelTitle}[role="menuitem"]`, undefined, 'aria'); }); // Click the desired menu item diff --git a/test/e2e/helpers/settings-shortcuts-helpers.ts b/test/e2e/helpers/settings-shortcuts-helpers.ts index d31cbb8c17..1a1cbefd76 100644 --- a/test/e2e/helpers/settings-shortcuts-helpers.ts +++ b/test/e2e/helpers/settings-shortcuts-helpers.ts @@ -98,7 +98,7 @@ export const shortcutsForAction = async (shortcutText: string) => { const shortcutElements = await listItemElement.$$(SHORTCUT_DISPLAY_SELECTOR); const shortcutElementsTextContent = await Promise.all(shortcutElements.map(element => element.getProperty('textContent'))); - return Promise.all( + return await Promise.all( shortcutElementsTextContent.map(async textContent => textContent ? await textContent.jsonValue() : [])); }; @@ -108,7 +108,7 @@ export const shortcutInputValues = async () => { assert.fail('shortcut input not found'); } const shortcutValues = await Promise.all(shortcutInputs.map(async input => input.getProperty('value'))); - return Promise.all(shortcutValues.map(async value => value ? await value.jsonValue() : [])); + return await Promise.all(shortcutValues.map(async value => value ? await value.jsonValue() : [])); }; export const clickAddShortcutLink = async () => { diff --git a/test/e2e/helpers/sources-helpers.ts b/test/e2e/helpers/sources-helpers.ts index c8b978fc04..b7c2a64be7 100644 --- a/test/e2e/helpers/sources-helpers.ts +++ b/test/e2e/helpers/sources-helpers.ts @@ -189,7 +189,7 @@ export async function openSourceCodeEditorForFile(sourceFile: string, testInput: export async function getSelectedSource(): Promise { const sourceTabPane = await waitFor('#sources-panel-sources-view .tabbed-pane'); const sourceTabs = await waitFor('.tabbed-pane-header-tab.selected', sourceTabPane); - return sourceTabs.evaluate(node => node.getAttribute('aria-label')) as Promise; + return await (sourceTabs.evaluate(node => node.getAttribute('aria-label')) as Promise); } export async function getBreakpointHitLocation() { @@ -231,7 +231,7 @@ export async function getToolbarText() { return []; } const textNodes = await $$('.toolbar-text', toolbar); - return Promise.all(textNodes.map(node => node.evaluate(node => node.textContent, node))); + return await Promise.all(textNodes.map(node => node.evaluate(node => node.textContent, node))); } export async function addBreakpointForLine(frontend: puppeteer.Page, index: number|string) { @@ -297,7 +297,7 @@ export async function enableInlineBreakpointForLine(line: number, index: number) * @param expectNoBreakpoint If we should wait for the line to not have any inline breakpoints after * the click instead of a disabled one. */ -export async function disableInlineBreakpointForLine(line: number, index: number, expectNoBreakpoint: boolean = false) { +export async function disableInlineBreakpointForLine(line: number, index: number, expectNoBreakpoint = false) { const {frontend} = getBrowserAndPages(); const decorationSelector = `pierce/.cm-content > :nth-child(${line}) > :nth-child(${index} of .cm-inlineBreakpoint)`; await click(decorationSelector); diff --git a/test/e2e/helpers/visual-logging-helpers.ts b/test/e2e/helpers/visual-logging-helpers.ts index e71d263414..67855b0d7e 100644 --- a/test/e2e/helpers/visual-logging-helpers.ts +++ b/test/e2e/helpers/visual-logging-helpers.ts @@ -146,7 +146,7 @@ export function veImpressionForDrawerToolbar(options?: { export async function dumpVeEvents(label: string) { const {frontend} = getBrowserAndPages(); const events = - // @ts-ignore + // @ts-expect-error await frontend.evaluate(async () => (await globalThis.getUnmatchedVeEvents()) as unknown as string[]); // eslint-disable-next-line no-console console.log(label + '\n', events); @@ -159,7 +159,7 @@ export async function expectVeEvents(expectedEvents: TestLogEntry[], root?: stri prependRoot(expectedEvents, root); const {frontend} = getBrowserAndPages(); - // @ts-ignore + // @ts-expect-error await frontend.evaluate(async expectedEvents => await globalThis.expectVeEvents(expectedEvents), expectedEvents); } diff --git a/test/e2e/host/user-metrics_test.ts b/test/e2e/host/user-metrics_test.ts index bd071a1872..bc69a6753f 100644 --- a/test/e2e/host/user-metrics_test.ts +++ b/test/e2e/host/user-metrics_test.ts @@ -68,12 +68,12 @@ declare global { } function retrieveRecordedHistogramEvents(frontend: puppeteer.Page): Promise { - // @ts-ignore + // @ts-expect-error return frontend.evaluate(() => window.InspectorFrontendHost.recordedEnumeratedHistograms); } function retrieveRecordedPerformanceHistogramEvents(frontend: puppeteer.Page): Promise { - // @ts-ignore + // @ts-expect-error return frontend.evaluate(() => window.InspectorFrontendHost.recordedPerformanceHistograms); } diff --git a/test/e2e/inline_editor/color-swatch_test.ts b/test/e2e/inline_editor/color-swatch_test.ts index 7b16d64aec..3d9631c375 100644 --- a/test/e2e/inline_editor/color-swatch_test.ts +++ b/test/e2e/inline_editor/color-swatch_test.ts @@ -21,7 +21,7 @@ import { waitForElementsComputedSection, } from '../helpers/elements-helpers.js'; -async function goToTestPageAndSelectTestElement(path: string = 'inline_editor/default.html') { +async function goToTestPageAndSelectTestElement(path = 'inline_editor/default.html') { await goToResource(path); await waitForContentOfSelectedElementsNode('\u200B'); await clickNthChildOfSelectedElementNode(1); diff --git a/test/e2e/inline_editor/font-editor_test.ts b/test/e2e/inline_editor/font-editor_test.ts index a11801b71e..ca7c14c374 100644 --- a/test/e2e/inline_editor/font-editor_test.ts +++ b/test/e2e/inline_editor/font-editor_test.ts @@ -14,7 +14,7 @@ import { waitForCSSPropertyValue, } from '../helpers/elements-helpers.js'; -async function goToTestPageAndSelectTestElement(path: string = 'inline_editor/fontEditor.html') { +async function goToTestPageAndSelectTestElement(path = 'inline_editor/fontEditor.html') { await goToResource(path); await waitForContentOfSelectedElementsNode('\u200B'); await clickNthChildOfSelectedElementNode(1); diff --git a/test/e2e/issues/bounce-tracking-issues_test.ts b/test/e2e/issues/bounce-tracking-issues_test.ts index f699b9747a..a6ad1ba8bf 100644 --- a/test/e2e/issues/bounce-tracking-issues_test.ts +++ b/test/e2e/issues/bounce-tracking-issues_test.ts @@ -30,7 +30,7 @@ describe('Bounce Tracking issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); const issue2 = { code: 'BounceTrackingIssue', @@ -40,7 +40,7 @@ describe('Bounce Tracking issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue2); }); await expandIssue(); diff --git a/test/e2e/issues/cookie-deprecation-metadata-issues_test.ts b/test/e2e/issues/cookie-deprecation-metadata-issues_test.ts index ba22befc3f..67ca40c67c 100644 --- a/test/e2e/issues/cookie-deprecation-metadata-issues_test.ts +++ b/test/e2e/issues/cookie-deprecation-metadata-issues_test.ts @@ -33,7 +33,7 @@ describe('Cookie Deprecation Metadata issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); const issue2 = { code: 'CookieDeprecationMetadataIssue', @@ -46,7 +46,7 @@ describe('Cookie Deprecation Metadata issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue2); }); await expandIssue(); diff --git a/test/e2e/issues/cors-issues_test.ts b/test/e2e/issues/cors-issues_test.ts index 02ba02f1a6..69a9483f12 100644 --- a/test/e2e/issues/cors-issues_test.ts +++ b/test/e2e/issues/cors-issues_test.ts @@ -15,95 +15,93 @@ import { } from '../helpers/issues-helpers.js'; describe('CORS issues', () => { - it( - 'should display CORS violations with the correct affected resources', async () => { - await goToResource('issues/cors-issue.html'); - const {target} = getBrowserAndPages(); - await target.evaluate(async () => { - // @ts-ignore - await window.doCorsFetches(`https://devtools.oopif.test:${document.location.port}`); - }); - await navigateToIssuesTab(); - await expandIssue(); - const issueElement = await getIssueByTitle('Ensure CORS response header values are valid'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('requests', issueElement, '.cors-issue-affected-resource-label'); - const text = await section.label.evaluate(el => el.textContent); - assert.strictEqual(text, '3 requests'); - await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - 'Preflight Request (if problematic)', - 'Header', - 'Problem', - 'Invalid Value (if available)', - ], - [ - /^devtools.oopif.test:.*/, - 'blocked', - '', - 'Access-Control-Allow-Origin', - 'Missing Header', - '', - ], - [ - /^devtools.oopif.test:.*/, - 'blocked', - /^devtools.oopif.test:.*/, - 'Access-Control-Allow-Origin', - 'Missing Header', - '', - ], - [ - /.*invalid-preflight.*/, - 'blocked', - /.*invalid-preflight.*/, - 'Access-Control-Allow-Origin', - 'Missing Header', - '', - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + it('should display CORS violations with the correct affected resources', async () => { + await goToResource('issues/cors-issue.html'); + const {target} = getBrowserAndPages(); + await target.evaluate(async () => { + // @ts-expect-error + await window.doCorsFetches(`https://devtools.oopif.test:${document.location.port}`); + }); + await navigateToIssuesTab(); + await expandIssue(); + const issueElement = await getIssueByTitle('Ensure CORS response header values are valid'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('requests', issueElement, '.cors-issue-affected-resource-label'); + const text = await section.label.evaluate(el => el.textContent); + assert.strictEqual(text, '3 requests'); + await ensureResourceSectionIsExpanded(section); + const expectedTableRows = [ + [ + 'Request', + 'Status', + 'Preflight Request (if problematic)', + 'Header', + 'Problem', + 'Invalid Value (if available)', + ], + [ + /^devtools.oopif.test:.*/, + 'blocked', + '', + 'Access-Control-Allow-Origin', + 'Missing Header', + '', + ], + [ + /^devtools.oopif.test:.*/, + 'blocked', + /^devtools.oopif.test:.*/, + 'Access-Control-Allow-Origin', + 'Missing Header', + '', + ], + [ + /.*invalid-preflight.*/, + 'blocked', + /.*invalid-preflight.*/, + 'Access-Control-Allow-Origin', + 'Missing Header', + '', + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); - it( - 'should display credentialed+wildcard CORS issues with the correct affected resources', async () => { - await goToResource('empty.html'); - const {target} = getBrowserAndPages(); - await target.evaluate(async () => { - try { - const url = new URL('./issues/origin-wildcard.rawresponse', document.location.toString()) - .toString() - .replace('localhost', 'devtools.oopif.test'); - await fetch(url, {credentials: 'include'}); - } catch { - } - }); - await navigateToIssuesTab(); - await expandIssue(); - const issueElement = - await getIssueByTitle('Ensure credentialed requests are not sent to CORS resources with origin wildcards'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); - const text = await section.label.evaluate(el => el.textContent); - assert.strictEqual(text, '1 request'); - await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - 'Preflight Request (if problematic)', - ], - [ - 'origin-wildcard.rawresponse', - 'blocked', - '', - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + it('should display credentialed+wildcard CORS issues with the correct affected resources', async () => { + await goToResource('empty.html'); + const {target} = getBrowserAndPages(); + await target.evaluate(async () => { + try { + const url = new URL('./issues/origin-wildcard.rawresponse', document.location.toString()) + .toString() + .replace('localhost', 'devtools.oopif.test'); + await fetch(url, {credentials: 'include'}); + } catch { + } + }); + await navigateToIssuesTab(); + await expandIssue(); + const issueElement = + await getIssueByTitle('Ensure credentialed requests are not sent to CORS resources with origin wildcards'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); + const text = await section.label.evaluate(el => el.textContent); + assert.strictEqual(text, '1 request'); + await ensureResourceSectionIsExpanded(section); + const expectedTableRows = [ + [ + 'Request', + 'Status', + 'Preflight Request (if problematic)', + ], + [ + 'origin-wildcard.rawresponse', + 'blocked', + '', + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); it('should display invalid CORS preflight response codes with the correct affected resources', async () => { await goToResource('empty.html'); @@ -216,58 +214,57 @@ describe('CORS issues', () => { await waitForTableFromResourceSectionContents(section.content, expectedTableRows); }); - it( - 'should display invalid CORS ACAC values with the correct affected resources', async () => { - await goToResource('empty.html'); - const {target} = getBrowserAndPages(); - await target.evaluate(async () => { - const url = new URL('./issues/acac-invalid.rawresponse', document.location.toString()) - .toString() - .replace('localhost', 'devtools.oopif.test'); - try { - await fetch(url, { - method: 'POST', - credentials: 'include', - headers: {'Content-Type': 'application/json'}, - body: JSON.stringify({geeting: 'hello'}), - }); - } catch { - } - try { - await fetch(url, {credentials: 'include'}); - } catch { - } + it('should display invalid CORS ACAC values with the correct affected resources', async () => { + await goToResource('empty.html'); + const {target} = getBrowserAndPages(); + await target.evaluate(async () => { + const url = new URL('./issues/acac-invalid.rawresponse', document.location.toString()) + .toString() + .replace('localhost', 'devtools.oopif.test'); + try { + await fetch(url, { + method: 'POST', + credentials: 'include', + headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({geeting: 'hello'}), }); - await navigateToIssuesTab(); - await expandIssue(); - const issueElement = await getIssueByTitle('Ensure CORS requests include credentials only when allowed'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('requests', issueElement, '.cors-issue-affected-resource-label'); - const text = await section.label.evaluate(el => el.textContent); - assert.strictEqual(text, '2 requests'); - await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - 'Preflight Request (if problematic)', - 'Access-Control-Allow-Credentials Header Value', - ], - [ - 'acac-invalid.rawresponse', - 'blocked', - 'acac-invalid.rawresponse', - 'false', - ], - [ - 'acac-invalid.rawresponse', - 'blocked', - '', - 'false', - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + } catch { + } + try { + await fetch(url, {credentials: 'include'}); + } catch { + } + }); + await navigateToIssuesTab(); + await expandIssue(); + const issueElement = await getIssueByTitle('Ensure CORS requests include credentials only when allowed'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('requests', issueElement, '.cors-issue-affected-resource-label'); + const text = await section.label.evaluate(el => el.textContent); + assert.strictEqual(text, '2 requests'); + await ensureResourceSectionIsExpanded(section); + const expectedTableRows = [ + [ + 'Request', + 'Status', + 'Preflight Request (if problematic)', + 'Access-Control-Allow-Credentials Header Value', + ], + [ + 'acac-invalid.rawresponse', + 'blocked', + 'acac-invalid.rawresponse', + 'false', + ], + [ + 'acac-invalid.rawresponse', + 'blocked', + '', + 'false', + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); it('should display CORS requests using disallowed methods with the correct affected resources', async () => { await goToResource('empty.html'); @@ -310,194 +307,188 @@ describe('CORS issues', () => { await waitForTableFromResourceSectionContents(section.content, expectedTableRows); }); - it( - 'should display CORS requests using disallowed headers with the correct affected resources', async () => { - await goToResource('empty.html'); - const {target} = getBrowserAndPages(); - await target.evaluate(async () => { - try { - // We can re-use `method-disallowed.rawresponse` for this test. - const url = new URL('./issues/method-disallowed.rawresponse', document.location.toString()) - .toString() - .replace('localhost', 'devtools.oopif.test'); - await fetch(url, { - headers: {'X-Foo': 'bar'}, - }); - } catch { - } + it('should display CORS requests using disallowed headers with the correct affected resources', async () => { + await goToResource('empty.html'); + const {target} = getBrowserAndPages(); + await target.evaluate(async () => { + try { + // We can re-use `method-disallowed.rawresponse` for this test. + const url = new URL('./issues/method-disallowed.rawresponse', document.location.toString()) + .toString() + .replace('localhost', 'devtools.oopif.test'); + await fetch(url, { + headers: {'X-Foo': 'bar'}, }); - await navigateToIssuesTab(); - await expandIssue(); - const issueElement = await getIssueByTitle('Ensure CORS request includes only allowed headers'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); - const text = await section.label.evaluate(el => el.textContent); - assert.strictEqual(text, '1 request'); - await ensureResourceSectionIsExpanded(section); + } catch { + } + }); + await navigateToIssuesTab(); + await expandIssue(); + const issueElement = await getIssueByTitle('Ensure CORS request includes only allowed headers'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); + const text = await section.label.evaluate(el => el.textContent); + assert.strictEqual(text, '1 request'); + await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - 'Preflight Request', - 'Disallowed Request Header', - ], - [ - 'method-disallowed.rawresponse', - 'blocked', - 'method-disallowed.rawresponse', - 'x-foo', - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + const expectedTableRows = [ + [ + 'Request', + 'Status', + 'Preflight Request', + 'Disallowed Request Header', + ], + [ + 'method-disallowed.rawresponse', + 'blocked', + 'method-disallowed.rawresponse', + 'x-foo', + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); - it( - 'should display CORS requests redirecting to credentialed URLs', async () => { - await goToResource('empty.html'); - const {target} = getBrowserAndPages(); - await target.evaluate(async () => { - try { - const url = new URL('./issues/credentialed-redirect.rawresponse', document.location.toString()) - .toString() - .replace('localhost', 'devtools.oopif.test'); - await fetch(url); - } catch { - } - }); - await navigateToIssuesTab(); - await expandIssue(); - const issueElement = - await getIssueByTitle('Ensure CORS requests are not redirected to URLs containing credentials'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); - const text = await section.label.evaluate(el => el.textContent); - assert.strictEqual(text, '1 request'); - await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - ], - [ - 'credentialed-redirect.rawresponse', - 'blocked', - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + it('should display CORS requests redirecting to credentialed URLs', async () => { + await goToResource('empty.html'); + const {target} = getBrowserAndPages(); + await target.evaluate(async () => { + try { + const url = new URL('./issues/credentialed-redirect.rawresponse', document.location.toString()) + .toString() + .replace('localhost', 'devtools.oopif.test'); + await fetch(url); + } catch { + } + }); + await navigateToIssuesTab(); + await expandIssue(); + const issueElement = + await getIssueByTitle('Ensure CORS requests are not redirected to URLs containing credentials'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); + const text = await section.label.evaluate(el => el.textContent); + assert.strictEqual(text, '1 request'); + await ensureResourceSectionIsExpanded(section); + const expectedTableRows = [ + [ + 'Request', + 'Status', + ], + [ + 'credentialed-redirect.rawresponse', + 'blocked', + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); - it( - 'should display CORS issues that are disallowed by the mode', async () => { - await goToResource('empty.html'); - const {target} = getBrowserAndPages(); - await target.evaluate(async () => { - try { - const url = - new URL('/', document.location.toString()).toString().replace('localhost', 'devtools.oopif.test'); - await fetch(url, {mode: 'same-origin'}); - } catch { - } - }); - await navigateToIssuesTab(); - await expandIssue(); - const issueElement = - await getIssueByTitle('Ensure only same-origin resources are fetched with same-origin request mode'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); - const text = await section.label.evaluate(el => el.textContent); - assert.strictEqual(text, '1 request'); - await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - 'Initiator Context', - 'Source Location', - ], - [ - /^devtools.oopif.test.*\//, - 'blocked', - /^https:\/\/localhost.*/, - /.*:\d+/, - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + it('should display CORS issues that are disallowed by the mode', async () => { + await goToResource('empty.html'); + const {target} = getBrowserAndPages(); + await target.evaluate(async () => { + try { + const url = new URL('/', document.location.toString()).toString().replace('localhost', 'devtools.oopif.test'); + await fetch(url, {mode: 'same-origin'}); + } catch { + } + }); + await navigateToIssuesTab(); + await expandIssue(); + const issueElement = + await getIssueByTitle('Ensure only same-origin resources are fetched with same-origin request mode'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); + const text = await section.label.evaluate(el => el.textContent); + assert.strictEqual(text, '1 request'); + await ensureResourceSectionIsExpanded(section); + const expectedTableRows = [ + [ + 'Request', + 'Status', + 'Initiator Context', + 'Source Location', + ], + [ + /^devtools.oopif.test.*\//, + 'blocked', + /^https:\/\/localhost.*/, + /.*:\d+/, + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); - it( - 'should display CORS issues that are unsupported by the scheme', async () => { - await goToResource('empty.html'); - const {target} = getBrowserAndPages(); - await target.evaluate(async () => { - try { - const url = new URL('/', document.location.toString()) - .toString() - .replace('https://localhost', 'webdav://devtools.oopif.test'); - await fetch(url); - } catch { - } - }); - await navigateToIssuesTab(); - await expandIssue(); - const issueElement = await getIssueByTitle('Ensure CORS requests are made on supported schemes'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); - const text = await section.label.evaluate(el => el.textContent); - assert.strictEqual(text, '1 request'); - await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - 'Initiator Context', - 'Source Location', - 'Unsupported Scheme', - ], - [ - /^devtools.oopif.test.*\//, - 'blocked', - /^https:\/\/localhost.*/, - /.*:\d+/, - 'webdav', - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + it('should display CORS issues that are unsupported by the scheme', async () => { + await goToResource('empty.html'); + const {target} = getBrowserAndPages(); + await target.evaluate(async () => { + try { + const url = new URL('/', document.location.toString()) + .toString() + .replace('https://localhost', 'webdav://devtools.oopif.test'); + await fetch(url); + } catch { + } + }); + await navigateToIssuesTab(); + await expandIssue(); + const issueElement = await getIssueByTitle('Ensure CORS requests are made on supported schemes'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); + const text = await section.label.evaluate(el => el.textContent); + assert.strictEqual(text, '1 request'); + await ensureResourceSectionIsExpanded(section); + const expectedTableRows = [ + [ + 'Request', + 'Status', + 'Initiator Context', + 'Source Location', + 'Unsupported Scheme', + ], + [ + /^devtools.oopif.test.*\//, + 'blocked', + /^https:\/\/localhost.*/, + /.*:\d+/, + 'webdav', + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); - it( - 'should display CORS issues that are misconfiguring the redirect mode', async () => { - await goToResource('empty.html'); - const {target} = getBrowserAndPages(); - await target.evaluate(async () => { - try { - const url = new URL('/', document.location.toString()) - .toString() - .replace('https://localhost', 'webdav://devtools.oopif.test'); - await fetch(url, {mode: 'no-cors', redirect: 'manual'}); - } catch { - } - }); - await navigateToIssuesTab(); - await expandIssue(); - const issueElement = await getIssueByTitle('Ensure no-cors requests configure redirect mode follow'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); - const text = await section.label.evaluate(el => el.textContent); - assert.strictEqual(text, '1 request'); - await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - 'Source Location', - ], - [ - /^devtools.oopif.test.*\//, - 'blocked', - /.*:\d+/, - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + it('should display CORS issues that are misconfiguring the redirect mode', async () => { + await goToResource('empty.html'); + const {target} = getBrowserAndPages(); + await target.evaluate(async () => { + try { + const url = new URL('/', document.location.toString()) + .toString() + .replace('https://localhost', 'webdav://devtools.oopif.test'); + await fetch(url, {mode: 'no-cors', redirect: 'manual'}); + } catch { + } + }); + await navigateToIssuesTab(); + await expandIssue(); + const issueElement = await getIssueByTitle('Ensure no-cors requests configure redirect mode follow'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('request', issueElement, '.cors-issue-affected-resource-label'); + const text = await section.label.evaluate(el => el.textContent); + assert.strictEqual(text, '1 request'); + await ensureResourceSectionIsExpanded(section); + const expectedTableRows = [ + [ + 'Request', + 'Status', + 'Source Location', + ], + [ + /^devtools.oopif.test.*\//, + 'blocked', + /.*:\d+/, + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); }); diff --git a/test/e2e/issues/cors-private-network-issues_test.ts b/test/e2e/issues/cors-private-network-issues_test.ts index 984f8b01f6..2792c05d77 100644 --- a/test/e2e/issues/cors-private-network-issues_test.ts +++ b/test/e2e/issues/cors-private-network-issues_test.ts @@ -37,7 +37,7 @@ describe('Cors Private Network issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); const issue2 = { code: 'CorsIssue', @@ -55,7 +55,7 @@ describe('Cors Private Network issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue2); }); @@ -91,157 +91,155 @@ describe('Cors Private Network issue', () => { await waitForTableFromResourceSectionContents(section.content, expectedTableRows); }); - it( - 'should display correct information for secure contexts', async () => { - await navigateToIssuesTab(); - const {frontend} = getBrowserAndPages(); - frontend.evaluate(() => { - const issue = { - code: 'CorsIssue', - details: { - corsIssueDetails: { - clientSecurityState: { - initiatorIsSecureContext: true, - initiatorIPAddressSpace: 'Public', - privateNetworkRequestPolicy: 'WarnFromInsecureToMorePrivate', - }, - corsErrorStatus: {corsError: 'InsecurePrivateNetwork', failedParameter: ''}, - isWarning: true, - request: {requestId: 'request-1', url: 'http://localhost/'}, - resourceIPAddressSpace: 'Local', - }, + it('should display correct information for secure contexts', async () => { + await navigateToIssuesTab(); + const {frontend} = getBrowserAndPages(); + frontend.evaluate(() => { + const issue = { + code: 'CorsIssue', + details: { + corsIssueDetails: { + clientSecurityState: { + initiatorIsSecureContext: true, + initiatorIPAddressSpace: 'Public', + privateNetworkRequestPolicy: 'WarnFromInsecureToMorePrivate', }, - }; - // @ts-ignore - window.addIssueForTest(issue); - const issue2 = { - code: 'CorsIssue', - details: { - corsIssueDetails: { - clientSecurityState: { - initiatorIsSecureContext: true, - initiatorIPAddressSpace: 'Unknown', - privateNetworkRequestPolicy: 'WarnFromInsecureToMorePrivate', - }, - corsErrorStatus: {corsError: 'InsecurePrivateNetwork', failedParameter: ''}, - isWarning: true, - request: {requestId: 'request-1', url: 'http://example.com/'}, - resourceIPAddressSpace: 'Local', - }, + corsErrorStatus: {corsError: 'InsecurePrivateNetwork', failedParameter: ''}, + isWarning: true, + request: {requestId: 'request-1', url: 'http://localhost/'}, + resourceIPAddressSpace: 'Local', + }, + }, + }; + // @ts-expect-error + window.addIssueForTest(issue); + const issue2 = { + code: 'CorsIssue', + details: { + corsIssueDetails: { + clientSecurityState: { + initiatorIsSecureContext: true, + initiatorIPAddressSpace: 'Unknown', + privateNetworkRequestPolicy: 'WarnFromInsecureToMorePrivate', }, - }; - // @ts-ignore - window.addIssueForTest(issue2); - }); + corsErrorStatus: {corsError: 'InsecurePrivateNetwork', failedParameter: ''}, + isWarning: true, + request: {requestId: 'request-1', url: 'http://example.com/'}, + resourceIPAddressSpace: 'Local', + }, + }, + }; + // @ts-expect-error + window.addIssueForTest(issue2); + }); - await expandIssue(); - const issueElement = await getIssueByTitle('Ensure private network requests are made from secure contexts'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('2 requests', issueElement, '.cors-issue-affected-resource-label'); - await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - 'Resource Address', - 'Initiator Address', - 'Initiator Context', - ], - [ - 'localhost/', - 'warning', - 'Local', - 'Public', - 'secure', - ], - [ - 'example.com/', - 'warning', - 'Local', - 'Unknown', - 'secure', - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + await expandIssue(); + const issueElement = await getIssueByTitle('Ensure private network requests are made from secure contexts'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('2 requests', issueElement, '.cors-issue-affected-resource-label'); + await ensureResourceSectionIsExpanded(section); + const expectedTableRows = [ + [ + 'Request', + 'Status', + 'Resource Address', + 'Initiator Address', + 'Initiator Context', + ], + [ + 'localhost/', + 'warning', + 'Local', + 'Public', + 'secure', + ], + [ + 'example.com/', + 'warning', + 'Local', + 'Unknown', + 'secure', + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); - it( - 'should display correct information for preflight request errors', async () => { - await navigateToIssuesTab(); - const {frontend} = getBrowserAndPages(); - frontend.evaluate(() => { - const issue = { - code: 'CorsIssue', - details: { - corsIssueDetails: { - clientSecurityState: { - initiatorIsSecureContext: true, - initiatorIPAddressSpace: 'Public', - privateNetworkRequestPolicy: 'PreflightBlock', - }, - corsErrorStatus: {corsError: 'PreflightMissingAllowPrivateNetwork', failedParameter: ''}, - isWarning: false, - request: {requestId: 'request-1', url: 'http://localhost/'}, - resourceIPAddressSpace: 'Local', - }, + it('should display correct information for preflight request errors', async () => { + await navigateToIssuesTab(); + const {frontend} = getBrowserAndPages(); + frontend.evaluate(() => { + const issue = { + code: 'CorsIssue', + details: { + corsIssueDetails: { + clientSecurityState: { + initiatorIsSecureContext: true, + initiatorIPAddressSpace: 'Public', + privateNetworkRequestPolicy: 'PreflightBlock', }, - }; - // @ts-ignore - window.addIssueForTest(issue); - const issue2 = { - code: 'CorsIssue', - details: { - corsIssueDetails: { - clientSecurityState: { - initiatorIsSecureContext: true, - initiatorIPAddressSpace: 'Public', - privateNetworkRequestPolicy: 'PreflightBlock', - }, - corsErrorStatus: {corsError: 'PreflightInvalidAllowPrivateNetwork', failedParameter: 'shouldBeTrue'}, - isWarning: false, - request: {requestId: 'request-1', url: 'http://example.com/'}, - resourceIPAddressSpace: 'Local', - }, + corsErrorStatus: {corsError: 'PreflightMissingAllowPrivateNetwork', failedParameter: ''}, + isWarning: false, + request: {requestId: 'request-1', url: 'http://localhost/'}, + resourceIPAddressSpace: 'Local', + }, + }, + }; + // @ts-expect-error + window.addIssueForTest(issue); + const issue2 = { + code: 'CorsIssue', + details: { + corsIssueDetails: { + clientSecurityState: { + initiatorIsSecureContext: true, + initiatorIPAddressSpace: 'Public', + privateNetworkRequestPolicy: 'PreflightBlock', }, - }; - // @ts-ignore - window.addIssueForTest(issue2); - }); + corsErrorStatus: {corsError: 'PreflightInvalidAllowPrivateNetwork', failedParameter: 'shouldBeTrue'}, + isWarning: false, + request: {requestId: 'request-1', url: 'http://example.com/'}, + resourceIPAddressSpace: 'Local', + }, + }, + }; + // @ts-expect-error + window.addIssueForTest(issue2); + }); - await expandIssue(); - const issueElement = - await getIssueByTitle('Ensure private network requests are only made to resources that allow them'); - assertNotNullOrUndefined(issueElement); - const section = await getResourcesElement('2 requests', issueElement, '.cors-issue-affected-resource-label'); - await ensureResourceSectionIsExpanded(section); - const expectedTableRows = [ - [ - 'Request', - 'Status', - 'Preflight Request', - 'Invalid Value (if available)', - 'Initiator Address', - 'Initiator Context', - ], - [ - 'localhost/', - 'blocked', - 'localhost/', - '', - 'Public', - 'secure', - ], - [ - 'example.com/', - 'blocked', - 'example.com/', - 'shouldBeTrue', - 'Public', - 'secure', - ], - ]; - await waitForTableFromResourceSectionContents(section.content, expectedTableRows); - }); + await expandIssue(); + const issueElement = + await getIssueByTitle('Ensure private network requests are only made to resources that allow them'); + assertNotNullOrUndefined(issueElement); + const section = await getResourcesElement('2 requests', issueElement, '.cors-issue-affected-resource-label'); + await ensureResourceSectionIsExpanded(section); + const expectedTableRows = [ + [ + 'Request', + 'Status', + 'Preflight Request', + 'Invalid Value (if available)', + 'Initiator Address', + 'Initiator Context', + ], + [ + 'localhost/', + 'blocked', + 'localhost/', + '', + 'Public', + 'secure', + ], + [ + 'example.com/', + 'blocked', + 'example.com/', + 'shouldBeTrue', + 'Public', + 'secure', + ], + ]; + await waitForTableFromResourceSectionContents(section.content, expectedTableRows); + }); it('should display correct information for failed preflight requests', async () => { await navigateToIssuesTab(); @@ -263,7 +261,7 @@ describe('Cors Private Network issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); }); diff --git a/test/e2e/issues/deprecation-issues_test.ts b/test/e2e/issues/deprecation-issues_test.ts index 11dcefda1d..091d95fef2 100644 --- a/test/e2e/issues/deprecation-issues_test.ts +++ b/test/e2e/issues/deprecation-issues_test.ts @@ -35,7 +35,7 @@ describe('Deprecation Issues', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); }); diff --git a/test/e2e/issues/expect-ct-issues_test.ts b/test/e2e/issues/expect-ct-issues_test.ts index 9c27b22fcd..9fa42210f3 100644 --- a/test/e2e/issues/expect-ct-issues_test.ts +++ b/test/e2e/issues/expect-ct-issues_test.ts @@ -30,7 +30,7 @@ describe('Expect-CT Issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); }); diff --git a/test/e2e/issues/heavy-ad-issues_test.ts b/test/e2e/issues/heavy-ad-issues_test.ts index eb7b98f807..cc7be71015 100644 --- a/test/e2e/issues/heavy-ad-issues_test.ts +++ b/test/e2e/issues/heavy-ad-issues_test.ts @@ -32,7 +32,7 @@ describe('Heavy Ad issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); const issue2 = { code: 'HeavyAdIssue', @@ -44,7 +44,7 @@ describe('Heavy Ad issue', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue2); }); await expandIssue(); diff --git a/test/e2e/issues/hide-issues-menu_test.ts b/test/e2e/issues/hide-issues-menu_test.ts index d66f3130a9..51092a25da 100644 --- a/test/e2e/issues/hide-issues-menu_test.ts +++ b/test/e2e/issues/hide-issues-menu_test.ts @@ -39,7 +39,7 @@ describe('Hide issues menu', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); }); frontend.evaluate(() => { @@ -56,7 +56,7 @@ describe('Hide issues menu', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); }); diff --git a/test/e2e/issues/privacy-sandbox-extensions-api_test.ts b/test/e2e/issues/privacy-sandbox-extensions-api_test.ts index 1c1ddaa591..f7b8264bad 100644 --- a/test/e2e/issues/privacy-sandbox-extensions-api_test.ts +++ b/test/e2e/issues/privacy-sandbox-extensions-api_test.ts @@ -34,7 +34,7 @@ describe('Privacy Sandbox Extensions API', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); }); diff --git a/test/e2e/issues/quota-issues_test.ts b/test/e2e/issues/quota-issues_test.ts index 1a06af59a0..d05451da05 100644 --- a/test/e2e/issues/quota-issues_test.ts +++ b/test/e2e/issues/quota-issues_test.ts @@ -34,7 +34,7 @@ describe('Quota Issues', () => { }, }, }; - // @ts-ignore + // @ts-expect-error window.addIssueForTest(issue); }); diff --git a/test/e2e/network/network-request-view_test.ts b/test/e2e/network/network-request-view_test.ts index 25eec3de90..b324fc8b13 100644 --- a/test/e2e/network/network-request-view_test.ts +++ b/test/e2e/network/network-request-view_test.ts @@ -223,7 +223,7 @@ describe('The Network Request view', () => { '[aria-label=EventStream][role=tab][aria-selected=true]', networkView, ); - return waitFor('.event-source-messages-view'); + return await waitFor('.event-source-messages-view'); }; interface EventSourceMessageRaw { @@ -234,13 +234,13 @@ describe('The Network Request view', () => { } const waitForMessages = async (messagesView: puppeteer.ElementHandle, count: number) => { - return waitForFunction(async () => { + return await waitForFunction(async () => { const messages = await $$('.data-grid-data-grid-node', messagesView); if (messages.length !== count) { return undefined; } - return Promise.all(messages.map(message => { + return await Promise.all(messages.map(message => { return new Promise(async resolve => { const [id, type, data] = await Promise.all([ getTextContent('.id-column', message), @@ -330,17 +330,17 @@ describe('The Network Request view', () => { root: networkView, }); await waitFor('[aria-label=Messages][role=tab][aria-selected=true]', networkView); - return waitFor('.websocket-frame-view'); + return await waitFor('.websocket-frame-view'); }; let messagesView = await navigateToWebsocketMessages(); const waitForMessages = async (count: number) => { - return waitForFunction(async () => { + return await waitForFunction(async () => { const messages = await $$('.data-column.websocket-frame-view-td', messagesView); if (messages.length !== count) { return undefined; } - return Promise.all(messages.map(message => { + return await Promise.all(messages.map(message => { return message.evaluate(message => message.textContent || ''); })); }); diff --git a/test/e2e/recorder/helpers.ts b/test/e2e/recorder/helpers.ts index fa0b65742b..bb7f31ae86 100644 --- a/test/e2e/recorder/helpers.ts +++ b/test/e2e/recorder/helpers.ts @@ -239,7 +239,7 @@ export async function clickSelectButtonItem(itemLabel: string, root: string) { export async function setupRecorderWithScript( script: UserFlow, - path: string = 'recorder/recorder.html', + path = 'recorder/recorder.html', ): Promise { await enableAndOpenRecorderPanel(path); await createAndStartRecording(script.title); @@ -249,7 +249,7 @@ export async function setupRecorderWithScript( export async function setupRecorderWithScriptAndReplay( script: UserFlow, - path: string = 'recorder/recorder.html', + path = 'recorder/recorder.html', ): Promise { await setupRecorderWithScript(script, path); const onceFinished = onReplayFinished(); diff --git a/test/e2e/rendering/Rendering_test.ts b/test/e2e/rendering/Rendering_test.ts index 2308ccaa0d..a05c93a946 100644 --- a/test/e2e/rendering/Rendering_test.ts +++ b/test/e2e/rendering/Rendering_test.ts @@ -55,7 +55,6 @@ describe('Rendering pane', () => { }); if (!hasSupport) { - // @ts-ignore this.skip(); } diff --git a/test/e2e/sensors/emulate-hardware-concurrency_test.ts b/test/e2e/sensors/emulate-hardware-concurrency_test.ts index 0412cd81af..1e7d760c8b 100644 --- a/test/e2e/sensors/emulate-hardware-concurrency_test.ts +++ b/test/e2e/sensors/emulate-hardware-concurrency_test.ts @@ -11,7 +11,7 @@ import {openPanelViaMoreTools} from '../helpers/settings-helpers.js'; async function waitForChangedConcurrency(lastConcurrency: number|undefined) { const {target} = getBrowserAndPages(); - return waitForFunction(async () => { + return await waitForFunction(async () => { const newConcurrency = await target.evaluate('navigator.hardwareConcurrency') as number; if (newConcurrency !== lastConcurrency) { return newConcurrency; diff --git a/test/shared/helper.ts b/test/shared/helper.ts index 43397e5057..b1e5985a3d 100644 --- a/test/shared/helper.ts +++ b/test/shared/helper.ts @@ -80,7 +80,7 @@ async function performActionOnSelector( break; } } - return waitForFunction(async () => { + return await waitForFunction(async () => { const element = await waitFor(selector, options?.root, undefined, queryHandler); try { await action(element); @@ -142,7 +142,7 @@ export const doubleClick = ...passedClickOptions, clickCount: 2, }; - return click(selector, { + return await click(selector, { ...options, clickOptions: clickOptionsWithDoubleClick, }); @@ -223,7 +223,7 @@ export const $$ = * @param root The root of the search. */ export const $textContent = async (textContent: string, root?: puppeteer.ElementHandle) => { - return $(textContent, root, 'pierceShadowText'); + return await $(textContent, root, 'pierceShadowText'); }; /** @@ -233,7 +233,7 @@ export const $textContent = async (textContent: string, root?: puppeteer.Element * @param root The root of the search. */ export const $$textContent = async (textContent: string, root?: puppeteer.ElementHandle) => { - return $$(textContent, root, 'pierceShadowText'); + return await $$(textContent, root, 'pierceShadowText'); }; export const timeout = (duration: number) => new Promise(resolve => setTimeout(resolve, duration)); @@ -247,7 +247,7 @@ export const getTextContent = export const getAllTextContents = async(selector: string, root?: puppeteer.JSHandle, handler = 'pierce'): Promise> => { const allElements = await $$(selector, root, handler); - return Promise.all(allElements.map(e => e.evaluate(e => e.textContent))); + return await Promise.all(allElements.map(e => e.evaluate(e => e.textContent))); }; /** @@ -466,7 +466,7 @@ export const goToResourceWithCustomHost = async (host: string, path: string) => await goTo(`${getResourcesPath(host)}/${path}`); }; -export const getResourcesPath = (host: string = 'localhost') => { +export const getResourcesPath = (host = 'localhost') => { return `https://${host}:${getTestServerPort()}/test/e2e/resources`; }; @@ -579,7 +579,7 @@ export const selectTextFromNodeToNode = async ( document.execCommand('copy'); - return navigator.clipboard.readText(); + return await navigator.clipboard.readText(); }, await from, await to, direction); }; @@ -736,7 +736,7 @@ export const hasClass = async (element: puppeteer.ElementHandle, classn export const waitForClass = async (element: puppeteer.ElementHandle, classname: string) => { await waitForFunction(async () => { - return hasClass(element, classname); + return await hasClass(element, classname); }); }; @@ -843,7 +843,7 @@ export async function raf(page: puppeteer.Page): Promise { export async function readClipboard() { const {frontend, browser} = getBrowserAndPages(); await browser.defaultBrowserContext().overridePermissions(frontend.url(), ['clipboard-read']); - const clipboard = await frontend.evaluate(async () => navigator.clipboard.readText()); + const clipboard = await frontend.evaluate(async () => await navigator.clipboard.readText()); await browser.defaultBrowserContext().clearPermissionOverrides(); return clipboard; } diff --git a/test/shared/screenshots.ts b/test/shared/screenshots.ts index a5ce303607..11210d3638 100644 --- a/test/shared/screenshots.ts +++ b/test/shared/screenshots.ts @@ -79,7 +79,8 @@ export const assertElementScreenshotUnchanged = async ( if (platform !== 'linux') { return; } - return assertScreenshotUnchangedWithRetries(element, fileName, maximumDiffThreshold, DEFAULT_RETRIES_COUNT, options); + return await assertScreenshotUnchangedWithRetries( + element, fileName, maximumDiffThreshold, DEFAULT_RETRIES_COUNT, options); }; const assertScreenshotUnchangedWithRetries = async ( @@ -230,7 +231,7 @@ interface ImageDiff { } async function imageDiff(golden: string, generated: string) { - return new Promise(async (resolve, reject) => { + return await new Promise(async (resolve, reject) => { try { const imageDiff: ImageDiff = {rawMisMatchPercentage: 0, diffPath: ''}; const diffText = await execImageDiffCommand(`${IMAGE_DIFF_BINARY} --histogram ${golden} ${generated}`); @@ -256,7 +257,7 @@ async function imageDiff(golden: string, generated: string) { } async function execImageDiffCommand(cmd: string) { - return new Promise((resolve, reject) => { + return await new Promise((resolve, reject) => { let commandOutput = ''; try { commandOutput = childProcess.execSync(cmd, {encoding: 'utf8'});