Skip to content

Commit

Permalink
refactor: deprecate all config types from the main Vitest entrypoint,…
Browse files Browse the repository at this point in the history
… introduce `SerializedConfig` type (#6205)
  • Loading branch information
sheremet-va authored Jul 23, 2024
1 parent 883f348 commit 3aab8a1
Show file tree
Hide file tree
Showing 57 changed files with 584 additions and 264 deletions.
2 changes: 1 addition & 1 deletion docs/guide/browser/context.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export const page: {
/**
* Serialized test config.
*/
config: ResolvedConfig
config: SerializedConfig
/**
* Change the size of iframe's viewport.
*/
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/context.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ResolvedConfig } from 'vitest'
import type { SerializedConfig } from 'vitest'

export type BufferEncoding =
| 'ascii'
Expand Down Expand Up @@ -253,7 +253,7 @@ export interface BrowserPage {
/**
* Serialized test config.
*/
config: ResolvedConfig
config: SerializedConfig
/**
* Change the size of iframe's viewport.
*/
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/client/orchestrator.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type { ResolvedConfig } from 'vitest'
import { channel, client } from '@vitest/browser/client'
import { generateHash } from '@vitest/runner/utils'
import { type GlobalChannelIncomingEvent, type IframeChannelEvent, type IframeChannelIncomingEvent, globalChannel } from '@vitest/browser/client'
import { relative } from 'pathe'
import type { SerializedConfig } from 'vitest'
import { getBrowserState, getConfig } from './utils'
import { getUiAPI } from './ui'
import { createModuleMocker } from './tester/msw'
Expand Down Expand Up @@ -230,7 +230,7 @@ async function done() {
await client.rpc.finishBrowserTests(getBrowserState().contextId)
}

async function getContainer(config: ResolvedConfig): Promise<HTMLDivElement> {
async function getContainer(config: SerializedConfig): Promise<HTMLDivElement> {
if (config.browser.ui) {
const element = document.querySelector('#tester-ui')
if (!element) {
Expand Down
10 changes: 5 additions & 5 deletions packages/browser/src/client/tester/runner.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { CancelReason, File, Suite, Task, TaskResultPack, VitestRunner } from '@vitest/runner'
import type { ResolvedConfig, WorkerGlobalState } from 'vitest'
import type { SerializedConfig, WorkerGlobalState } from 'vitest'
import type { VitestExecutor } from 'vitest/execute'
import { NodeBenchmarkRunner, VitestTestRunner } from 'vitest/runners'
import { loadDiffConfig, loadSnapshotSerializers, takeCoverageInsideWorker } from 'vitest/browser'
Expand All @@ -12,7 +12,7 @@ import { rpc } from './rpc'
import type { VitestBrowserClientMocker } from './mocker'

interface BrowserRunnerOptions {
config: ResolvedConfig
config: SerializedConfig
}

export const browserHashMap = new Map<
Expand All @@ -25,13 +25,13 @@ interface CoverageHandler {
}

export function createBrowserRunner(
runnerClass: { new (config: ResolvedConfig): VitestRunner },
runnerClass: { new (config: SerializedConfig): VitestRunner },
mocker: VitestBrowserClientMocker,
state: WorkerGlobalState,
coverageModule: CoverageHandler | null,
): { new (options: BrowserRunnerOptions): VitestRunner } {
return class BrowserTestRunner extends runnerClass implements VitestRunner {
public config: ResolvedConfig
public config: SerializedConfig
hashMap = browserHashMap
public sourceMapCache = new Map<string, any>()

Expand Down Expand Up @@ -140,7 +140,7 @@ let cachedRunner: VitestRunner | null = null
export async function initiateRunner(
state: WorkerGlobalState,
mocker: VitestBrowserClientMocker,
config: ResolvedConfig,
config: SerializedConfig,
) {
if (cachedRunner) {
return cachedRunner
Expand Down
6 changes: 3 additions & 3 deletions packages/browser/src/client/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ResolvedConfig, WorkerGlobalState } from 'vitest'
import type { SerializedConfig, WorkerGlobalState } from 'vitest'

export async function importId(id: string) {
const name = `/@id/${id}`.replace(/\\/g, '/')
Expand All @@ -10,15 +10,15 @@ export async function importFs(id: string) {
return getBrowserState().wrapModule(() => import(/* @vite-ignore */ name))
}

export function getConfig(): ResolvedConfig {
export function getConfig(): SerializedConfig {
return getBrowserState().config
}

export interface BrowserRunnerState {
files: string[]
runningFiles: string[]
moduleCache: WorkerGlobalState['moduleCache']
config: ResolvedConfig
config: SerializedConfig
provider: string
viteConfig: {
root: string
Expand Down
3 changes: 1 addition & 2 deletions packages/browser/src/node/commands/screenshot.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { mkdir } from 'node:fs/promises'
import { normalize } from 'node:path'
import type { BrowserCommand } from 'vitest/node'
import type { BrowserCommand, ResolvedConfig } from 'vitest/node'
import { basename, dirname, relative, resolve } from 'pathe'
import type { ResolvedConfig } from 'vitest'
import type { ScreenshotOptions } from '../../../context'
import { PlaywrightBrowserProvider } from '../providers/playwright'
import { WebdriverBrowserProvider } from '../providers/webdriver'
Expand Down
3 changes: 1 addition & 2 deletions packages/browser/src/node/resolveMock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@ import { existsSync, readFileSync, readdirSync } from 'node:fs'
import { builtinModules } from 'node:module'
import { basename, dirname, extname, isAbsolute, join, resolve } from 'pathe'
import type { PartialResolvedId } from 'rollup'
import type { ResolvedConfig } from 'vitest'
import type { ResolvedConfig, WorkspaceProject } from 'vitest/node'
import type { ResolvedConfig as ViteConfig } from 'vite'
import type { WorkspaceProject } from 'vitest/node'

export async function resolveMock(
project: WorkspaceProject,
Expand Down
4 changes: 2 additions & 2 deletions packages/browser/src/node/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import type {
import { join, resolve } from 'pathe'
import type { ErrorWithDiff } from '@vitest/utils'
import { slash } from '@vitest/utils'
import type { ResolvedConfig } from 'vitest'
import { type StackTraceParserOptions, parseErrorStacktrace, parseStacktrace } from '@vitest/utils/source-map'
import type { SerializedConfig } from 'vitest'
import { BrowserServerState } from './state'
import { getBrowserProvider } from './utils'
import { BrowserServerCDPHandler } from './cdp'
Expand Down Expand Up @@ -224,7 +224,7 @@ export class BrowserServer implements IBrowserServer {
}
}

function wrapConfig(config: ResolvedConfig): ResolvedConfig {
function wrapConfig(config: SerializedConfig): SerializedConfig {
return {
...config,
// workaround RegExp serialization
Expand Down
3 changes: 1 addition & 2 deletions packages/browser/src/node/serverOrchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,13 @@ export async function resolveOrchestrator(

const files = server.state.getContext(contextId!)?.files ?? []

const config = server.getSerializableConfig()
const injectorJs = typeof server.injectorJs === 'string'
? server.injectorJs
: await server.injectorJs

const injector = replacer(injectorJs, {
__VITEST_PROVIDER__: JSON.stringify(server.provider.name),
__VITEST_CONFIG__: JSON.stringify(config),
__VITEST_CONFIG__: JSON.stringify(server.getSerializableConfig()),
__VITEST_VITE_CONFIG__: JSON.stringify({
root: server.vite.config.root,
}),
Expand Down
6 changes: 2 additions & 4 deletions packages/browser/src/node/serverTester.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,9 @@ export async function resolveTester(
? server.injectorJs
: await server.injectorJs

const config = server.getSerializableConfig()

const injector = replacer(injectorJs, {
__VITEST_PROVIDER__: JSON.stringify(server.provider.name),
__VITEST_CONFIG__: JSON.stringify(config),
__VITEST_CONFIG__: JSON.stringify(server.getSerializableConfig()),
__VITEST_FILES__: JSON.stringify(files),
__VITEST_VITE_CONFIG__: JSON.stringify({
root: server.vite.config.root,
Expand All @@ -57,7 +55,7 @@ export async function resolveTester(
const testerScripts = await server.formatScripts(
project.config.browser.testerScripts,
)
const clientScript = `<script type="module" src="${config.base || '/'}@vite/client"></script>`
const clientScript = `<script type="module" src="${server.project.config.base || '/'}@vite/client"></script>`
const stateJs = typeof server.stateJs === 'string'
? server.stateJs
: await server.stateJs
Expand Down
4 changes: 2 additions & 2 deletions packages/runner/src/types/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import type {

export interface VitestRunnerConfig {
root: string
setupFiles: string[] | string
name: string
setupFiles: string[]
name?: string
passWithNoTests: boolean
testNamePattern?: RegExp
allowOnly?: boolean
Expand Down
2 changes: 1 addition & 1 deletion packages/runner/src/utils/collect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ export function calculateSuiteHash(parent: Suite): void {
export function createFileTask(
filepath: string,
root: string,
projectName: string,
projectName: string | undefined,
pool?: string,
): File {
const path = relative(root, filepath)
Expand Down
4 changes: 2 additions & 2 deletions packages/ui/client/composables/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createClient, getTasks } from '@vitest/ws-client'
import type { WebSocketStatus } from '@vueuse/core'
import type { File, ResolvedConfig, TaskResultPack } from 'vitest'
import type { File, SerializedConfig, TaskResultPack } from 'vitest'
import { reactive as reactiveVue } from 'vue'
import { createFileTask } from '@vitest/runner/utils'
import type { BrowserRunnerState } from '../../../types'
Expand Down Expand Up @@ -45,7 +45,7 @@ export const client = (function createVitestClient() {
}
})()

export const config = shallowRef<ResolvedConfig>({} as any)
export const config = shallowRef<SerializedConfig>({} as any)
export const status = ref<WebSocketStatus>('CONNECTING')

export const current = computed(() => {
Expand Down
4 changes: 2 additions & 2 deletions packages/ui/client/composables/client/static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { VitestClient } from '@vitest/ws-client'
import type {
File,
ModuleGraphData,
ResolvedConfig,
SerializedConfig,
WebSocketEvents,
WebSocketHandlers,
} from 'vitest'
Expand All @@ -14,7 +14,7 @@ import { StateManager } from '../../../../vitest/src/node/state'
interface HTMLReportMetadata {
paths: string[]
files: File[]
config: ResolvedConfig
config: SerializedConfig
moduleGraph: Record<string, Record<string, ModuleGraphData>>
unhandledErrors: unknown[]
// filename -> source
Expand Down
16 changes: 4 additions & 12 deletions packages/ui/client/composables/navigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ export const coverageConfigured = computed(() => coverage.value?.enabled)
export const coverageEnabled = computed(() => {
return (
coverageConfigured.value
&& coverage.value.reporter
.map(([reporterName]) => reporterName)
.includes('html')
&& !!coverage.value.htmlReporter
)
})
export const detailSizes = useLocalStorage<[left: number, right: number]>(
Expand All @@ -31,16 +29,10 @@ export const detailSizes = useLocalStorage<[left: number, right: number]>(
export const coverageUrl = computed(() => {
if (coverageEnabled.value) {
const idx = coverage.value!.reportsDirectory.lastIndexOf('/')
const htmlReporter = coverage.value!.reporter.find((reporter) => {
if (reporter[0] !== 'html') {
return undefined
}

return reporter
})
return htmlReporter && 'subdir' in htmlReporter[1]
const htmlReporterSubdir = coverage.value!.htmlReporter?.subdir
return htmlReporterSubdir
? `/${coverage.value!.reportsDirectory.slice(idx + 1)}/${
htmlReporter[1].subdir
htmlReporterSubdir
}/index.html`
: `/${coverage.value!.reportsDirectory.slice(idx + 1)}/index.html`
}
Expand Down
6 changes: 3 additions & 3 deletions packages/ui/node/reporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type {
File,
ModuleGraphData,
Reporter,
ResolvedConfig,
SerializedConfig,
Vitest,
} from 'vitest'
import type { HTMLOptions } from 'vitest/node'
Expand All @@ -35,7 +35,7 @@ function getOutputFile(config: PotentialConfig | undefined) {
interface HTMLReportData {
paths: string[]
files: File[]
config: ResolvedConfig
config: SerializedConfig
moduleGraph: Record<string, Record<string, ModuleGraphData>>
unhandledErrors: unknown[]
// filename -> source
Expand Down Expand Up @@ -63,7 +63,7 @@ export default class HTMLReporter implements Reporter {
const result: HTMLReportData = {
paths: this.ctx.state.getPaths(),
files: this.ctx.state.getFiles(),
config: this.ctx.config,
config: this.ctx.getCoreWorkspaceProject().getSerializableConfig(),
unhandledErrors: this.ctx.state.getUnhandledErrors(),
moduleGraph: {},
sources: {},
Expand Down
4 changes: 2 additions & 2 deletions packages/ui/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ResolvedConfig } from 'vitest'
import type { SerializedConfig } from 'vitest'

export interface WSMessage {
/**
Expand All @@ -16,7 +16,7 @@ export type RunState = 'idle' | 'running'

export interface BrowserRunnerState {
files: string[]
config: ResolvedConfig
config: SerializedConfig
type: 'orchestrator'
wrapModule: <T>(module: () => T) => T
}
2 changes: 1 addition & 1 deletion packages/vitest/src/api/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export function setup(ctx: Vitest, _server?: ViteDevServer) {
await ctx.rerunFiles(files)
},
getConfig() {
return ctx.config
return ctx.getCoreWorkspaceProject().getSerializableConfig()
},
async getTransformResult(projectName: string, id, browser = false) {
const project = ctx.getProjectByName(projectName)
Expand Down
7 changes: 4 additions & 3 deletions packages/vitest/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import type {
File,
ModuleGraphData,
Reporter,
ResolvedConfig,
SerializableSpec,
SerializedConfig,
TaskResultPack,
} from '../types'

Expand All @@ -16,9 +17,9 @@ export interface WebSocketHandlers {
onCollected: (files?: File[]) => Promise<void>
onTaskUpdate: (packs: TaskResultPack[]) => void
getFiles: () => File[]
getTestFiles: () => Promise<[{ name: string; root: string }, file: string][]>
getTestFiles: () => Promise<SerializableSpec[]>
getPaths: () => string[]
getConfig: () => ResolvedConfig
getConfig: () => SerializedConfig
getModuleGraph: (
projectName: string,
id: string,
Expand Down
2 changes: 2 additions & 0 deletions packages/vitest/src/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,8 @@ const config = {
clearMocks: false,
restoreMocks: false,
mockReset: false,
unstubGlobals: false,
unstubEnvs: false,
include: defaultInclude,
exclude: defaultExclude,
teardownTimeout: 10000,
Expand Down
Loading

0 comments on commit 3aab8a1

Please sign in to comment.