-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.ts
58 lines (52 loc) · 1.54 KB
/
utils.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
// Copyright 2018-2024 the oak authors. All rights reserved.
const hasPromiseWithResolvers = "withResolvers" in Promise;
/** Append a set of headers onto a response. */
export function appendHeaders(response: Response, headers: Headers): Response {
for (const [key, value] of headers) {
response.headers.append(key, value);
}
return response;
}
/**
* Creates a promise with resolve and reject functions that can be called.
*
* Offloads to the native `Promise.withResolvers` when available.
*/
export function createPromiseWithResolvers<T>(): {
promise: Promise<T>;
resolve: (value: T | PromiseLike<T>) => void;
// deno-lint-ignore no-explicit-any
reject: (reason?: any) => void;
} {
if (hasPromiseWithResolvers) {
return Promise.withResolvers<T>();
}
let resolve;
let reject;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve: resolve!, reject: reject! };
}
/**
* Safely decode a URI component, where if it fails, instead of throwing,
* just returns the original string.
*/
export function decodeComponent(text: string) {
try {
return decodeURIComponent(text);
} catch {
return text;
}
}
/** Determines if the runtime is Bun or not. */
export function isBun(): boolean {
return "Bun" in globalThis;
}
/** Determines if the runtime is Node.js or not. */
export function isNode(): boolean {
return "process" in globalThis && "global" in globalThis &&
!("Bun" in globalThis) && !("WebSocketPair" in globalThis) &&
!("Deno" in globalThis);
}