forked from vitest-dev/vitest
/
rpc.ts
35 lines (30 loc) · 873 Bytes
/
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
import { getWorkerState } from '../utils'
import {
setTimeout as safeSetTimeout,
} from '../utils/timers'
const safeRandom = Math.random
function withSafeTimers(fn: () => void) {
const currentSetTimeout = globalThis.setTimeout
const currentRandom = globalThis.Math.random
try {
globalThis.setTimeout = safeSetTimeout
globalThis.Math.random = safeRandom
const result = fn()
return result
}
finally {
globalThis.setTimeout = currentSetTimeout
globalThis.Math.random = currentRandom
}
}
export const rpc = () => {
const { rpc } = getWorkerState()
return new Proxy(rpc, {
get(target, p, handler) {
const sendCall = Reflect.get(target, p, handler)
const safeSendCall = (...args: any[]) => withSafeTimers(() => sendCall(...args))
safeSendCall.asEvent = sendCall.asEvent
return safeSendCall
},
})
}