Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: show correct stack trace in errors and console #2248

Merged
merged 15 commits into from Nov 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/vite-node/README.md
Expand Up @@ -56,6 +56,7 @@ In Vite Node, the server and runner (client) are separated, so you can integrate
import { createServer } from 'vite'
import { ViteNodeServer } from 'vite-node/server'
import { ViteNodeRunner } from 'vite-node/client'
import { installSourcemapsSupport } from 'vite-node/source-map'

// create vite server
const server = await createServer({
Expand All @@ -70,6 +71,11 @@ await server.pluginContainer.buildStart({})
// create vite-node server
const node = new ViteNodeServer(server)

// fixes stacktraces in Errors
installSourcemapsSupport({
getSourceMap: source => node.getSourceMap(source),
})

// create vite-node runner
const runner = new ViteNodeRunner({
root: server.config.root,
Expand Down
7 changes: 7 additions & 0 deletions packages/vite-node/package.json
Expand Up @@ -39,6 +39,11 @@
"types": "./dist/hmr.d.ts",
"require": "./dist/hmr.cjs",
"import": "./dist/hmr.mjs"
},
"./source-map": {
"types": "./dist/source-map.d.ts",
"require": "./dist/source-map.cjs",
"import": "./dist/source-map.mjs"
}
},
"main": "./dist/index.mjs",
Expand Down Expand Up @@ -73,10 +78,12 @@
"debug": "^4.3.4",
"mlly": "^0.5.16",
"pathe": "^0.2.0",
"source-map-support": "^0.5.21",
"vite": "^3.0.0"
},
"devDependencies": {
"@types/debug": "^4.1.7",
"@types/source-map-support": "^0.5.6",
"cac": "^6.7.14",
"picocolors": "^1.0.0",
"rollup": "^2.79.1"
Expand Down
15 changes: 8 additions & 7 deletions packages/vite-node/rollup.config.js
Expand Up @@ -9,13 +9,14 @@ import { defineConfig } from 'rollup'
import pkg from './package.json'

const entries = {
index: 'src/index.ts',
server: 'src/server.ts',
types: 'src/types.ts',
client: 'src/client.ts',
utils: 'src/utils.ts',
cli: 'src/cli.ts',
hmr: 'src/hmr/index.ts',
'index': 'src/index.ts',
'server': 'src/server.ts',
'types': 'src/types.ts',
'client': 'src/client.ts',
'utils': 'src/utils.ts',
'cli': 'src/cli.ts',
'hmr': 'src/hmr/index.ts',
'source-map': 'src/source-map.ts',
}

const external = [
Expand Down
5 changes: 5 additions & 0 deletions packages/vite-node/src/cli.ts
Expand Up @@ -7,6 +7,7 @@ import { ViteNodeRunner } from './client'
import type { ViteNodeServerOptions } from './types'
import { toArray } from './utils'
import { createHotContext, handleMessage, viteNodeHmrPlugin } from './hmr'
import { installSourcemapsSupport } from './source-map'

const cli = cac('vite-node')

Expand Down Expand Up @@ -58,6 +59,10 @@ async function run(files: string[], options: CliOptions = {}) {

const node = new ViteNodeServer(server, serverOptions)

installSourcemapsSupport({
getSourceMap: source => node.getSourceMap(source),
})

const runner = new ViteNodeRunner({
root: server.config.root,
base: server.config.base,
Expand Down
28 changes: 26 additions & 2 deletions packages/vite-node/src/client.ts
Expand Up @@ -109,6 +109,23 @@ export class ModuleCacheMap extends Map<string, ModuleCache> {
}
return invalidated
}

/**
* Return parsed source map based on inlined source map of the module
*/
getSourceMap(id: string) {
const fsPath = this.normalizePath(id)
const cache = this.get(fsPath)
if (cache.map)
return cache.map
const mapString = cache?.code?.match(/\/\/# sourceMappingURL=data:application\/json;charset=utf-8;base64,(.+)/)?.[1]
if (mapString) {
const map = JSON.parse(Buffer.from(mapString, 'base64').toString('utf-8'))
cache.map = map
return map
}
return null
}
}

export class ViteNodeRunner {
Expand Down Expand Up @@ -136,6 +153,10 @@ export class ViteNodeRunner {
return await this.cachedRequest(id, [])
}

getSourceMap(id: string) {
return this.moduleCache.getSourceMap(id)
}

/** @internal */
async cachedRequest(rawId: string, callstack: string[]) {
const id = normalizeRequestId(rawId, this.options.base)
Expand Down Expand Up @@ -293,7 +314,7 @@ export class ViteNodeRunner {
// Be careful when changing this
// changing context will change amount of code added on line :114 (vm.runInThisContext)
// this messes up sourcemaps for coverage
// adjust `offset` variable in packages/vitest/src/integrations/coverage/c8.ts#86 if you do change this
// adjust `offset` variable in packages/coverage-c8/src/provider.ts#86 if you do change this
const context = this.prepareContext({
// esm transformed by Vite
__vite_ssr_import__: request,
Expand All @@ -318,9 +339,12 @@ export class ViteNodeRunner {
transformed = transformed.replace(/^\#\!.*/, s => ' '.repeat(s.length))

// add 'use strict' since ESM enables it by default
const fn = vm.runInThisContext(`'use strict';async (${Object.keys(context).join(',')})=>{{${transformed}\n}}`, {
const codeDefinition = `'use strict';async (${Object.keys(context).join(',')})=>{{`
const code = `${codeDefinition}${transformed}\n}}`
const fn = vm.runInThisContext(code, {
filename: fsPath,
lineOffset: 0,
columnOffset: -codeDefinition.length,
})

await fn(...Object.values(context))
Expand Down
8 changes: 8 additions & 0 deletions packages/vite-node/src/server.ts
Expand Up @@ -73,6 +73,14 @@ export class ViteNodeServer {
return this.server.pluginContainer.resolveId(id, importer, { ssr: mode === 'ssr' })
}

getSourceMap(source: string) {
const fetchResult = this.fetchCache.get(source)?.result
if (fetchResult?.map)
return fetchResult.map
const ssrTransformResult = this.server.moduleGraph.getModuleById(source)?.ssrTransformResult
return (ssrTransformResult?.map || null) as unknown as RawSourceMap | null
}

async fetchModule(id: string): Promise<FetchResult> {
// reuse transform for concurrent requests
if (!this.fetchPromiseMap.has(id)) {
Expand Down
23 changes: 23 additions & 0 deletions packages/vite-node/src/source-map.ts
@@ -0,0 +1,23 @@
import { install } from 'source-map-support'
import type { RawSourceMap } from './types'

interface InstallSourceMapSupportOptions {
getSourceMap: (source: string) => RawSourceMap | null | undefined
}

export function installSourcemapsSupport(options: InstallSourceMapSupportOptions) {
install({
environment: 'node',
handleUncaughtExceptions: false,
retrieveSourceMap(source) {
const map = options.getSourceMap(source)
if (map) {
return {
url: source,
map,
}
}
return null
},
})
}
1 change: 1 addition & 0 deletions packages/vite-node/src/types.ts
Expand Up @@ -45,6 +45,7 @@ export interface ModuleCache {
promise?: Promise<any>
exports?: any
code?: string
map?: RawSourceMap
/**
* Module ids that imports this module
*/
Expand Down
62 changes: 59 additions & 3 deletions packages/vitest/LICENSE.md
Expand Up @@ -335,6 +335,34 @@ Repository: micromatch/braces

---------------------------------------

## buffer-from
License: MIT
Repository: LinusU/buffer-from

> MIT License
>
> Copyright (c) 2016, 2018 Linus Unnebäck
>
> 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.

---------------------------------------

## cac
License: MIT
By: egoist
Expand Down Expand Up @@ -1806,10 +1834,10 @@ Repository: chalk/slice-ansi

---------------------------------------

## source-map-js
## source-map
License: BSD-3-Clause
By: Valentin 7rulnik Semirulnik, Nick Fitzgerald, Tobias Koppers, Duncan Beevers, Stephen Crane, Ryan Seddon, Miles Elam, Mihai Bazon, Michael Ficarra, Todd Wolfson, Alexander Solovyov, Felix Gnass, Conrad Irwin, usrbincc, David Glasser, Chase Douglas, Evan Wallace, Heather Arthur, Hugh Kennedy, Simon Lydell, Jmeas Smith, Michael Z Goddard, azu, John Gozde, Adam Kirkton, Chris Montgomery, J. Ryan Stinnett, Jack Herrington, Chris Truter, Daniel Espeset, Jamie Wong, Eddy Bruël, Hawken Rives, Gilad Peleg, djchie, Gary Ye, Nicolas Lalevée
Repository: 7rulnik/source-map-js
By: Nick Fitzgerald, Tobias Koppers, Duncan Beevers, Stephen Crane, Ryan Seddon, Miles Elam, Mihai Bazon, Michael Ficarra, Todd Wolfson, Alexander Solovyov, Felix Gnass, Conrad Irwin, usrbincc, David Glasser, Chase Douglas, Evan Wallace, Heather Arthur, Hugh Kennedy, Simon Lydell, Jmeas Smith, Michael Z Goddard, azu, John Gozde, Adam Kirkton, Chris Montgomery, J. Ryan Stinnett, Jack Herrington, Chris Truter, Daniel Espeset, Jamie Wong, Eddy Bruël, Hawken Rives, Gilad Peleg, djchie, Gary Ye, Nicolas Lalevée
Repository: http://github.com/mozilla/source-map.git

> Copyright (c) 2009-2011, Mozilla Foundation and contributors
> All rights reserved.
Expand Down Expand Up @@ -1841,6 +1869,34 @@ Repository: 7rulnik/source-map-js

---------------------------------------

## source-map-support
License: MIT
Repository: https://github.com/evanw/node-source-map-support

> The MIT License (MIT)
>
> Copyright (c) 2014 Evan Wallace
>
> 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.

---------------------------------------

## sourcemap-codec
License: MIT
By: Rich Harris
Expand Down
1 change: 0 additions & 1 deletion packages/vitest/package.json
Expand Up @@ -152,7 +152,6 @@
"pretty-format": "^27.5.1",
"prompts": "^2.4.2",
"rollup": "^2.79.1",
"source-map-js": "^1.0.2",
"strip-ansi": "^7.0.1",
"typescript": "^4.8.4",
"vite-node": "workspace:*",
Expand Down
6 changes: 0 additions & 6 deletions packages/vitest/src/api/setup.ts
Expand Up @@ -8,7 +8,6 @@ import type { ModuleNode } from 'vite'
import { API_PATH } from '../constants'
import type { Vitest } from '../node'
import type { File, ModuleGraphData, Reporter, TaskResultPack, UserConsoleLog } from '../types'
import { interpretSourcePos, parseStacktrace } from '../utils/source-map'
import type { TransformResultWithSource, WebSocketEvents, WebSocketHandlers } from './types'

export function setup(ctx: Vitest) {
Expand Down Expand Up @@ -154,11 +153,6 @@ class WebSocketReporter implements Reporter {
if (this.clients.size === 0)
return

await Promise.all(packs.map(async (i) => {
if (i[1]?.error)
await interpretSourcePos(parseStacktrace(i[1].error as any), this.ctx)
}))

this.clients.forEach((client) => {
client.onTaskUpdate?.(packs)
})
Expand Down
@@ -1,7 +1,6 @@
import { promises as fs } from 'fs'
import type MagicString from 'magic-string'
import { rpc } from '../../../runtime/rpc'
import { getOriginalPos, lineSplitRE, numberToPos, posToNumber } from '../../../utils/source-map'
import { lineSplitRE, numberToPos, posToNumber } from '../../../utils/source-map'
import { getCallLastIndex } from '../../../utils'

export interface InlineSnapshot {
Expand All @@ -17,14 +16,12 @@ export async function saveInlineSnapshots(
const MagicString = (await import('magic-string')).default
const files = new Set(snapshots.map(i => i.file))
await Promise.all(Array.from(files).map(async (file) => {
const map = await rpc().getSourceMap(file)
const snaps = snapshots.filter(i => i.file === file)
const code = await fs.readFile(file, 'utf8')
const s = new MagicString(code)

for (const snap of snaps) {
const pos = await getOriginalPos(map, snap)
const index = posToNumber(code, pos!)
const index = posToNumber(code, snap)
replaceInlineSnap(code, s, index, snap.snapshot)
}

Expand Down
4 changes: 1 addition & 3 deletions packages/vitest/src/node/error.ts
Expand Up @@ -4,7 +4,7 @@ import { join, normalize, relative } from 'pathe'
import c from 'picocolors'
import cliTruncate from 'cli-truncate'
import type { ErrorWithDiff, ParsedStack, Position } from '../types'
import { interpretSourcePos, lineSplitRE, parseStacktrace, posToNumber } from '../utils/source-map'
import { lineSplitRE, parseStacktrace, posToNumber } from '../utils/source-map'
import { F_POINTER } from '../utils/figures'
import { stringify } from '../integrations/chai/jest-matcher-utils'
import type { Vitest } from './core'
Expand Down Expand Up @@ -45,8 +45,6 @@ export async function printError(error: unknown, ctx: Vitest, options: PrintErro

const stacks = parseStacktrace(e, fullStack)

await interpretSourcePos(stacks, ctx)

const nearest = stacks.find(stack =>
ctx.server.moduleGraph.getModuleById(stack.file)
&& existsSync(stack.file),
Expand Down
3 changes: 1 addition & 2 deletions packages/vitest/src/node/reporters/json.ts
Expand Up @@ -4,7 +4,7 @@ import type { Vitest } from '../../node'
import type { File, Reporter, Suite, Task, TaskState } from '../../types'
import { getSuites, getTests } from '../../utils'
import { getOutputFile } from '../../utils/config-helpers'
import { interpretSourcePos, parseStacktrace } from '../../utils/source-map'
import { parseStacktrace } from '../../utils/source-map'

// for compatibility reasons, the reporter produces a JSON similar to the one produced by the Jest JSON reporter
// the following types are extracted from the Jest repository (and simplified)
Expand Down Expand Up @@ -186,7 +186,6 @@ export class JsonReporter implements Reporter {
return

const stack = parseStacktrace(error)
await interpretSourcePos(stack, this.ctx)
const frame = stack[stack.length - 1]
if (!frame)
return
Expand Down
13 changes: 9 additions & 4 deletions packages/vitest/src/runtime/setup.ts
@@ -1,3 +1,4 @@
import { installSourcemapsSupport } from 'vite-node/source-map'
import { environments } from '../integrations/env'
import type { Environment, ResolvedConfig } from '../types'
import { clearTimeout, getWorkerState, isNode, setTimeout, toArray } from '../utils'
Expand All @@ -15,9 +16,6 @@ export async function setupGlobalEnv(config: ResolvedConfig) {
enumerable: false,
})

// it's useful to see the full stack trace in the console by default
Error.stackTraceLimit = 100

// should be re-declared for each test
// if run with "threads: false"
setupDefines(config.defines)
Expand All @@ -27,8 +25,15 @@ export async function setupGlobalEnv(config: ResolvedConfig) {

globalSetup = true

if (isNode)
if (isNode) {
const state = getWorkerState()

installSourcemapsSupport({
getSourceMap: source => state.moduleCache.getSourceMap(source),
})

await setupConsoleLogSpy()
}

if (config.globals)
(await import('../integrations/globals')).registerApiGlobally()
Expand Down