-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathserver.ts
266 lines (222 loc) · 8.86 KB
/
server.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import { performance } from 'node:perf_hooks'
import { existsSync } from 'node:fs'
import { join, normalize, relative, resolve } from 'pathe'
import type { TransformResult, ViteDevServer } from 'vite'
import createDebug from 'debug'
import type { EncodedSourceMap } from '@jridgewell/trace-mapping'
import type { DebuggerOptions, FetchResult, ViteNodeResolveId, ViteNodeServerOptions } from './types'
import { shouldExternalize } from './externalize'
import { normalizeModuleId, toArray, toFilePath } from './utils'
import { Debugger } from './debug'
import { withInlineSourcemap } from './source-map'
export * from './externalize'
const debugRequest = createDebug('vite-node:server:request')
export class ViteNodeServer {
private fetchPromiseMap = new Map<string, Promise<FetchResult>>()
private transformPromiseMap = new Map<string, Promise<TransformResult | null | undefined>>()
private existingOptimizedDeps = new Set<string>()
fetchCache = new Map<string, {
duration?: number
timestamp: number
result: FetchResult
}>()
externalizeCache = new Map<string, Promise<string | false>>()
debugger?: Debugger
constructor(
public server: ViteDevServer,
public options: ViteNodeServerOptions = {},
) {
// eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
// @ts-ignore ssr is not typed in Vite 2, but defined in Vite 3, so we can't use expect-error
const ssrOptions = server.config.ssr
options.deps ??= {}
options.deps.cacheDir = relative(server.config.root, options.deps.cacheDir || server.config.cacheDir)
if (ssrOptions) {
// we don't externalize ssr, because it has different semantics in Vite
// if (ssrOptions.external) {
// options.deps.external ??= []
// options.deps.external.push(...ssrOptions.external)
// }
if (ssrOptions.noExternal === true) {
options.deps.inline ??= true
}
else if (options.deps.inline !== true) {
options.deps.inline ??= []
options.deps.inline.push(...toArray(ssrOptions.noExternal))
}
}
if (process.env.VITE_NODE_DEBUG_DUMP) {
options.debug = Object.assign(<DebuggerOptions>{
dumpModules: !!process.env.VITE_NODE_DEBUG_DUMP,
loadDumppedModules: process.env.VITE_NODE_DEBUG_DUMP === 'load',
}, options.debug ?? {})
}
if (options.debug)
this.debugger = new Debugger(server.config.root, options.debug!)
options.deps.moduleDirectories ??= []
const envValue = process.env.VITE_NODE_DEPS_MODULE_DIRECTORIES || process.env.npm_config_VITE_NODE_DEPS_MODULE_DIRECTORIES
const customModuleDirectories = envValue?.split(',')
if (customModuleDirectories)
options.deps.moduleDirectories.push(...customModuleDirectories)
options.deps.moduleDirectories = options.deps.moduleDirectories.map((dir) => {
if (!dir.startsWith('/'))
dir = `/${dir}`
if (!dir.endsWith('/'))
dir += '/'
return normalize(dir)
})
// always add node_modules as a module directory
if (!options.deps.moduleDirectories.includes('/node_modules/'))
options.deps.moduleDirectories.push('/node_modules/')
}
shouldExternalize(id: string) {
return shouldExternalize(id, this.options.deps, this.externalizeCache)
}
private async ensureExists(id: string): Promise<boolean> {
if (this.existingOptimizedDeps.has(id))
return true
if (existsSync(id)) {
this.existingOptimizedDeps.add(id)
return true
}
return new Promise<boolean>((resolve) => {
setTimeout(() => {
this.ensureExists(id).then(() => {
resolve(true)
})
})
})
}
async resolveId(id: string, importer?: string, transformMode?: 'web' | 'ssr'): Promise<ViteNodeResolveId | null> {
if (importer && !importer.startsWith(this.server.config.root))
importer = resolve(this.server.config.root, importer)
const mode = transformMode ?? ((importer && this.getTransformMode(importer)) || 'ssr')
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 EncodedSourceMap | null
}
async fetchModule(id: string, transformMode?: 'web' | 'ssr'): Promise<FetchResult> {
id = normalizeModuleId(id)
// reuse transform for concurrent requests
if (!this.fetchPromiseMap.has(id)) {
this.fetchPromiseMap.set(id,
this._fetchModule(id, transformMode)
.then((r) => {
return this.options.sourcemap !== true ? { ...r, map: undefined } : r
})
.finally(() => {
this.fetchPromiseMap.delete(id)
}),
)
}
return this.fetchPromiseMap.get(id)!
}
async transformRequest(id: string, filepath = id) {
// reuse transform for concurrent requests
if (!this.transformPromiseMap.has(id)) {
this.transformPromiseMap.set(id,
this._transformRequest(id, filepath)
.finally(() => {
this.transformPromiseMap.delete(id)
}),
)
}
return this.transformPromiseMap.get(id)!
}
async transformModule(id: string, transformMode?: 'web' | 'ssr') {
if (transformMode !== 'web')
throw new Error('`transformModule` only supports `transformMode: "web"`.')
const normalizedId = normalizeModuleId(id)
const mod = this.server.moduleGraph.getModuleById(normalizedId)
const result = mod?.transformResult || await this.server.transformRequest(normalizedId)
return {
code: result?.code,
}
}
getTransformMode(id: string) {
const withoutQuery = id.split('?')[0]
if (this.options.transformMode?.web?.some(r => withoutQuery.match(r)))
return 'web'
if (this.options.transformMode?.ssr?.some(r => withoutQuery.match(r)))
return 'ssr'
if (withoutQuery.match(/\.([cm]?[jt]sx?|json)$/))
return 'ssr'
return 'web'
}
private async _fetchModule(id: string, transformMode?: 'web' | 'ssr'): Promise<FetchResult> {
let result: FetchResult
const cacheDir = this.options.deps?.cacheDir
if (cacheDir && id.includes(cacheDir)) {
if (!id.startsWith(this.server.config.root))
id = join(this.server.config.root, id)
const timeout = setTimeout(() => {
throw new Error(`ViteNodeServer: ${id} not found. This is a bug, please report it.`)
}, 5000) // CI can be quite slow
await this.ensureExists(id)
clearTimeout(timeout)
}
const { path: filePath } = toFilePath(id, this.server.config.root)
const module = this.server.moduleGraph.getModuleById(id)
const timestamp = module ? module.lastHMRTimestamp : null
const cache = this.fetchCache.get(filePath)
if (timestamp && cache && cache.timestamp >= timestamp)
return cache.result
const time = Date.now()
const externalize = await this.shouldExternalize(filePath)
let duration: number | undefined
if (externalize) {
result = { externalize }
this.debugger?.recordExternalize(id, externalize)
}
else {
const start = performance.now()
const r = await this._transformRequest(id, filePath, transformMode)
duration = performance.now() - start
result = { code: r?.code, map: r?.map as any }
}
this.fetchCache.set(filePath, {
duration,
timestamp: time,
result,
})
return result
}
protected async processTransformResult(filepath: string, result: TransformResult) {
const mod = this.server.moduleGraph.getModuleById(filepath)
return withInlineSourcemap(result, {
filepath: mod?.file || filepath,
root: this.server.config.root,
})
}
private async _transformRequest(id: string, filepath: string, customTransformMode?: 'web' | 'ssr') {
debugRequest(id)
let result: TransformResult | null = null
if (this.options.debug?.loadDumppedModules) {
result = await this.debugger?.loadDump(id) ?? null
if (result)
return result
}
const transformMode = customTransformMode ?? this.getTransformMode(id)
if (transformMode === 'web') {
// for components like Vue, we want to use the client side
// plugins but then convert the code to be consumed by the server
result = await this.server.transformRequest(id)
if (result)
result = await this.server.ssrTransform(result.code, result.map, id)
}
else {
result = await this.server.transformRequest(id, { ssr: true })
}
const sourcemap = this.options.sourcemap ?? 'inline'
if (sourcemap === 'inline' && result && !id.includes('node_modules'))
result = await this.processTransformResult(filepath, result)
if (this.options.debug?.dumpModules)
await this.debugger?.dumpFile(id, result)
return result
}
}