@@ -34,32 +34,38 @@ declare let require: Function;
3434// eslint-disable-next-line @typescript-eslint/no-explicit-any
3535declare let global : any ;
3636declare const self : unknown ;
37+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
38+ declare let process : any ; // Used by @rollup /plugin-replace
3739
3840const detectRandomBytes = ( ) : RandomBytesFunction => {
39- if ( typeof window !== 'undefined' ) {
40- // browser crypto implementation(s)
41- const target = window . crypto || window . msCrypto ; // allow for IE11
42- if ( target && target . getRandomValues ) {
43- return size => target . getRandomValues ( Buffer . alloc ( size ) ) ;
41+ if ( process . browser ) {
42+ if ( typeof window !== 'undefined' ) {
43+ // browser crypto implementation(s)
44+ const target = window . crypto || window . msCrypto ; // allow for IE11
45+ if ( target && target . getRandomValues ) {
46+ return size => target . getRandomValues ( Buffer . alloc ( size ) ) ;
47+ }
4448 }
45- }
4649
47- if ( typeof global !== 'undefined' && global . crypto && global . crypto . getRandomValues ) {
48- // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global
49- return size => global . crypto . getRandomValues ( Buffer . alloc ( size ) ) ;
50- }
50+ if ( typeof global !== 'undefined' && global . crypto && global . crypto . getRandomValues ) {
51+ // allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global
52+ return size => global . crypto . getRandomValues ( Buffer . alloc ( size ) ) ;
53+ }
5154
52- let requiredRandomBytes : RandomBytesFunction | null | undefined ;
53- try {
54- // eslint-disable-next-line @typescript-eslint/no-var-requires
55- requiredRandomBytes = require ( 'crypto' ) . randomBytes ;
56- } catch ( e ) {
57- // keep the fallback
58- }
55+ return insecureRandomBytes ;
56+ } else {
57+ let requiredRandomBytes : RandomBytesFunction | null | undefined ;
58+ try {
59+ // eslint-disable-next-line @typescript-eslint/no-var-requires
60+ requiredRandomBytes = require ( 'crypto' ) . randomBytes ;
61+ } catch ( e ) {
62+ // keep the fallback
63+ }
5964
60- // NOTE: in transpiled cases the above require might return null/undefined
65+ // NOTE: in transpiled cases the above require might return null/undefined
6166
62- return requiredRandomBytes || insecureRandomBytes ;
67+ return requiredRandomBytes || insecureRandomBytes ;
68+ }
6369} ;
6470
6571export const randomBytes = detectRandomBytes ( ) ;
0 commit comments