-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathclient.ts
326 lines (273 loc) · 9.61 KB
/
client.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
import { createRequire } from 'module'
import { fileURLToPath, pathToFileURL } from 'url'
import vm from 'vm'
import { dirname, extname, isAbsolute, resolve } from 'pathe'
import { isNodeBuiltin } from 'mlly'
import createDebug from 'debug'
import { isPrimitive, mergeSlashes, normalizeModuleId, normalizeRequestId, slash, toFilePath } from './utils'
import type { HotContext, ModuleCache, ViteNodeRunnerOptions } from './types'
const debugExecute = createDebug('vite-node:client:execute')
const debugNative = createDebug('vite-node:client:native')
export const DEFAULT_REQUEST_STUBS = {
'/@vite/client': {
injectQuery: (id: string) => id,
createHotContext() {
return {
accept: () => {},
prune: () => {},
dispose: () => {},
decline: () => {},
invalidate: () => {},
on: () => {},
}
},
updateStyle(id: string, css: string) {
if (typeof document === 'undefined')
return
const element = document.getElementById(id)
if (element)
element.remove()
const head = document.querySelector('head')
const style = document.createElement('style')
style.setAttribute('type', 'text/css')
style.id = id
style.innerHTML = css
head?.appendChild(style)
},
},
}
export class ModuleCacheMap extends Map<string, ModuleCache> {
normalizePath(fsPath: string) {
return normalizeModuleId(fsPath)
}
set(fsPath: string, mod: Partial<ModuleCache>) {
fsPath = this.normalizePath(fsPath)
if (!super.has(fsPath))
super.set(fsPath, mod)
else
Object.assign(super.get(fsPath) as ModuleCache, mod)
return this
}
get(fsPath: string) {
fsPath = this.normalizePath(fsPath)
return super.get(fsPath)
}
delete(fsPath: string) {
fsPath = this.normalizePath(fsPath)
return super.delete(fsPath)
}
}
export class ViteNodeRunner {
root: string
debug: boolean
/**
* Holds the cache of modules
* Keys of the map are filepaths, or plain package names
*/
moduleCache: ModuleCacheMap
constructor(public options: ViteNodeRunnerOptions) {
this.root = options.root ?? process.cwd()
this.moduleCache = options.moduleCache ?? new ModuleCacheMap()
this.debug = options.debug ?? (typeof process !== 'undefined' ? !!process.env.VITE_NODE_DEBUG_RUNNER : false)
}
async executeFile(file: string) {
return await this.cachedRequest(`/@fs/${slash(resolve(file))}`, [])
}
async executeId(id: string) {
return await this.cachedRequest(id, [])
}
/** @internal */
async cachedRequest(rawId: string, callstack: string[]) {
const id = normalizeRequestId(rawId, this.options.base)
const fsPath = toFilePath(id, this.root)
// the callstack reference itself circularly
if (callstack.includes(fsPath) && this.moduleCache.get(fsPath)?.exports)
return this.moduleCache.get(fsPath)?.exports
// cached module
if (this.moduleCache.get(fsPath)?.promise)
return this.moduleCache.get(fsPath)?.promise
const promise = this.directRequest(id, fsPath, callstack)
this.moduleCache.set(fsPath, { promise })
return await promise
}
/** @internal */
async directRequest(id: string, fsPath: string, _callstack: string[]) {
const callstack = [..._callstack, fsPath]
const request = async (dep: string) => {
const fsPath = toFilePath(normalizeRequestId(dep, this.options.base), this.root)
const getStack = () => {
return `stack:\n${[...callstack, fsPath].reverse().map(p => `- ${p}`).join('\n')}`
}
let debugTimer: any
if (this.debug)
debugTimer = setTimeout(() => console.warn(() => `module ${fsPath} takes over 2s to load.\n${getStack()}`), 2000)
try {
if (callstack.includes(fsPath)) {
const depExports = this.moduleCache.get(fsPath)?.exports
if (depExports)
return depExports
throw new Error(`[vite-node] Failed to resolve circular dependency, ${getStack()}`)
}
const mod = await this.cachedRequest(dep, callstack)
return mod
}
finally {
if (debugTimer)
clearTimeout(debugTimer)
}
}
Object.defineProperty(request, 'callstack', { get: () => callstack })
const resolveId = async (dep: string, callstackPosition = 1) => {
// probably means it was passed as variable
// and wasn't transformed by Vite
// or some dependency name was passed
// runner.executeFile('@scope/name')
// runner.executeFile(myDynamicName)
if (this.options.resolveId && this.shouldResolveId(dep)) {
let importer = callstack[callstack.length - callstackPosition]
if (importer && importer.startsWith('mock:'))
importer = importer.slice(5)
const { id } = await this.options.resolveId(dep, importer) || {}
dep = id && isAbsolute(id) ? mergeSlashes(`/@fs/${id}`) : id || dep
}
return dep
}
id = await resolveId(id, 2)
const requestStubs = this.options.requestStubs || DEFAULT_REQUEST_STUBS
if (id in requestStubs)
return requestStubs[id]
// eslint-disable-next-line prefer-const
let { code: transformed, externalize } = await this.options.fetchModule(id)
if (externalize) {
debugNative(externalize)
const mod = await this.interopedImport(externalize)
this.moduleCache.set(fsPath, { exports: mod })
return mod
}
if (transformed == null)
throw new Error(`[vite-node] Failed to load ${id}`)
// disambiguate the `<UNIT>:/` on windows: see nodejs/node#31710
const url = pathToFileURL(fsPath).href
const meta = { url }
const exports: any = Object.create(null)
exports[Symbol.toStringTag] = 'Module'
this.moduleCache.set(fsPath, { code: transformed, exports })
const __filename = fileURLToPath(url)
const moduleProxy = {
set exports(value) {
exportAll(exports, value)
exports.default = value
},
get exports() {
return exports
},
}
// Vite hot context
let hotContext: HotContext | undefined
if (this.options.createHotContext) {
Object.defineProperty(meta, 'hot', {
enumerable: true,
get: () => {
hotContext ||= this.options.createHotContext?.(this, `/@fs/${fsPath}`)
return hotContext
},
})
}
// 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.ts#L100 if you do change this
const context = this.prepareContext({
// esm transformed by Vite
__vite_ssr_import__: request,
__vite_ssr_dynamic_import__: request,
__vite_ssr_exports__: exports,
__vite_ssr_exportAll__: (obj: any) => exportAll(exports, obj),
__vite_ssr_import_meta__: meta,
__vitest_resolve_id__: resolveId,
// cjs compact
require: createRequire(url),
exports,
module: moduleProxy,
__filename,
__dirname: dirname(__filename),
})
debugExecute(__filename)
// remove shebang
if (transformed[0] === '#')
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}}`, {
filename: fsPath,
lineOffset: 0,
})
await fn(...Object.values(context))
return exports
}
prepareContext(context: Record<string, any>) {
return context
}
shouldResolveId(dep: string) {
if (isNodeBuiltin(dep) || dep in (this.options.requestStubs || DEFAULT_REQUEST_STUBS) || dep.startsWith('/@vite'))
return false
return !isAbsolute(dep) || !extname(dep)
}
/**
* Define if a module should be interop-ed
* This function mostly for the ability to override by subclass
*/
shouldInterop(path: string, mod: any) {
if (this.options.interopDefault === false)
return false
// never interop ESM modules
// TODO: should also skip for `.js` with `type="module"`
return !path.endsWith('.mjs') && 'default' in mod
}
/**
* Import a module and interop it
*/
async interopedImport(path: string) {
const mod = await import(path)
if (this.shouldInterop(path, mod)) {
const tryDefault = this.hasNestedDefault(mod)
return new Proxy(mod, {
get: proxyMethod('get', tryDefault),
set: proxyMethod('set', tryDefault),
has: proxyMethod('has', tryDefault),
deleteProperty: proxyMethod('deleteProperty', tryDefault),
})
}
return mod
}
hasNestedDefault(target: any) {
return '__esModule' in target && target.__esModule && 'default' in target.default
}
}
function proxyMethod(name: 'get' | 'set' | 'has' | 'deleteProperty', tryDefault: boolean) {
return function (target: any, key: string | symbol, ...args: [any?, any?]) {
const result = Reflect[name](target, key, ...args)
if (isPrimitive(target.default))
return result
if ((tryDefault && key === 'default') || typeof result === 'undefined')
return Reflect[name](target.default, key, ...args)
return result
}
}
function exportAll(exports: any, sourceModule: any) {
// #1120 when a module exports itself it causes
// call stack error
if (exports === sourceModule)
return
for (const key in sourceModule) {
if (key !== 'default') {
try {
Object.defineProperty(exports, key, {
enumerable: true,
configurable: true,
get() { return sourceModule[key] },
})
}
catch (_err) { }
}
}
}