-
Notifications
You must be signed in to change notification settings - Fork 19
/
esmock.js
44 lines (34 loc) · 1.66 KB
/
esmock.js
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
import module from 'node:module'
import * as hooks from './esmockLoader.js'
import esmockLoader from './esmockLoader.js'
import esmockModule from './esmockModule.js'
import esmockArgs from './esmockArgs.js'
import esmockErr from './esmockErr.js'
const esmockGo = opts => async (...args) => {
const [moduleId, parent, defs, gdefs, opt] = esmockArgs(args, opts)
if (!module.register && !await esmockLoader())
throw esmockErr.errMissingLoader()
const fileURLKey = await esmockModule(moduleId, parent, defs, gdefs, opt)
const importedModule = await import(fileURLKey)
if (opt.purge !== false)
esmockModule.purge(fileURLKey)
return esmockModule.sanitize(importedModule, fileURLKey)
}
const purge = mockModule => mockModule
&& /object|function/.test(typeof mockModule) && 'esmkTreeId' in mockModule
&& esmockModule.purge(mockModule.esmkTreeId)
const strict = Object.assign(esmockGo({ strict: 1 }), {
purge, p: esmockGo({ strict: 1, purge: false }) })
const strictest = Object.assign(esmockGo({ strict: 3 }), {
purge, p: esmockGo({ strict: 3, purge: false }) })
const esmock = Object.assign(esmockGo(), {
purge, p: esmockGo({ purge: false }), strict, strictest })
export {esmock as default, strict, strictest}
// for older node versions, to support "--loader=esmock" rather than
// "--loader=esmock/loader", esmock.js exported loader hook definitions here
//
// for newer node versions 20.6+, exporting hook definitions here causes
// problems when --loader is used w/ module.register
const hooksFinal = module.register ? {} : hooks
const { load, resolve, getSource, initialize, globalPreload } = hooksFinal
export { load, resolve, getSource, initialize, globalPreload }