Skip to content

Commit

Permalink
refactor: make a distinction between node and runtime types (#6214)
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Jul 24, 2024
1 parent 1affb99 commit 56dbfa6
Show file tree
Hide file tree
Showing 125 changed files with 866 additions and 778 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
},
"pnpm": {
"overrides": {
"acorn": "8.11.3",
"mlly": "^1.7.1",
"rollup": "$rollup",
"vite": "$vite",
Expand Down
21 changes: 21 additions & 0 deletions packages/vitest/LICENSE.md
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,27 @@ License: MIT
By: Mathias Bynens
Repository: https://github.com/mathiasbynens/emoji-regex.git

> Copyright Mathias Bynens <https://mathiasbynens.be/>
>
> Permission is hereby granted, free of charge, to any person obtaining
> a copy of this software and associated documentation files (the
> "Software"), to deal in the Software without restriction, including
> without limitation the rights to use, copy, modify, merge, publish,
> distribute, sublicense, and/or sell copies of the Software, and to
> permit persons to whom the Software is furnished to do so, subject to
> the following conditions:
>
> The above copyright notice and this permission notice shall be
> included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
> NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
> LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
> OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
> WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---------------------------------------

## expect-type
Expand Down
45 changes: 9 additions & 36 deletions packages/vitest/rollup.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from 'node:fs'
import { builtinModules, createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import { dirname, join, normalize, relative, resolve } from 'pathe'
import { dirname, join, normalize, resolve } from 'pathe'
import esbuild from 'rollup-plugin-esbuild'
import dts from 'rollup-plugin-dts'
import nodeResolve from '@rollup/plugin-node-resolve'
Expand All @@ -17,13 +17,13 @@ const pkg = require('./package.json')

const entries = {
'path': 'src/paths.ts',
'index': 'src/index.ts',
'index': 'src/public/index.ts',
'cli': 'src/node/cli.ts',
'node': 'src/node.ts',
'node': 'src/public/node.ts',
'suite': 'src/suite.ts',
'browser': 'src/browser.ts',
'runners': 'src/runners.ts',
'environments': 'src/environments.ts',
'environments': 'src/public/environments.ts',
'spy': 'src/integrations/spy.ts',
'coverage': 'src/coverage.ts',
'utils': 'src/public/utils.ts',
Expand All @@ -45,9 +45,9 @@ const entries = {
}

const dtsEntries = {
index: 'src/index.ts',
node: 'src/node.ts',
environments: 'src/environments.ts',
index: 'src/public/index.ts',
node: 'src/public/node.ts',
environments: 'src/public/environments.ts',
browser: 'src/browser.ts',
runners: 'src/runners.ts',
suite: 'src/suite.ts',
Expand Down Expand Up @@ -107,35 +107,7 @@ export default ({ watch }) =>
output: {
dir: 'dist',
format: 'esm',
chunkFileNames: (chunkInfo) => {
let id
= chunkInfo.facadeModuleId
|| Object.keys(chunkInfo.moduleIds).find(
i =>
!i.includes('node_modules')
&& (i.includes('src/') || i.includes('src\\')),
)
if (id) {
id = normalize(id)
const parts = Array.from(
new Set(
relative(process.cwd(), id)
.split(/\//g)
.map(i => i.replace(/\..*$/, ''))
.filter(
i =>
!['src', 'index', 'dist', 'node_modules'].some(j =>
i.includes(j),
) && i.match(/^[\w-]+$/),
),
),
)
if (parts.length) {
return `chunks/${parts.slice(-2).join('-')}.[hash].js`
}
}
return 'vendor/[name].[hash].js'
},
chunkFileNames: 'chunks/[name].[hash].js',
},
external,
plugins: [...plugins, !watch && licensePlugin()],
Expand Down Expand Up @@ -163,6 +135,7 @@ export default ({ watch }) =>
entryFileNames: chunk =>
`${normalize(chunk.name).replace('src/', '')}.d.ts`,
format: 'esm',
chunkFileNames: 'chunks/[name].[hash].d.ts',
},
external,
plugins: [dts({ respectExternal: true })],
Expand Down
17 changes: 6 additions & 11 deletions packages/vitest/src/api/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,14 @@ import { parse, stringify } from 'flatted'
import type { WebSocket } from 'ws'
import { WebSocketServer } from 'ws'
import type { ViteDevServer } from 'vite'
import type { File, TaskResultPack } from '@vitest/runner'
import { API_PATH } from '../constants'
import type { Vitest } from '../node'
import type {
Awaitable,
File,
ModuleGraphData,
Reporter,
SerializableSpec,
TaskResultPack,
UserConsoleLog,
} from '../types'
import type { Vitest } from '../node/core'
import type { Awaitable, ModuleGraphData, UserConsoleLog } from '../types/general'
import type { Reporter } from '../node/types/reporter'
import { getModuleGraph, isPrimitive, noop, stringifyReplace } from '../utils'
import { parseErrorStacktrace } from '../utils/source-map'
import type { SerializedSpec } from '../runtime/types/utils'
import type {
TransformResultWithSource,
WebSocketEvents,
Expand Down Expand Up @@ -165,7 +160,7 @@ export class WebSocketReporter implements Reporter {
})
}

onSpecsCollected(specs?: SerializableSpec[] | undefined): Awaitable<void> {
onSpecsCollected(specs?: SerializedSpec[] | undefined): Awaitable<void> {
if (this.clients.size === 0) {
return
}
Expand Down
56 changes: 35 additions & 21 deletions packages/vitest/src/api/types.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,36 @@
import type { TransformResult } from 'vite'
import type { BirpcReturn } from 'birpc'
import type {
File,
ModuleGraphData,
Reporter,
SerializableSpec,
SerializedConfig,
TaskResultPack,
} from '../types'
import type { File, TaskResultPack } from '@vitest/runner'
import type { Awaitable, ModuleGraphData, UserConsoleLog } from '../types/general'
import type { SerializedConfig } from '../runtime/config'
import type { SerializedSpec } from '../runtime/types/utils'

export interface TransformResultWithSource extends TransformResult {
interface SourceMap {
file: string
mappings: string
names: string[]
sources: string[]
sourcesContent?: string[]
version: number
toString: () => string
toUrl: () => string
}

export interface TransformResultWithSource {
code: string
map: SourceMap | {
mappings: ''
} | null
etag?: string
deps?: string[]
dynamicDeps?: string[]
source?: string
}

export interface WebSocketHandlers {
onCollected: (files?: File[]) => Promise<void>
onTaskUpdate: (packs: TaskResultPack[]) => void
getFiles: () => File[]
getTestFiles: () => Promise<SerializableSpec[]>
getTestFiles: () => Promise<SerializedSpec[]>
getPaths: () => string[]
getConfig: () => SerializedConfig
getModuleGraph: (
Expand All @@ -37,16 +50,17 @@ export interface WebSocketHandlers {
getUnhandledErrors: () => unknown[]
}

export interface WebSocketEvents
extends Pick<
Reporter,
| 'onCollected'
| 'onFinished'
| 'onTaskUpdate'
| 'onUserConsoleLog'
| 'onPathsCollected'
| 'onSpecsCollected'
> {
export interface WebSocketEvents {
onCollected?: (files?: File[]) => Awaitable<void>
onFinished?: (
files: File[],
errors: unknown[],
coverage?: unknown
) => Awaitable<void>
onTaskUpdate?: (packs: TaskResultPack[]) => Awaitable<void>
onUserConsoleLog?: (log: UserConsoleLog) => Awaitable<void>
onPathsCollected?: (paths?: string[]) => Awaitable<void>
onSpecsCollected?: (specs?: SerializedSpec[]) => Awaitable<void>
onFinishedReportCoverage: () => void
}

Expand Down
4 changes: 3 additions & 1 deletion packages/vitest/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import './node/types/vite'

import type { ConfigEnv, UserConfig as ViteUserConfig } from 'vite'
import type { ProjectConfig } from './types'
import type { ProjectConfig } from './node/types/config'

export interface UserWorkspaceConfig extends ViteUserConfig {
test?: ProjectConfig
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/create/browser/creator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { Agent } from '@antfu/install-pkg'
import { detectPackageManager, installPackage } from '@antfu/install-pkg'
import { findUp } from 'find-up'
import { execa } from 'execa'
import type { BrowserBuiltinProvider } from '../../types/browser'
import type { BrowserBuiltinProvider } from '../../node/types/browser'
import { configFiles } from '../../constants'
import { generateExampleFiles } from './examples'

Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type {
CoverageV8Options,
ResolvedCoverageOptions,
UserConfig,
} from './types'
} from './node/types/config'
import { isCI } from './utils/env'

export { defaultBrowserPort } from './constants'
Expand Down
2 changes: 0 additions & 2 deletions packages/vitest/src/environments.ts

This file was deleted.

22 changes: 0 additions & 22 deletions packages/vitest/src/index.ts

This file was deleted.

5 changes: 2 additions & 3 deletions packages/vitest/src/integrations/chai/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,9 @@ import {
getState,
setState,
} from '@vitest/expect'
import type { Assertion, ExpectStatic } from '@vitest/expect'
import type { MatcherState } from '../../types/chai'
import type { Assertion, ExpectStatic, MatcherState } from '@vitest/expect'
import { getTestName } from '../../utils/tasks'
import { getCurrentEnvironment, getWorkerState } from '../../utils/global'
import { getCurrentEnvironment, getWorkerState } from '../../runtime/utils'
import { createExpectPoll } from './poll'

export function createExpect(test?: TaskPopulated) {
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/coverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { SerializedCoverageConfig } from '../runtime/config'
import type {
CoverageProvider,
CoverageProviderModule,
} from '../types'
} from '../node/types/coverage'

interface Loader {
executeId: (id: string) => Promise<{ default: CoverageProviderModule }>
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/css/css-modules.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { createHash } from 'node:crypto'
import type { CSSModuleScopeStrategy } from '../../types'
import type { CSSModuleScopeStrategy } from '../../node/types/config'

export function generateCssFilenameHash(filepath: string) {
return createHash('md5').update(filepath).digest('hex').slice(0, 6)
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/env/edge-runtime.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Environment } from '../../types'
import type { Environment } from '../../types/environment'
import { populateGlobal } from './utils'
import { KEYS } from './jsdom-keys'

Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/env/happy-dom.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Environment } from '../../types'
import type { Environment } from '../../types/environment'
import { populateGlobal } from './utils'

async function teardownWindow(win: {
Expand Down
23 changes: 0 additions & 23 deletions packages/vitest/src/integrations/env/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { VitestEnvironment } from '../../types/config'
import node from './node'
import jsdom from './jsdom'
import happy from './happy-dom'
Expand All @@ -12,25 +11,3 @@ export const environments = {
}

export const envs = Object.keys(environments)

export const envPackageNames: Record<
Exclude<keyof typeof environments, 'node'>,
string
> = {
'jsdom': 'jsdom',
'happy-dom': 'happy-dom',
'edge-runtime': '@edge-runtime/vm',
}

export function getEnvPackageName(env: VitestEnvironment) {
if (env === 'node') {
return null
}
if (env in envPackageNames) {
return (envPackageNames as any)[env]
}
if (env[0] === '.' || env[0] === '/') {
return null
}
return `vitest-environment-${env}`
}
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/env/jsdom.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Environment } from '../../types'
import type { Environment } from '../../types/environment'
import { populateGlobal } from './utils'

function catchWindowErrors(window: Window) {
Expand Down
5 changes: 3 additions & 2 deletions packages/vitest/src/integrations/env/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@ import { readFileSync } from 'node:fs'
import { normalize, resolve } from 'pathe'
import { ViteNodeRunner } from 'vite-node/client'
import type { ViteNodeRunnerOptions } from 'vite-node'
import type { BuiltinEnvironment, VitestEnvironment } from '../../types/config'
import type { ContextRPC, Environment, WorkerRPC } from '../../types'
import type { BuiltinEnvironment, VitestEnvironment } from '../../node/types/config'
import type { ContextRPC, WorkerRPC } from '../../types/worker'
import type { Environment } from '../../types/environment'
import { environments } from './index'

function isBuiltinEnvironment(
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/env/node.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Console } from 'node:console'
import type { Environment } from '../../types'
import type { Environment } from '../../types/environment'

// some globals we do not want, either because deprecated or we set it ourselves
const denyList = new Set([
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/globals.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { globalApis } from '../constants'
import * as index from '../index'
import * as index from '../public/index'

export function registerApiGlobally() {
globalApis.forEach((api) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/inject.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ProvidedContext } from '../types/general'
import { getWorkerState } from '../utils/global'
import { getWorkerState } from '../runtime/utils'

/**
* Gives access to injected context provided from the main thread.
Expand Down
2 changes: 1 addition & 1 deletion packages/vitest/src/integrations/run-once.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getWorkerState } from '../utils/global'
import { getWorkerState } from '../runtime/utils'

const filesCount = new Map<string, number>()
const cache = new Map<string, any>()
Expand Down
Loading

0 comments on commit 56dbfa6

Please sign in to comment.