Skip to content

Commit

Permalink
refactor: enable isolatedDeclarations (#7473)
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz authored Feb 13, 2025
1 parent 01b91b5 commit accd2ed
Show file tree
Hide file tree
Showing 168 changed files with 788 additions and 640 deletions.
6 changes: 3 additions & 3 deletions packages/browser/src/client/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ export type IframeChannelEvent =
| IframeChannelIncomingEvent
| IframeChannelOutgoingEvent

export const channel = new BroadcastChannel(
export const channel: BroadcastChannel = new BroadcastChannel(
`vitest:${getBrowserState().sessionId}`,
)
export const globalChannel = new BroadcastChannel('vitest:global')
export const globalChannel: BroadcastChannel = new BroadcastChannel('vitest:global')

export function waitForChannel(event: IframeChannelOutgoingEvent['type']) {
export function waitForChannel(event: IframeChannelOutgoingEvent['type']): Promise<void> {
return new Promise<void>((resolve) => {
channel.addEventListener(
'message',
Expand Down
12 changes: 6 additions & 6 deletions packages/browser/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@ import { getBrowserState } from './utils'

const PAGE_TYPE = getBrowserState().type

export const PORT = location.port
export const HOST = [location.hostname, PORT].filter(Boolean).join(':')
export const RPC_ID
export const PORT: string = location.port
export const HOST: string = [location.hostname, PORT].filter(Boolean).join(':')
export const RPC_ID: string
= PAGE_TYPE === 'orchestrator'
? getBrowserState().sessionId
: getBrowserState().testerId
const METHOD = getBrowserState().method
export const ENTRY_URL = `${
export const ENTRY_URL: string = `${
location.protocol === 'https:' ? 'wss:' : 'ws:'
}//${HOST}/__vitest_browser_api__?type=${PAGE_TYPE}&rpcId=${RPC_ID}&sessionId=${getBrowserState().sessionId}&projectName=${getBrowserState().config.name || ''}&method=${METHOD}&token=${(window as any).VITEST_API_TOKEN}`

let setCancel = (_: CancelReason) => {}
export const onCancel = new Promise<CancelReason>((resolve) => {
export const onCancel: Promise<CancelReason> = new Promise((resolve) => {
setCancel = resolve
})

Expand Down Expand Up @@ -135,6 +135,6 @@ function createClient() {
return ctx
}

export const client = createClient()
export const client: VitestBrowserClient = createClient()

export * from './channel'
3 changes: 2 additions & 1 deletion packages/browser/src/client/tester/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type {
UserEventTabOptions,
UserEventTypeOptions,
} from '../../../context'
import type { BrowserRunnerState } from '../utils'
import { convertElementToCssSelector, ensureAwaited, getBrowserState, getWorkerState } from '../utils'

// this file should not import anything directly, only types and utils
Expand Down Expand Up @@ -238,7 +239,7 @@ function createPreviewUserEvent(userEventBase: TestingLibraryUserEvent, options:
return vitestUserEvent
}

export function cdp() {
export function cdp(): BrowserRunnerState['cdp'] {
return getBrowserState().cdp!
}

Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/client/tester/dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ expect(${name}).toHaveBeenCalledWith(${formattedParams})
}
}

export function setupDialogsSpy() {
export function setupDialogsSpy(): void {
globalThis.alert = showPopupWarning('alert', undefined)
globalThis.confirm = showPopupWarning('confirm', false, true)
globalThis.prompt = showPopupWarning('prompt', null, 'your value')
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/client/tester/expect-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { ExpectPollOptions } from 'vitest'
import * as matchers from '@testing-library/jest-dom/matchers'
import { chai, expect } from 'vitest'

export async function setupExpectDom() {
export async function setupExpectDom(): Promise<void> {
expect.extend(matchers)
expect.element = <T extends Element | Locator>(elementOrLocator: T, options?: ExpectPollOptions) => {
if (!(elementOrLocator instanceof Element) && !('element' in elementOrLocator)) {
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/client/tester/locators/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import { ensureAwaited, getBrowserState, getWorkerState } from '../../utils'
import { getElementError } from '../public-utils'

// we prefer using playwright locators because they are more powerful and support Shadow DOM
export const selectorEngine = Ivya.create({
export const selectorEngine: Ivya = Ivya.create({
browser: ((name: string) => {
switch (name) {
case 'edge':
Expand Down Expand Up @@ -217,7 +217,7 @@ export abstract class Locator {
return this.worker.rpc as any as BrowserRPC
}

protected triggerCommand<T>(command: string, ...args: any[]) {
protected triggerCommand<T>(command: string, ...args: any[]): Promise<T> {
const filepath = this.worker.filepath
|| this.worker.current?.file?.filepath
|| undefined
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/client/tester/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { rpc } from './rpc'

const { Date, console, performance } = globalThis

export function setupConsoleLogSpy() {
export function setupConsoleLogSpy(): void {
const {
log,
info,
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/client/tester/msw.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ModuleMockerMSWInterceptor } from '@vitest/mocker/browser'
import { getConfig } from '../utils'

export function createModuleMockerInterceptor() {
export function createModuleMockerInterceptor(): ModuleMockerMSWInterceptor {
const debug = getConfig().env.VITEST_BROWSER_DEBUG
return new ModuleMockerMSWInterceptor({
globalThisAccessor: '"__vitest_mocker__"',
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/client/tester/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function withSafeTimers(getTimers: typeof getSafeTimers, fn: () => void) {

const promises = new Set<Promise<unknown>>()

export async function rpcDone() {
export async function rpcDone(): Promise<unknown[] | undefined> {
if (!promises.size) {
return
}
Expand Down
7 changes: 2 additions & 5 deletions packages/browser/src/client/tester/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@ interface BrowserRunnerOptions {
config: SerializedConfig
}

export const browserHashMap = new Map<
string,
string
>()
export const browserHashMap: Map<string, string> = new Map()

interface CoverageHandler {
takeCoverage: () => Promise<unknown>
Expand Down Expand Up @@ -157,7 +154,7 @@ export async function initiateRunner(
state: WorkerGlobalState,
mocker: VitestBrowserClientMocker,
config: SerializedConfig,
) {
): Promise<VitestRunner> {
if (cachedRunner) {
return cachedRunner
}
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/client/tester/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export class VitestBrowserSnapshotEnvironment implements SnapshotEnvironment {
private sourceMaps = new Map<string, any>()
private traceMaps = new Map<string, TraceMap>()

public addSourceMap(filepath: string, map: any) {
public addSourceMap(filepath: string, map: any): void {
this.sourceMaps.set(filepath, map)
}

Expand Down
8 changes: 4 additions & 4 deletions packages/browser/src/client/utils.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import type { SerializedConfig, WorkerGlobalState } from 'vitest'

export async function importId(id: string) {
export async function importId(id: string): Promise<any> {
const name = `/@id/${id}`.replace(/\\/g, '/')
return getBrowserState().wrapModule(() => import(/* @vite-ignore */ name))
}

export async function importFs(id: string) {
export async function importFs(id: string): Promise<any> {
const name = `/@fs/${id}`.replace(/\\/g, '/')
return getBrowserState().wrapModule(() => import(/* @vite-ignore */ name))
}

export const executor = {
isBrowser: true,

executeId: (id: string) => {
executeId: (id: string): Promise<any> => {
if (id[0] === '/' || id[1] === ':') {
return importFs(id)
}
Expand Down Expand Up @@ -103,7 +103,7 @@ export function getWorkerState(): WorkerGlobalState {
}

/* @__NO_SIDE_EFFECTS__ */
export function convertElementToCssSelector(element: Element) {
export function convertElementToCssSelector(element: Element): string {
if (!element || !(element instanceof Element)) {
throw new Error(
`Expected DOM element to be an instance of Element, received ${typeof element}`,
Expand Down
8 changes: 4 additions & 4 deletions packages/browser/src/node/cdp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@ export class BrowserServerCDPHandler {
private tester: WebSocketBrowserRPC,
) {}

send(method: string, params?: Record<string, unknown>) {
send(method: string, params?: Record<string, unknown>): Promise<unknown> {
return this.session.send(method, params)
}

on(event: string, id: string, once = false) {
on(event: string, id: string, once = false): void {
if (!this.listenerIds[event]) {
this.listenerIds[event] = []
}
Expand All @@ -36,7 +36,7 @@ export class BrowserServerCDPHandler {
}
}

off(event: string, id: string) {
off(event: string, id: string): void {
if (!this.listenerIds[event]) {
this.listenerIds[event] = []
}
Expand All @@ -48,7 +48,7 @@ export class BrowserServerCDPHandler {
}
}

once(event: string, listener: string) {
once(event: string, listener: string): void {
this.on(event, listener, true)
}
}
36 changes: 18 additions & 18 deletions packages/browser/src/node/commands/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,22 +17,22 @@ import { type } from './type'
import { upload } from './upload'

export default {
readFile,
removeFile,
writeFile,
__vitest_fileInfo: _fileInfo,
__vitest_upload: upload,
__vitest_click: click,
__vitest_dblClick: dblClick,
__vitest_tripleClick: tripleClick,
__vitest_screenshot: screenshot,
__vitest_type: type,
__vitest_clear: clear,
__vitest_fill: fill,
__vitest_tab: tab,
__vitest_keyboard: keyboard,
__vitest_selectOptions: selectOptions,
__vitest_dragAndDrop: dragAndDrop,
__vitest_hover: hover,
__vitest_cleanup: keyboardCleanup,
readFile: readFile as typeof readFile,
removeFile: removeFile as typeof removeFile,
writeFile: writeFile as typeof writeFile,
__vitest_fileInfo: _fileInfo as typeof _fileInfo,
__vitest_upload: upload as typeof upload,
__vitest_click: click as typeof click,
__vitest_dblClick: dblClick as typeof dblClick,
__vitest_tripleClick: tripleClick as typeof tripleClick,
__vitest_screenshot: screenshot as typeof screenshot,
__vitest_type: type as typeof type,
__vitest_clear: clear as typeof clear,
__vitest_fill: fill as typeof fill,
__vitest_tab: tab as typeof tab,
__vitest_keyboard: keyboard as typeof keyboard,
__vitest_selectOptions: selectOptions as typeof selectOptions,
__vitest_dragAndDrop: dragAndDrop as typeof dragAndDrop,
__vitest_hover: hover as typeof hover,
__vitest_cleanup: keyboardCleanup as typeof keyboardCleanup,
}
2 changes: 1 addition & 1 deletion packages/browser/src/node/commands/keyboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export async function keyboardImplementation(
text: string,
selectAll: () => Promise<void>,
skipRelease: boolean,
) {
): Promise<{ pressed: Set<string> }> {
if (provider instanceof PlaywrightBrowserProvider) {
const page = provider.getPage(sessionId)
const actions = parseKeyDef(defaultKeyMap, text)
Expand Down
2 changes: 1 addition & 1 deletion packages/browser/src/node/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@ import { fileURLToPath } from 'node:url'
import { resolve } from 'pathe'

const pkgRoot = resolve(fileURLToPath(import.meta.url), '../..')
export const distRoot = resolve(pkgRoot, 'dist')
export const distRoot: string = resolve(pkgRoot, 'dist')
2 changes: 1 addition & 1 deletion packages/browser/src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export async function createBrowserServer(
configFile: string | undefined,
prePlugins: Plugin[] = [],
postPlugins: Plugin[] = [],
) {
): Promise<ParentBrowserProject> {
if (project.vitest.version !== version) {
project.vitest.logger.warn(
c.yellow(
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/node/middlewares/utils.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import type { ServerResponse } from 'node:http'

export function disableCache(res: ServerResponse) {
export function disableCache(res: ServerResponse): void {
res.setHeader(
'Cache-Control',
'no-cache, max-age=0, must-revalidate',
)
res.setHeader('Content-Type', 'text/html; charset=utf-8')
}

export function allowIframes(res: ServerResponse) {
export function allowIframes(res: ServerResponse): void {
// remove custom iframe related headers to allow the iframe to load
res.removeHeader('X-Frame-Options')
}
19 changes: 10 additions & 9 deletions packages/browser/src/node/project.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { StackTraceParserOptions } from '@vitest/utils/source-map'
import type { ErrorWithDiff, SerializedConfig } from 'vitest'
import type { ViteDevServer } from 'vite'
import type { ErrorWithDiff, ParsedStack, SerializedConfig } from 'vitest'
import type {
BrowserProvider,
ProjectBrowser as IProjectBrowser,
Expand All @@ -23,11 +24,11 @@ export class ProjectBrowser implements IProjectBrowser {
public provider!: BrowserProvider
public vitest: Vitest
public config: ResolvedConfig
public children = new Set<ProjectBrowser>()
public children: Set<ProjectBrowser> = new Set<ProjectBrowser>()

public parent!: ParentBrowserProject

public state = new BrowserServerState()
public state: BrowserServerState = new BrowserServerState()

constructor(
public project: TestProject,
Expand All @@ -53,18 +54,18 @@ export class ProjectBrowser implements IProjectBrowser {
).then(html => (this.testerHtml = html))
}

get vite() {
get vite(): ViteDevServer {
return this.parent.vite
}

wrapSerializedConfig() {
wrapSerializedConfig(): SerializedConfig {
const config = wrapConfig(this.project.serializedConfig)
config.env ??= {}
config.env.VITEST_BROWSER_DEBUG = process.env.VITEST_BROWSER_DEBUG || ''
return config
}

async initBrowserProvider(project: TestProject) {
async initBrowserProvider(project: TestProject): Promise<void> {
if (this.provider) {
return
}
Expand Down Expand Up @@ -95,18 +96,18 @@ export class ProjectBrowser implements IProjectBrowser {
public parseErrorStacktrace(
e: ErrorWithDiff,
options: StackTraceParserOptions = {},
) {
): ParsedStack[] {
return this.parent.parseErrorStacktrace(e, options)
}

public parseStacktrace(
trace: string,
options: StackTraceParserOptions = {},
) {
): ParsedStack[] {
return this.parent.parseStacktrace(trace, options)
}

async close() {
async close(): Promise<void> {
await this.parent.vite.close()
}
}
Expand Down
Loading

0 comments on commit accd2ed

Please sign in to comment.