1
+ /* @flow */
2
+
1
3
import { randomBytes } from 'crypto' ;
2
4
3
5
// Returns a new random hex string of the given even size.
4
- export function randomHexString ( size ) {
6
+ export function randomHexString ( size : number ) : string {
5
7
if ( size === 0 ) {
6
8
throw new Error ( 'Zero-length randomHexString is useless.' ) ;
7
9
}
@@ -17,28 +19,28 @@ export function randomHexString(size) {
17
19
// because chars length of 62 doesn't divide the number of all bytes
18
20
// (256) evenly. Such bias is acceptable for most cases when the output
19
21
// length is long enough and doesn't need to be uniform.
20
- export function randomString ( size ) {
22
+ export function randomString ( size : number ) : string {
21
23
if ( size === 0 ) {
22
24
throw new Error ( 'Zero-length randomString is useless.' ) ;
23
25
}
24
- var chars = ( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
26
+ let chars = ( 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
25
27
'abcdefghijklmnopqrstuvwxyz' +
26
28
'0123456789' ) ;
27
- var objectId = '' ;
28
- var bytes = randomBytes ( size ) ;
29
- for ( var i = 0 ; i < bytes . length ; ++ i ) {
29
+ let objectId = '' ;
30
+ let bytes = randomBytes ( size ) ;
31
+ for ( let i = 0 ; i < bytes . length ; ++ i ) {
30
32
objectId += chars [ bytes . readUInt8 ( i ) % chars . length ] ;
31
33
}
32
34
return objectId ;
33
35
}
34
36
35
37
// Returns a new random alphanumeric string suitable for object ID.
36
- export function newObjectId ( ) {
38
+ export function newObjectId ( ) : string {
37
39
//TODO: increase length to better protect against collisions.
38
40
return randomString ( 10 ) ;
39
41
}
40
42
41
43
// Returns a new random hex string suitable for secure tokens.
42
- export function newToken ( ) {
44
+ export function newToken ( ) : string {
43
45
return randomHexString ( 32 ) ;
44
46
}
0 commit comments