Skip to content

Commit

Permalink
refactor: enable isolatedDeclarations in snapshot and spy packages (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
sheremet-va authored Jul 16, 2024
1 parent a7636e3 commit a852b16
Show file tree
Hide file tree
Showing 18 changed files with 91 additions and 63 deletions.
2 changes: 1 addition & 1 deletion packages/coverage-istanbul/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const COVERAGE_STORE_KEY = '__VITEST_COVERAGE__'
export const COVERAGE_STORE_KEY: string = '__VITEST_COVERAGE__'
12 changes: 9 additions & 3 deletions packages/coverage-istanbul/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { COVERAGE_STORE_KEY } from './constants'
import type { IstanbulCoverageProvider } from './provider'

export async function getProvider() {
export async function getProvider(): Promise<IstanbulCoverageProvider> {
// to not bundle the provider
const providerPath = './provider.js'
const { IstanbulCoverageProvider } = (await import(
Expand All @@ -10,7 +11,7 @@ export async function getProvider() {
return new IstanbulCoverageProvider()
}

export function takeCoverage() {
export function takeCoverage(): any {
// @ts-expect-error -- untyped global
const coverage = globalThis[COVERAGE_STORE_KEY]

Expand All @@ -21,7 +22,12 @@ export function takeCoverage() {
return coverage
}

export default {
const _default: {
getProvider: () => Promise<IstanbulCoverageProvider>
takeCoverage: () => any
} = {
getProvider,
takeCoverage,
}

export default _default
29 changes: 15 additions & 14 deletions packages/coverage-istanbul/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,25 +57,23 @@ interface TestExclude {
}
}

const DEFAULT_PROJECT = Symbol.for('default-project')
const DEFAULT_PROJECT: unique symbol = Symbol.for('default-project')
const debug = createDebug('vitest:coverage')
let uniqueId = 0

export class IstanbulCoverageProvider
extends BaseCoverageProvider
implements CoverageProvider {
export class IstanbulCoverageProvider extends BaseCoverageProvider implements CoverageProvider {
name = 'istanbul'

ctx!: Vitest
options!: Options
instrumenter!: Instrumenter
testExclude!: InstanceType<TestExclude>

coverageFiles = new Map<ProjectName, CoverageFilesByTransformMode>()
coverageFiles: Map<ProjectName, CoverageFilesByTransformMode> = new Map()
coverageFilesDirectory!: string
pendingPromises: Promise<void>[] = []

initialize(ctx: Vitest) {
initialize(ctx: Vitest): void {
const config: CoverageIstanbulOptions = ctx.config.coverage

this.ctx = ctx
Expand Down Expand Up @@ -145,11 +143,14 @@ export class IstanbulCoverageProvider
)
}

resolveOptions() {
resolveOptions(): Options {
return this.options
}

onFileTransform(sourceCode: string, id: string, pluginCtx: any) {
onFileTransform(sourceCode: string, id: string, pluginCtx: any): {
code: string
map: any
} | undefined {
if (!this.testExclude.shouldInstrument(id)) {
return
}
Expand Down Expand Up @@ -178,7 +179,7 @@ export class IstanbulCoverageProvider
* Note that adding new entries here and requiring on those without
* backwards compatibility is a breaking change.
*/
onAfterSuiteRun({ coverage, transformMode, projectName }: AfterSuiteRunMeta) {
onAfterSuiteRun({ coverage, transformMode, projectName }: AfterSuiteRunMeta): void {
if (!coverage) {
return
}
Expand All @@ -204,7 +205,7 @@ export class IstanbulCoverageProvider
this.pendingPromises.push(promise)
}

async clean(clean = true) {
async clean(clean = true): Promise<void> {
if (clean && existsSync(this.options.reportsDirectory)) {
await fs.rm(this.options.reportsDirectory, {
recursive: true,
Expand All @@ -227,7 +228,7 @@ export class IstanbulCoverageProvider
this.pendingPromises = []
}

async generateCoverage({ allTestsRun }: ReportContext) {
async generateCoverage({ allTestsRun }: ReportContext): Promise<CoverageMap> {
const coverageMap = libCoverage.createCoverageMap({})
let index = 0
const total = this.pendingPromises.length
Expand Down Expand Up @@ -282,7 +283,7 @@ export class IstanbulCoverageProvider
return coverageMap
}

async reportCoverage(coverageMap: unknown, { allTestsRun }: ReportContext) {
async reportCoverage(coverageMap: unknown, { allTestsRun }: ReportContext): Promise<void> {
await this.generateReports(
(coverageMap as CoverageMap) || libCoverage.createCoverageMap({}),
allTestsRun,
Expand All @@ -305,7 +306,7 @@ export class IstanbulCoverageProvider
async generateReports(
coverageMap: CoverageMap,
allTestsRun: boolean | undefined,
) {
): Promise<void> {
const context = libReport.createContext({
dir: this.options.reportsDirectory,
coverageMap,
Expand Down Expand Up @@ -370,7 +371,7 @@ export class IstanbulCoverageProvider
}
}

async mergeReports(coverageMaps: unknown[]) {
async mergeReports(coverageMaps: unknown[]): Promise<void> {
const coverageMap = libCoverage.createCoverageMap({})

for (const coverage of coverageMaps) {
Expand Down
3 changes: 3 additions & 0 deletions packages/coverage-istanbul/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"moduleResolution": "Bundler"
},
"include": ["./src/**/*.ts"],
"exclude": ["./dist"]
}
14 changes: 12 additions & 2 deletions packages/coverage-v8/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import type { Profiler } from 'node:inspector'
import * as coverage from './takeCoverage'
import type { V8CoverageProvider } from './provider'

export default {
...coverage,
async getProvider() {
startCoverage(): void {
return coverage.startCoverage()
},
takeCoverage(): Promise<{ result: Profiler.ScriptCoverage[] }> {
return coverage.takeCoverage()
},
stopCoverage(): void {
return coverage.stopCoverage()
},
async getProvider(): Promise<V8CoverageProvider> {
// to not bundle the provider
const name = './provider.js'
const { V8CoverageProvider } = (await import(
Expand Down
24 changes: 11 additions & 13 deletions packages/coverage-v8/src/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,25 +73,23 @@ const VITE_EXPORTS_LINE_PATTERN
= /Object\.defineProperty\(__vite_ssr_exports__.*\n/g
const DECORATOR_METADATA_PATTERN
= /_ts_metadata\("design:paramtypes", \[[^\]]*\]\),*/g
const DEFAULT_PROJECT = Symbol.for('default-project')
const DEFAULT_PROJECT: unique symbol = Symbol.for('default-project')

const debug = createDebug('vitest:coverage')
let uniqueId = 0

export class V8CoverageProvider
extends BaseCoverageProvider
implements CoverageProvider {
export class V8CoverageProvider extends BaseCoverageProvider implements CoverageProvider {
name = 'v8'

ctx!: Vitest
options!: Options
testExclude!: InstanceType<TestExclude>

coverageFiles = new Map<ProjectName, CoverageFilesByTransformMode>()
coverageFiles: Map<ProjectName, CoverageFilesByTransformMode> = new Map()
coverageFilesDirectory!: string
pendingPromises: Promise<void>[] = []

initialize(ctx: Vitest) {
initialize(ctx: Vitest): void {
const config: CoverageV8Options = ctx.config.coverage

this.ctx = ctx
Expand Down Expand Up @@ -142,11 +140,11 @@ export class V8CoverageProvider
)
}

resolveOptions() {
resolveOptions(): Options {
return this.options
}

async clean(clean = true) {
async clean(clean = true): Promise<void> {
if (clean && existsSync(this.options.reportsDirectory)) {
await fs.rm(this.options.reportsDirectory, {
recursive: true,
Expand Down Expand Up @@ -174,7 +172,7 @@ export class V8CoverageProvider
* Note that adding new entries here and requiring on those without
* backwards compatibility is a breaking change.
*/
onAfterSuiteRun({ coverage, transformMode, projectName }: AfterSuiteRunMeta) {
onAfterSuiteRun({ coverage, transformMode, projectName }: AfterSuiteRunMeta): void {
if (transformMode !== 'web' && transformMode !== 'ssr') {
throw new Error(`Invalid transform mode: ${transformMode}`)
}
Expand All @@ -196,7 +194,7 @@ export class V8CoverageProvider
this.pendingPromises.push(promise)
}

async generateCoverage({ allTestsRun }: ReportContext) {
async generateCoverage({ allTestsRun }: ReportContext): Promise<CoverageMap> {
const coverageMap = libCoverage.createCoverageMap({})
let index = 0
const total = this.pendingPromises.length
Expand Down Expand Up @@ -255,7 +253,7 @@ export class V8CoverageProvider
return coverageMap
}

async reportCoverage(coverageMap: unknown, { allTestsRun }: ReportContext) {
async reportCoverage(coverageMap: unknown, { allTestsRun }: ReportContext): Promise<void> {
if (provider === 'stackblitz') {
this.ctx.logger.log(
c.blue(' % ')
Expand Down Expand Up @@ -284,7 +282,7 @@ export class V8CoverageProvider
}
}

async generateReports(coverageMap: CoverageMap, allTestsRun?: boolean) {
async generateReports(coverageMap: CoverageMap, allTestsRun?: boolean): Promise<void> {
const context = libReport.createContext({
dir: this.options.reportsDirectory,
coverageMap,
Expand Down Expand Up @@ -349,7 +347,7 @@ export class V8CoverageProvider
}
}

async mergeReports(coverageMaps: unknown[]) {
async mergeReports(coverageMaps: unknown[]): Promise<void> {
const coverageMap = libCoverage.createCoverageMap({})

for (const coverage of coverageMaps) {
Expand Down
6 changes: 3 additions & 3 deletions packages/coverage-v8/src/takeCoverage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { provider } from 'std-env'

const session = new inspector.Session()

export function startCoverage() {
export function startCoverage(): void {
session.connect()
session.post('Profiler.enable')
session.post('Profiler.startPreciseCoverage', {
Expand All @@ -17,7 +17,7 @@ export function startCoverage() {
})
}

export async function takeCoverage() {
export async function takeCoverage(): Promise<{ result: Profiler.ScriptCoverage[] }> {
return new Promise((resolve, reject) => {
session.post('Profiler.takePreciseCoverage', async (error, coverage) => {
if (error) {
Expand All @@ -36,7 +36,7 @@ export async function takeCoverage() {
})
}

export function stopCoverage() {
export function stopCoverage(): void {
session.post('Profiler.stopPreciseCoverage')
session.post('Profiler.disable')
session.disconnect()
Expand Down
3 changes: 3 additions & 0 deletions packages/coverage-v8/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"moduleResolution": "Bundler"
},
"include": ["./src/**/*.ts"],
"exclude": ["./dist"]
}
16 changes: 8 additions & 8 deletions packages/snapshot/src/client.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { deepMergeSnapshot } from './port/utils'
import SnapshotState from './port/state'
import type { SnapshotStateOptions } from './types'
import type { SnapshotResult, SnapshotStateOptions } from './types'
import type { RawSnapshotInfo } from './port/rawSnapshot'

function createMismatchError(
Expand Down Expand Up @@ -53,15 +53,15 @@ export class SnapshotClient {
filepath?: string
name?: string
snapshotState: SnapshotState | undefined
snapshotStateMap = new Map<string, SnapshotState>()
snapshotStateMap: Map<string, SnapshotState> = new Map()

constructor(private options: SnapshotClientOptions = {}) {}

async startCurrentRun(
filepath: string,
name: string,
options: SnapshotStateOptions,
) {
): Promise<void> {
this.filepath = filepath
this.name = name

Expand All @@ -78,16 +78,16 @@ export class SnapshotClient {
}
}

getSnapshotState(filepath: string) {
getSnapshotState(filepath: string): SnapshotState {
return this.snapshotStateMap.get(filepath)!
}

clearTest() {
clearTest(): void {
this.filepath = undefined
this.name = undefined
}

skipTestSnapshots(name: string) {
skipTestSnapshots(name: string): void {
this.snapshotState?.markSnapshotsAsCheckedForTest(name)
}

Expand Down Expand Up @@ -189,7 +189,7 @@ export class SnapshotClient {
return this.assert(options)
}

async finishCurrentRun() {
async finishCurrentRun(): Promise<SnapshotResult | null> {
if (!this.snapshotState) {
return null
}
Expand All @@ -199,7 +199,7 @@ export class SnapshotClient {
return result
}

clear() {
clear(): void {
this.snapshotStateMap.clear()
}
}
2 changes: 1 addition & 1 deletion packages/snapshot/src/env/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export class NodeSnapshotEnvironment implements SnapshotEnvironment {
return `// Snapshot v${this.getVersion()}`
}

async resolveRawPath(testPath: string, rawPath: string) {
async resolveRawPath(testPath: string, rawPath: string): Promise<string> {
return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath)
}

Expand Down
11 changes: 5 additions & 6 deletions packages/snapshot/src/manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,17 @@ export class SnapshotManager {
this.clear()
}

clear() {
clear(): void {
this.summary = emptySummary(this.options)
}

add(result: SnapshotResult) {
add(result: SnapshotResult): void {
addSnapshotResult(this.summary, result)
}

resolvePath(testPath: string) {
resolvePath(testPath: string): string {
const resolver
= this.options.resolveSnapshotPath
|| (() => {
= this.options.resolveSnapshotPath || (() => {
return join(
join(dirname(testPath), '__snapshots__'),
`${basename(testPath)}${this.extension}`,
Expand All @@ -37,7 +36,7 @@ export class SnapshotManager {
return path
}

resolveRawPath(testPath: string, rawPath: string) {
resolveRawPath(testPath: string, rawPath: string): string {
return isAbsolute(rawPath) ? rawPath : resolve(dirname(testPath), rawPath)
}
}
Expand Down
Loading

0 comments on commit a852b16

Please sign in to comment.