-
Notifications
You must be signed in to change notification settings - Fork 25
/
quibble.mjs
202 lines (171 loc) · 5.74 KB
/
quibble.mjs
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
import quibble from './quibble.js'
export default quibble
export const reset = quibble.reset
export const ignoreCallsFromThisFile = quibble.ignoreCallsFromThisFile
export const config = quibble.config
export const isLoaderLoaded = quibble.isLoaderLoaded
let __quibble
export async function resolve (specifier, context, nextResolve) {
const resolve = () => nextResolve(
specifier.includes('__quibble')
? specifier.replace('?__quibbleresolvepath', '').replace('?__quibbleoriginal', '')
: specifier,
context
)
if (specifier.includes('__quibbleresolvepath')) {
const resolvedPath = new URL((await resolve()).url).pathname
const error = new Error()
error.code = 'QUIBBLE_RESOLVED_PATH'
error.resolvedPath = resolvedPath
throw error
}
if (!__quibble.quibbledModules) {
return resolve()
}
if (specifier === 'quibble') {
return resolve()
}
const stubModuleGeneration = __quibble.stubModuleGeneration
if (specifier.includes('__quibbleoriginal')) {
return resolve()
}
const { parentURL } = context
try {
const { url } = await resolve()
const quibbledUrl = `${url}?__quibble=${stubModuleGeneration}`
// 'node:' is the prefix for Node >=14.13. 'nodejs:' is for earlier versions
if (/^node(js){0,1}:/.test(url) && !getStubsInfo(new URL(quibbledUrl))) return { url }
return { url: quibbledUrl }
} catch (error) {
if (error.code === 'ERR_MODULE_NOT_FOUND') {
return {
url: parentURL
? `${new URL(specifier, parentURL).href}?__quibble=${stubModuleGeneration}`
: new URL(specifier).href
}
} else { throw error }
}
}
export async function getFormat (url, context, defaultGetFormat) {
if (getStubsInfo(new URL(url))) {
return {
format: 'module'
}
} else {
return defaultGetFormat(url, context, defaultGetFormat)
}
}
export async function getSource (url, context, defaultGetSource) {
const stubsInfo = getStubsInfo(new URL(url))
return stubsInfo
? { source: transformModuleSource(stubsInfo) }
: defaultGetSource(url, context, defaultGetSource)
}
/** @param {URL} moduleUrl */
function getStubsInfo (moduleUrl) {
if (!__quibble.quibbledModules) return undefined
if (!moduleUrl.searchParams.get('__quibble')) return undefined
const moduleFilepath = moduleUrl.pathname
const stub = __quibble.quibbledModules.get(moduleFilepath)
return stub ? [moduleFilepath, stub] : undefined
}
function transformModuleSource ([moduleKey, stubs]) {
return `
${(stubs.namedExportNames || [])
.map(
(name) =>
`export let ${name} = globalThis[Symbol.for('__quibbleEsmUser')].quibbledModules.get(${JSON.stringify(
moduleKey
)}).namedExportStubs["${name}"]`
)
.join(';\n')};
${
stubs.hasDefaultExport
? `export default globalThis[Symbol.for('__quibbleEsmUser')].quibbledModules.get(${JSON.stringify(
moduleKey
)}).defaultExportStub;`
: ''
}
`
}
/**
* @param {string} url
* @param {{
* format: string,
* }} context
* @param {Function} nextLoad
* @returns {Promise<{ source: !(string | SharedArrayBuffer | Uint8Array), format: string}>}
*/
export async function load (url, context, nextLoad) {
const stubsInfo = getStubsInfo(new URL(url))
return stubsInfo
? { source: transformModuleSource(stubsInfo), format: 'module', shortCircuit: true }
: nextLoad(url, context)
}
export const globalPreload = ({ port }) => {
__quibble = globalThis[Symbol.for('__quibbleEsmLoader')] = { stubModuleGeneration: 1, quibbledModules: new Map() }
port.addEventListener('message', ({ data }) => {
if (data.type === 'reset') {
__quibble.quibbledModules = new Map()
__quibble.stubModuleGeneration++
hasResetHappened[0] = 0
} else if (data.type === 'addMockedModule') {
__quibble.quibbledModules.set(data.fullModulePath, {
namedExportNames: data.namedExportNames,
hasDefaultExport: data.hasDefaultExport
})
++__quibble.stubModuleGeneration
port.postMessage({ type: data.returnMessage })
}
})
const sharedArrayBuffer = new SharedArrayBuffer(4)
const hasResetHappened = new Int32Array(sharedArrayBuffer)
port.postMessage({ type: 'ready', hasResetHappened })
port.unref()
return `(${thisWillRunInUserThread})(globalThis, port)`
}
export const getGlobalPreloadCode = globalPreload
async function thisWillRunInUserThread (globalThis, port) {
const events = getBuiltin('events') // eslint-disable-line
globalThis[Symbol.for('__quibbleEsmUser')] = {
...globalThis[Symbol.for('__quibbleEsmUser')],
reset () {
if (!loaderAndUserRunInSameThread(globalThis)) {
port.postMessage({ type: 'reset' })
hasResetHappened[0] = 1
Atomics.wait(hasResetHappened, 0, 1)
hasResetHappened[0] = 0
} else {
const __quibble = globalThis[Symbol.for('__quibbleEsmLoader')]
__quibble.quibbledModules = new Map()
__quibble.stubModuleGeneration++
}
},
async addMockedModule (fullModulePath, {
namedExportNames,
hasDefaultExport
}) {
const returnMessage = `addMockedModuleReturn-${Math.random() * 1000000 | 0}`
port.postMessage({
type: 'addMockedModule',
fullModulePath,
namedExportNames,
hasDefaultExport,
returnMessage
})
await new Promise((resolve) => {
const checkMessage = ({ data }) => {
if (data.type === returnMessage) {
port.removeEventListener('message', checkMessage)
resolve()
}
}
port.addEventListener('message', checkMessage)
})
}
}
const [{ hasResetHappened }] = await events.once(port, 'message')
function loaderAndUserRunInSameThread (globalThis) {
return !!globalThis[Symbol.for('__quibbleEsmLoader')]
}
}