MCPcopy
hub / github.com/vitest-dev/vitest / createLoadHook

Function createLoadHook

packages/vitest/src/runtime/workers/native.ts:152–234  ·  view source on GitHub ↗
(_worker: WorkerSetupContext)

Source from the content-addressed store, hash-verified

150])
151
152function createLoadHook(_worker: WorkerSetupContext): module.LoadHookSync {
153 return (url, context, nextLoad) => {
154 const result: module.LoadFnOutput = url.includes('mock=') && isBuiltin(cleanUrl(url))
155 ? { format: 'commonjs' } // avoid resolving the builtin module that is supposed to be mocked
156 : nextLoad(url, context)
157 if (
158 (result.format && ignoreFormats.has(result.format))
159 || url.includes(distDir)
160 ) {
161 return result
162 }
163
164 const mocker = getNativeMocker()
165
166 mocker?.checkCircularManualMock(url)
167
168 if (url.includes('mock=automock') || url.includes('mock=autospy')) {
169 const automockedResult = mocker?.loadAutomock(url, result)
170 if (automockedResult != null) {
171 return automockedResult
172 }
173 return result
174 }
175
176 if (url.includes('mock=manual')) {
177 const mockedResult = mocker?.loadManualMock(url, result)
178 if (mockedResult != null) {
179 return mockedResult
180 }
181 return result
182 }
183
184 // ignore non-vitest modules for performance reasons,
185 // vi.hoisted and vi.mock won't work outside of test files or setup files
186 if (!result.source || !url.includes('vitest=')) {
187 return result
188 }
189
190 const filename = url.startsWith('file://') ? fileURLToPath(url) : url
191 const source = result.source.toString()
192 const transformedCode = result.format?.includes('typescript')
193 ? module.stripTypeScriptTypes(source)
194 : source
195
196 let _ms: MagicString | undefined
197 const ms = () => _ms || (_ms = new MagicString(source))
198
199 if (source.includes('import.meta.vitest')) {
200 replaceInSourceMarker(url, source, ms)
201 }
202
203 hoistMocks(
204 transformedCode,
205 filename,
206 code => parse(code, {
207 ecmaVersion: 'latest',
208 sourceType: result.format === 'module' || result.format === 'module-typescript' || result.format === 'typescript'
209 ? 'module'

Callers 1

setupNodeLoaderHooksFunction · 0.85

Calls 12

cleanUrlFunction · 0.90
isBuiltinFunction · 0.85
getNativeMockerFunction · 0.85
replaceInSourceMarkerFunction · 0.85
hoistMocksFunction · 0.85
loadAutomockMethod · 0.80
loadManualMockMethod · 0.80
genSourceMapUrlFunction · 0.70
parseFunction · 0.50
hasMethod · 0.45
toStringMethod · 0.45

Tested by

no test coverage detected