/
debug.ts
83 lines (74 loc) · 2.47 KB
/
debug.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/* eslint-disable no-console */
import { existsSync, promises as fs } from 'node:fs'
import { join, resolve } from 'pathe'
import type { TransformResult } from 'vite'
import c from 'picocolors'
import type { DebuggerOptions } from './types'
function hashCode(s: string) {
return s.split('').reduce((a, b) => {
a = ((a << 5) - a) + b.charCodeAt(0)
return a & a
}, 0)
}
export class Debugger {
dumpDir: string | undefined
initPromise: Promise<void> | undefined
externalizeMap = new Map<string, string>()
constructor(root: string, public options: DebuggerOptions) {
if (options.dumpModules)
this.dumpDir = resolve(root, options.dumpModules === true ? '.vite-node/dump' : options.dumpModules)
if (this.dumpDir) {
if (options.loadDumppedModules)
console.info(c.gray(`[vite-node] [debug] load modules from ${this.dumpDir}`))
else
console.info(c.gray(`[vite-node] [debug] dump modules to ${this.dumpDir}`))
}
this.initPromise = this.clearDump()
}
async clearDump() {
if (!this.dumpDir)
return
if (!this.options.loadDumppedModules && existsSync(this.dumpDir))
await fs.rm(this.dumpDir, { recursive: true, force: true })
await fs.mkdir(this.dumpDir, { recursive: true })
}
encodeId(id: string) {
return `${id.replace(/[^\w@_-]/g, '_').replace(/_+/g, '_')}-${hashCode(id)}.js`
}
async recordExternalize(id: string, path: string) {
if (!this.dumpDir)
return
this.externalizeMap.set(id, path)
await this.writeInfo()
}
async dumpFile(id: string, result: TransformResult | null) {
if (!result || !this.dumpDir)
return
await this.initPromise
const name = this.encodeId(id)
return await fs.writeFile(join(this.dumpDir, name), `// ${id.replace(/\0/g, '\\0')}\n${result.code}`, 'utf-8')
}
async loadDump(id: string): Promise<TransformResult | null> {
if (!this.dumpDir)
return null
await this.initPromise
const name = this.encodeId(id)
const path = join(this.dumpDir, name)
if (!existsSync(path))
return null
const code = await fs.readFile(path, 'utf-8')
return {
code: code.replace(/^\/\/.*?\n/, ''),
map: undefined!,
}
}
async writeInfo() {
if (!this.dumpDir)
return
const info = JSON.stringify({
time: new Date().toLocaleString(),
externalize: Object.fromEntries(this.externalizeMap.entries()),
}, null, 2)
return fs.writeFile(join(this.dumpDir, 'info.json'), info, 'utf-8')
}
}