Skip to content

Commit 0c24b54

Browse files
committed
feat: implement a safe random runner
1 parent 10c9229 commit 0c24b54

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { GLOBAL_OBJ } from './worldwide';
2+
3+
type SafeRandomContextRunner = <T>(callback: () => T) => T;
4+
5+
let RESOLVED_RUNNER: SafeRandomContextRunner | undefined;
6+
7+
/**
8+
* Simple wrapper that allows SDKs to *secretly* set context wrapper to generate safe random IDs in cache components contexts
9+
*/
10+
export function runInRandomSafeContext<T>(cb: () => T): T {
11+
// Skips future symbol lookups if we've already resolved the runner once
12+
if (RESOLVED_RUNNER) {
13+
return RESOLVED_RUNNER(cb);
14+
}
15+
16+
const sym = Symbol.for('__SENTRY_SAFE_RANDOM_ID_WRAPPER__');
17+
const globalWithSymbol: typeof GLOBAL_OBJ & { [sym]?: SafeRandomContextRunner } = GLOBAL_OBJ;
18+
if (!(sym in globalWithSymbol) || typeof globalWithSymbol[sym] !== 'function') {
19+
return cb();
20+
}
21+
22+
RESOLVED_RUNNER = globalWithSymbol[sym];
23+
24+
return globalWithSymbol[sym](cb);
25+
}
26+
27+
/**
28+
* Returns the current date and time wrapped in a safe context runner.
29+
* @returns number The current date and time.
30+
*/
31+
export function safeDateNow(): number {
32+
return runInRandomSafeContext(() => Date.now());
33+
}
34+
35+
/**
36+
* Returns a random number between 0 and 1 wrapped in a safe context runner.
37+
* @returns number A random number between 0 and 1.
38+
*/
39+
export function safeMathRandom(): number {
40+
return runInRandomSafeContext(() => Math.random());
41+
}

0 commit comments

Comments
 (0)