-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
time.ts
60 lines (54 loc) · 1.82 KB
/
time.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
import { performance } from 'node:perf_hooks'
import * as messages from '@cucumber/messages'
interface ProtectedTimingBuiltins {
clearImmediate: typeof clearImmediate
clearInterval: typeof clearInterval
clearTimeout: typeof clearTimeout
Date: typeof Date
setImmediate: typeof setImmediate
setInterval: typeof setInterval
setTimeout: typeof setTimeout
performance: typeof performance
}
const methods: Partial<ProtectedTimingBuiltins> = {
clearInterval: clearInterval.bind(global),
clearTimeout: clearTimeout.bind(global),
Date,
setInterval: setInterval.bind(global),
setTimeout: setTimeout.bind(global),
performance,
}
if (typeof setImmediate !== 'undefined') {
methods.setImmediate = setImmediate.bind(global)
methods.clearImmediate = clearImmediate.bind(global)
}
export function durationBetweenTimestamps(
startedTimestamp: messages.Timestamp,
finishedTimestamp: messages.Timestamp
): messages.Duration {
const durationMillis =
messages.TimeConversion.timestampToMillisecondsSinceEpoch(
finishedTimestamp
) -
messages.TimeConversion.timestampToMillisecondsSinceEpoch(startedTimestamp)
return messages.TimeConversion.millisecondsToDuration(durationMillis)
}
export async function wrapPromiseWithTimeout<T>(
promise: Promise<T>,
timeoutInMilliseconds: number,
timeoutMessage: string = ''
): Promise<T> {
let timeoutId: ReturnType<typeof setTimeout>
if (timeoutMessage === '') {
timeoutMessage = `Action did not complete within ${timeoutInMilliseconds} milliseconds`
}
const timeoutPromise = new Promise<T>((resolve, reject) => {
timeoutId = methods.setTimeout(() => {
reject(new Error(timeoutMessage))
}, timeoutInMilliseconds)
})
return await Promise.race([promise, timeoutPromise]).finally(() =>
methods.clearTimeout(timeoutId)
)
}
export default methods