/
rpc.ts
74 lines (65 loc) · 2.08 KB
/
rpc.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
import {
getSafeTimers,
} from '@vitest/utils'
import { getWorkerState } from '../utils'
const { get } = Reflect
const safeRandom = Math.random
function withSafeTimers(fn: () => void) {
const { setTimeout, clearTimeout, nextTick, setImmediate, clearImmediate } = getSafeTimers()
const currentSetTimeout = globalThis.setTimeout
const currentClearTimeout = globalThis.clearTimeout
const currentRandom = globalThis.Math.random
const currentNextTick = globalThis.process.nextTick
const currentSetImmediate = globalThis.setImmediate
const currentClearImmediate = globalThis.clearImmediate
try {
globalThis.setTimeout = setTimeout
globalThis.clearTimeout = clearTimeout
globalThis.Math.random = safeRandom
globalThis.process.nextTick = nextTick
globalThis.setImmediate = setImmediate
globalThis.clearImmediate = clearImmediate
const result = fn()
return result
}
finally {
globalThis.setTimeout = currentSetTimeout
globalThis.clearTimeout = currentClearTimeout
globalThis.Math.random = currentRandom
globalThis.setImmediate = currentSetImmediate
globalThis.clearImmediate = currentClearImmediate
nextTick(() => {
globalThis.process.nextTick = currentNextTick
})
}
}
const promises = new Set<Promise<unknown>>()
export const rpcDone = async () => {
// Run possible setTimeouts, e.g. the onces used by ConsoleLogSpy
const { setTimeout } = getSafeTimers()
await new Promise(resolve => setTimeout(resolve))
if (!promises.size)
return
const awaitable = Array.from(promises)
return Promise.all(awaitable)
}
export const rpc = () => {
const { rpc } = getWorkerState()
return new Proxy(rpc, {
get(target, p, handler) {
const sendCall = get(target, p, handler)
const safeSendCall = (...args: any[]) => withSafeTimers(async () => {
const result = sendCall(...args)
promises.add(result)
try {
return await result
}
finally {
promises.delete(result)
}
})
safeSendCall.asEvent = sendCall.asEvent
return safeSendCall
},
})
}