Skip to content

Commit f94c42c

Browse files
fix: fix browser support (#172)
Signed-off-by: Jérôme Benoit <jerome.benoit@piment-noir.org>
1 parent 88fab00 commit f94c42c

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

src/utils.ts

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,32 @@
11
import { emptyFunction, tTable } from './constants';
22
import type { Fn, Statistics } from './types';
33

4+
/**
5+
* The JavaScript runtime environment.
6+
*/
7+
enum JSRuntime {
8+
bun = 'bun',
9+
deno = 'deno',
10+
node = 'node',
11+
browser = 'browser',
12+
}
13+
14+
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
15+
const isBun = !!(globalThis as any).Bun || !!globalThis.process.versions.bun;
16+
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
17+
const isDeno = !!(globalThis as any).Deno;
18+
const isNode = globalThis.process.release.name === 'node';
19+
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access
20+
const isBrowser = !!(globalThis as any).navigator;
21+
22+
const runtime: JSRuntime | 'unknown' = (() => {
23+
if (isBun) return JSRuntime.bun;
24+
if (isDeno) return JSRuntime.deno;
25+
if (isNode) return JSRuntime.node;
26+
if (isBrowser) return JSRuntime.browser;
27+
return 'unknown';
28+
})();
29+
430
/**
531
* Converts nanoseconds to milliseconds.
632
*
@@ -17,7 +43,14 @@ export const nToMs = (ns: number) => ns / 1e6;
1743
*/
1844
export const mToNs = (ms: number) => ms * 1e6;
1945

20-
const hrtimeBigint = process.hrtime.bigint.bind(process.hrtime);
46+
let hrtimeBigint: () => bigint;
47+
if (runtime === JSRuntime.browser) {
48+
hrtimeBigint = () => {
49+
throw new Error('hrtime.bigint() is not supported in this JS environment');
50+
};
51+
} else {
52+
hrtimeBigint = process.hrtime.bigint.bind(process.hrtime);
53+
}
2154
export const hrtimeNow = () => nToMs(Number(hrtimeBigint()));
2255

2356
const performanceNow = performance.now.bind(performance);

0 commit comments

Comments
 (0)