Skip to content

Commit

Permalink
fix(coverage): c8 to ignore vite's generated helpers (#3241)
Browse files Browse the repository at this point in the history
  • Loading branch information
AriPerkkio authored Apr 25, 2023
1 parent be0844c commit 21942db
Show file tree
Hide file tree
Showing 10 changed files with 947 additions and 469 deletions.
2 changes: 2 additions & 0 deletions packages/coverage-c8/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@
"vitest": ">=0.30.0 <1"
},
"dependencies": {
"@ampproject/remapping": "^2.2.0",
"c8": "^7.13.0",
"magic-string": "^0.30.0",
"picocolors": "^1.0.0",
"std-env": "^3.3.2"
},
Expand Down
31 changes: 30 additions & 1 deletion packages/coverage-c8/src/provider.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { existsSync, promises as fs } from 'node:fs'
import _url from 'node:url'
import type { Profiler } from 'node:inspector'
import MagicString from 'magic-string'
import remapping from '@ampproject/remapping'
import { extname, resolve } from 'pathe'
import c from 'picocolors'
import { provider } from 'std-env'
Expand All @@ -18,6 +20,9 @@ import { checkCoverages } from 'c8/lib/commands/check-coverage.js'

type Options = ResolvedCoverageOptions<'c8'>

// Note that this needs to match the line ending as well
const VITE_EXPORTS_LINE_PATTERN = /Object\.defineProperty\(__vite_ssr_exports__.*\n/g

export class C8CoverageProvider extends BaseCoverageProvider implements CoverageProvider {
name = 'c8'

Expand Down Expand Up @@ -169,7 +174,7 @@ export class C8CoverageProvider extends BaseCoverageProvider implements Coverage

return {
sourceMap: {
sourcemap: data.map,
sourcemap: removeViteHelpersFromSourceMaps(data.source, data.map),
},
source: Array(offset).fill('.').join('') + data.source,
}
Expand All @@ -193,3 +198,27 @@ export class C8CoverageProvider extends BaseCoverageProvider implements Coverage
}
}
}

/**
* Remove generated code from the source maps:
* - Vite's export helpers: e.g. `Object.defineProperty(__vite_ssr_exports__, "sum", { enumerable: true, configurable: true, get(){ return sum }});`
*/
function removeViteHelpersFromSourceMaps(source: string | undefined, map: EncodedSourceMap) {
if (!source || !source.match(VITE_EXPORTS_LINE_PATTERN))
return map

const sourceWithoutHelpers = new MagicString(source)
sourceWithoutHelpers.replaceAll(VITE_EXPORTS_LINE_PATTERN, '\n')

const mapWithoutHelpers = sourceWithoutHelpers.generateMap({
hires: true,
})

// A merged source map where the first one excludes helpers
const combinedMap = remapping(
[{ ...mapWithoutHelpers, version: 3 }, map],
() => null,
)

return combinedMap
}
12 changes: 12 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 21942db

Please sign in to comment.