nanoid 3.3.6 → 3.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/async/index.cjs CHANGED
@@ -1,7 +1,14 @@
1
1
  let crypto = require('crypto')
2
+
2
3
  let { urlAlphabet } = require('../url-alphabet/index.cjs')
4
+
5
+ // `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
6
+ // because it is possible to use in combination with `Buffer.allocUnsafe()`.
3
7
  let random = bytes =>
4
8
  new Promise((resolve, reject) => {
9
+ // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
10
+ // Memory flushing is unnecessary since the buffer allocation itself resets
11
+ // the memory with the new bytes.
5
12
  crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
6
13
  if (err) {
7
14
  reject(err)
@@ -10,26 +17,55 @@ let random = bytes =>
10
17
  }
11
18
  })
12
19
  })
20
+
13
21
  let customAlphabet = (alphabet, defaultSize = 21) => {
22
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
23
+ // values closer to the alphabet size. The bitmask calculates the closest
24
+ // `2^31 - 1` number, which exceeds the alphabet size.
25
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
14
26
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
27
+ // Though, the bitmask solution is not perfect since the bytes exceeding
28
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
29
+ // the random bytes redundancy has to be satisfied.
30
+
31
+ // Note: every hardware random generator call is performance expensive,
32
+ // because the system call for entropy collection takes a lot of time.
33
+ // So, to avoid additional system calls, extra bytes are requested in advance.
34
+
35
+ // Next, a step determines how many random bytes to generate.
36
+ // The number of random bytes gets decided upon the ID size, mask,
37
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
38
+ // according to benchmarks).
15
39
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
40
+
16
41
  let tick = (id, size = defaultSize) =>
17
42
  random(step).then(bytes => {
43
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
18
44
  let i = step
19
45
  while (i--) {
46
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
20
47
  id += alphabet[bytes[i] & mask] || ''
21
- if (id.length === size) return id
48
+ if (id.length >= size) return id
22
49
  }
23
50
  return tick(id, size)
24
51
  })
52
+
25
53
  return size => tick('', size)
26
54
  }
55
+
27
56
  let nanoid = (size = 21) =>
28
- random(size).then(bytes => {
57
+ random((size |= 0)).then(bytes => {
29
58
  let id = ''
59
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
30
60
  while (size--) {
61
+ // It is incorrect to use bytes exceeding the alphabet size.
62
+ // The following mask reduces the random byte in the 0-255 value
63
+ // range to the 0-63 value range. Therefore, adding hacks, such
64
+ // as empty string fallback or magic numbers, is unneccessary because
65
+ // the bitmask trims bytes down to the alphabet size.
31
66
  id += urlAlphabet[bytes[size] & 63]
32
67
  }
33
68
  return id
34
69
  })
70
+
35
71
  module.exports = { nanoid, customAlphabet, random }
package/async/index.js CHANGED
@@ -1,7 +1,14 @@
1
1
  import crypto from 'crypto'
2
+
2
3
  import { urlAlphabet } from '../url-alphabet/index.js'
4
+
5
+ // `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
6
+ // because it is possible to use in combination with `Buffer.allocUnsafe()`.
3
7
  let random = bytes =>
4
8
  new Promise((resolve, reject) => {
9
+ // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
10
+ // Memory flushing is unnecessary since the buffer allocation itself resets
11
+ // the memory with the new bytes.
5
12
  crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
6
13
  if (err) {
7
14
  reject(err)
@@ -10,26 +17,55 @@ let random = bytes =>
10
17
  }
11
18
  })
12
19
  })
20
+
13
21
  let customAlphabet = (alphabet, defaultSize = 21) => {
22
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
23
+ // values closer to the alphabet size. The bitmask calculates the closest
24
+ // `2^31 - 1` number, which exceeds the alphabet size.
25
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
14
26
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
27
+ // Though, the bitmask solution is not perfect since the bytes exceeding
28
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
29
+ // the random bytes redundancy has to be satisfied.
30
+
31
+ // Note: every hardware random generator call is performance expensive,
32
+ // because the system call for entropy collection takes a lot of time.
33
+ // So, to avoid additional system calls, extra bytes are requested in advance.
34
+
35
+ // Next, a step determines how many random bytes to generate.
36
+ // The number of random bytes gets decided upon the ID size, mask,
37
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
38
+ // according to benchmarks).
15
39
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
40
+
16
41
  let tick = (id, size = defaultSize) =>
17
42
  random(step).then(bytes => {
43
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
18
44
  let i = step
19
45
  while (i--) {
46
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
20
47
  id += alphabet[bytes[i] & mask] || ''
21
- if (id.length === size) return id
48
+ if (id.length >= size) return id
22
49
  }
23
50
  return tick(id, size)
24
51
  })
52
+
25
53
  return size => tick('', size)
26
54
  }
55
+
27
56
  let nanoid = (size = 21) =>
28
- random(size).then(bytes => {
57
+ random((size |= 0)).then(bytes => {
29
58
  let id = ''
59
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
30
60
  while (size--) {
61
+ // It is incorrect to use bytes exceeding the alphabet size.
62
+ // The following mask reduces the random byte in the 0-255 value
63
+ // range to the 0-63 value range. Therefore, adding hacks, such
64
+ // as empty string fallback or magic numbers, is unneccessary because
65
+ // the bitmask trims bytes down to the alphabet size.
31
66
  id += urlAlphabet[bytes[size] & 63]
32
67
  }
33
68
  return id
34
69
  })
70
+
35
71
  export { nanoid, customAlphabet, random }
@@ -1,26 +1,57 @@
1
1
  import { getRandomBytesAsync } from 'expo-random'
2
+
2
3
  import { urlAlphabet } from '../url-alphabet/index.js'
4
+
3
5
  let random = getRandomBytesAsync
6
+
4
7
  let customAlphabet = (alphabet, defaultSize = 21) => {
8
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
9
+ // values closer to the alphabet size. The bitmask calculates the closest
10
+ // `2^31 - 1` number, which exceeds the alphabet size.
11
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
5
12
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
13
+ // Though, the bitmask solution is not perfect since the bytes exceeding
14
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
15
+ // the random bytes redundancy has to be satisfied.
16
+
17
+ // Note: every hardware random generator call is performance expensive,
18
+ // because the system call for entropy collection takes a lot of time.
19
+ // So, to avoid additional system calls, extra bytes are requested in advance.
20
+
21
+ // Next, a step determines how many random bytes to generate.
22
+ // The number of random bytes gets decided upon the ID size, mask,
23
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
24
+ // according to benchmarks).
6
25
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
26
+
7
27
  let tick = (id, size = defaultSize) =>
8
28
  random(step).then(bytes => {
29
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
9
30
  let i = step
10
31
  while (i--) {
32
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
11
33
  id += alphabet[bytes[i] & mask] || ''
12
- if (id.length === size) return id
34
+ if (id.length >= size) return id
13
35
  }
14
36
  return tick(id, size)
15
37
  })
38
+
16
39
  return size => tick('', size)
17
40
  }
41
+
18
42
  let nanoid = (size = 21) =>
19
- random(size).then(bytes => {
43
+ random((size |= 0)).then(bytes => {
20
44
  let id = ''
45
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
21
46
  while (size--) {
47
+ // It is incorrect to use bytes exceeding the alphabet size.
48
+ // The following mask reduces the random byte in the 0-255 value
49
+ // range to the 0-63 value range. Therefore, adding hacks, such
50
+ // as empty string fallback or magic numbers, is unneccessary because
51
+ // the bitmask trims bytes down to the alphabet size.
22
52
  id += urlAlphabet[bytes[size] & 63]
23
53
  }
24
54
  return id
25
55
  })
56
+
26
57
  export { nanoid, customAlphabet, random }
package/index.browser.cjs CHANGED
@@ -1,28 +1,65 @@
1
+ // This file replaces `index.js` in bundlers like webpack or Rollup,
2
+ // according to `browser` config in `package.json`.
3
+
1
4
  let { urlAlphabet } = require('./url-alphabet/index.cjs')
5
+
2
6
  let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
7
+
3
8
  let customRandom = (alphabet, defaultSize, getRandom) => {
9
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
10
+ // values closer to the alphabet size. The bitmask calculates the closest
11
+ // `2^31 - 1` number, which exceeds the alphabet size.
12
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
13
+ // `Math.clz32` is not used, because it is not available in browsers.
4
14
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
15
+ // Though, the bitmask solution is not perfect since the bytes exceeding
16
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
17
+ // the random bytes redundancy has to be satisfied.
18
+
19
+ // Note: every hardware random generator call is performance expensive,
20
+ // because the system call for entropy collection takes a lot of time.
21
+ // So, to avoid additional system calls, extra bytes are requested in advance.
22
+
23
+ // Next, a step determines how many random bytes to generate.
24
+ // The number of random bytes gets decided upon the ID size, mask,
25
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
26
+ // according to benchmarks).
27
+
28
+ // `-~f => Math.ceil(f)` if f is a float
29
+ // `-~i => i + 1` if i is an integer
5
30
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
31
+
6
32
  return (size = defaultSize) => {
7
33
  let id = ''
8
34
  while (true) {
9
35
  let bytes = getRandom(step)
10
- let j = step
36
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
37
+ let j = step | 0
11
38
  while (j--) {
39
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
12
40
  id += alphabet[bytes[j] & mask] || ''
13
41
  if (id.length === size) return id
14
42
  }
15
43
  }
16
44
  }
17
45
  }
46
+
18
47
  let customAlphabet = (alphabet, size = 21) =>
19
48
  customRandom(alphabet, size, random)
49
+
20
50
  let nanoid = (size = 21) =>
21
51
  crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
52
+ // It is incorrect to use bytes exceeding the alphabet size.
53
+ // The following mask reduces the random byte in the 0-255 value
54
+ // range to the 0-63 value range. Therefore, adding hacks, such
55
+ // as empty string fallback or magic numbers, is unneccessary because
56
+ // the bitmask trims bytes down to the alphabet size.
22
57
  byte &= 63
23
58
  if (byte < 36) {
59
+ // `0-9a-z`
24
60
  id += byte.toString(36)
25
61
  } else if (byte < 62) {
62
+ // `A-Z`
26
63
  id += (byte - 26).toString(36).toUpperCase()
27
64
  } else if (byte > 62) {
28
65
  id += '-'
@@ -31,4 +68,5 @@ let nanoid = (size = 21) =>
31
68
  }
32
69
  return id
33
70
  }, '')
71
+
34
72
  module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
package/index.browser.js CHANGED
@@ -1,28 +1,65 @@
1
+ // This file replaces `index.js` in bundlers like webpack or Rollup,
2
+ // according to `browser` config in `package.json`.
3
+
1
4
  import { urlAlphabet } from './url-alphabet/index.js'
5
+
2
6
  let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
7
+
3
8
  let customRandom = (alphabet, defaultSize, getRandom) => {
9
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
10
+ // values closer to the alphabet size. The bitmask calculates the closest
11
+ // `2^31 - 1` number, which exceeds the alphabet size.
12
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
13
+ // `Math.clz32` is not used, because it is not available in browsers.
4
14
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
15
+ // Though, the bitmask solution is not perfect since the bytes exceeding
16
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
17
+ // the random bytes redundancy has to be satisfied.
18
+
19
+ // Note: every hardware random generator call is performance expensive,
20
+ // because the system call for entropy collection takes a lot of time.
21
+ // So, to avoid additional system calls, extra bytes are requested in advance.
22
+
23
+ // Next, a step determines how many random bytes to generate.
24
+ // The number of random bytes gets decided upon the ID size, mask,
25
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
26
+ // according to benchmarks).
27
+
28
+ // `-~f => Math.ceil(f)` if f is a float
29
+ // `-~i => i + 1` if i is an integer
5
30
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
31
+
6
32
  return (size = defaultSize) => {
7
33
  let id = ''
8
34
  while (true) {
9
35
  let bytes = getRandom(step)
10
- let j = step
36
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
37
+ let j = step | 0
11
38
  while (j--) {
39
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
12
40
  id += alphabet[bytes[j] & mask] || ''
13
41
  if (id.length === size) return id
14
42
  }
15
43
  }
16
44
  }
17
45
  }
46
+
18
47
  let customAlphabet = (alphabet, size = 21) =>
19
48
  customRandom(alphabet, size, random)
49
+
20
50
  let nanoid = (size = 21) =>
21
51
  crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
52
+ // It is incorrect to use bytes exceeding the alphabet size.
53
+ // The following mask reduces the random byte in the 0-255 value
54
+ // range to the 0-63 value range. Therefore, adding hacks, such
55
+ // as empty string fallback or magic numbers, is unneccessary because
56
+ // the bitmask trims bytes down to the alphabet size.
22
57
  byte &= 63
23
58
  if (byte < 36) {
59
+ // `0-9a-z`
24
60
  id += byte.toString(36)
25
61
  } else if (byte < 62) {
62
+ // `A-Z`
26
63
  id += (byte - 26).toString(36).toUpperCase()
27
64
  } else if (byte > 62) {
28
65
  id += '-'
@@ -31,4 +68,5 @@ let nanoid = (size = 21) =>
31
68
  }
32
69
  return id
33
70
  }, '')
71
+
34
72
  export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
package/index.cjs CHANGED
@@ -1,7 +1,15 @@
1
1
  let crypto = require('crypto')
2
+
2
3
  let { urlAlphabet } = require('./url-alphabet/index.cjs')
4
+
5
+ // It is best to make fewer, larger requests to the crypto module to
6
+ // avoid system call overhead. So, random numbers are generated in a
7
+ // pool. The pool is a Buffer that is larger than the initial random
8
+ // request size by this multiplier. The pool is enlarged if subsequent
9
+ // requests exceed the maximum buffer size.
3
10
  const POOL_SIZE_MULTIPLIER = 128
4
11
  let pool, poolOffset
12
+
5
13
  let fillPool = bytes => {
6
14
  if (!pool || pool.length < bytes) {
7
15
  pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
@@ -13,33 +21,65 @@ let fillPool = bytes => {
13
21
  }
14
22
  poolOffset += bytes
15
23
  }
24
+
16
25
  let random = bytes => {
17
- fillPool((bytes -= 0))
26
+ // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution
27
+ fillPool((bytes |= 0))
18
28
  return pool.subarray(poolOffset - bytes, poolOffset)
19
29
  }
30
+
20
31
  let customRandom = (alphabet, defaultSize, getRandom) => {
32
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
33
+ // values closer to the alphabet size. The bitmask calculates the closest
34
+ // `2^31 - 1` number, which exceeds the alphabet size.
35
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
21
36
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
37
+ // Though, the bitmask solution is not perfect since the bytes exceeding
38
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
39
+ // the random bytes redundancy has to be satisfied.
40
+
41
+ // Note: every hardware random generator call is performance expensive,
42
+ // because the system call for entropy collection takes a lot of time.
43
+ // So, to avoid additional system calls, extra bytes are requested in advance.
44
+
45
+ // Next, a step determines how many random bytes to generate.
46
+ // The number of random bytes gets decided upon the ID size, mask,
47
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
48
+ // according to benchmarks).
22
49
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
50
+
23
51
  return (size = defaultSize) => {
24
52
  let id = ''
25
53
  while (true) {
26
54
  let bytes = getRandom(step)
55
+ // A compact alternative for `for (let i = 0; i < step; i++)`.
27
56
  let i = step
28
57
  while (i--) {
58
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
29
59
  id += alphabet[bytes[i] & mask] || ''
30
60
  if (id.length === size) return id
31
61
  }
32
62
  }
33
63
  }
34
64
  }
65
+
35
66
  let customAlphabet = (alphabet, size = 21) =>
36
67
  customRandom(alphabet, size, random)
68
+
37
69
  let nanoid = (size = 21) => {
38
- fillPool((size -= 0))
70
+ // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution
71
+ fillPool((size |= 0))
39
72
  let id = ''
73
+ // We are reading directly from the random pool to avoid creating new array
40
74
  for (let i = poolOffset - size; i < poolOffset; i++) {
75
+ // It is incorrect to use bytes exceeding the alphabet size.
76
+ // The following mask reduces the random byte in the 0-255 value
77
+ // range to the 0-63 value range. Therefore, adding hacks, such
78
+ // as empty string fallback or magic numbers, is unneccessary because
79
+ // the bitmask trims bytes down to the alphabet size.
41
80
  id += urlAlphabet[pool[i] & 63]
42
81
  }
43
82
  return id
44
83
  }
84
+
45
85
  module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
package/index.d.cts ADDED
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Generate secure URL-friendly unique ID.
3
+ *
4
+ * By default, the ID will have 21 symbols to have a collision probability
5
+ * similar to UUID v4.
6
+ *
7
+ * ```js
8
+ * import { nanoid } from 'nanoid'
9
+ * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"
10
+ * ```
11
+ *
12
+ * @param size Size of the ID. The default size is 21.
13
+ * @returns A random string.
14
+ */
15
+ export function nanoid(size?: number): string
16
+
17
+ /**
18
+ * Generate secure unique ID with custom alphabet.
19
+ *
20
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
21
+ * will not be secure.
22
+ *
23
+ * @param alphabet Alphabet used to generate the ID.
24
+ * @param defaultSize Size of the ID. The default size is 21.
25
+ * @returns A random string generator.
26
+ *
27
+ * ```js
28
+ * const { customAlphabet } = require('nanoid')
29
+ * const nanoid = customAlphabet('0123456789абвгдеё', 5)
30
+ * nanoid() //=> "8ё56а"
31
+ * ```
32
+ */
33
+ export function customAlphabet(
34
+ alphabet: string,
35
+ defaultSize?: number
36
+ ): (size?: number) => string
37
+
38
+ /**
39
+ * Generate unique ID with custom random generator and alphabet.
40
+ *
41
+ * Alphabet must contain 256 symbols or less. Otherwise, the generator
42
+ * will not be secure.
43
+ *
44
+ * ```js
45
+ * import { customRandom } from 'nanoid/format'
46
+ *
47
+ * const nanoid = customRandom('abcdef', 5, size => {
48
+ * const random = []
49
+ * for (let i = 0; i < size; i++) {
50
+ * random.push(randomByte())
51
+ * }
52
+ * return random
53
+ * })
54
+ *
55
+ * nanoid() //=> "fbaef"
56
+ * ```
57
+ *
58
+ * @param alphabet Alphabet used to generate a random string.
59
+ * @param size Size of the random string.
60
+ * @param random A random bytes generator.
61
+ * @returns A random string generator.
62
+ */
63
+ export function customRandom(
64
+ alphabet: string,
65
+ size: number,
66
+ random: (bytes: number) => Uint8Array
67
+ ): () => string
68
+
69
+ /**
70
+ * URL safe symbols.
71
+ *
72
+ * ```js
73
+ * import { urlAlphabet } from 'nanoid'
74
+ * const nanoid = customAlphabet(urlAlphabet, 10)
75
+ * nanoid() //=> "Uakgb_J5m9"
76
+ * ```
77
+ */
78
+ export const urlAlphabet: string
79
+
80
+ /**
81
+ * Generate an array of random bytes collected from hardware noise.
82
+ *
83
+ * ```js
84
+ * import { customRandom, random } from 'nanoid'
85
+ * const nanoid = customRandom("abcdef", 5, random)
86
+ * ```
87
+ *
88
+ * @param bytes Size of the array.
89
+ * @returns An array of random bytes.
90
+ */
91
+ export function random(bytes: number): Uint8Array
package/index.js CHANGED
@@ -1,7 +1,15 @@
1
1
  import crypto from 'crypto'
2
+
2
3
  import { urlAlphabet } from './url-alphabet/index.js'
4
+
5
+ // It is best to make fewer, larger requests to the crypto module to
6
+ // avoid system call overhead. So, random numbers are generated in a
7
+ // pool. The pool is a Buffer that is larger than the initial random
8
+ // request size by this multiplier. The pool is enlarged if subsequent
9
+ // requests exceed the maximum buffer size.
3
10
  const POOL_SIZE_MULTIPLIER = 128
4
11
  let pool, poolOffset
12
+
5
13
  let fillPool = bytes => {
6
14
  if (!pool || pool.length < bytes) {
7
15
  pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
@@ -13,33 +21,65 @@ let fillPool = bytes => {
13
21
  }
14
22
  poolOffset += bytes
15
23
  }
24
+
16
25
  let random = bytes => {
17
- fillPool((bytes -= 0))
26
+ // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution
27
+ fillPool((bytes |= 0))
18
28
  return pool.subarray(poolOffset - bytes, poolOffset)
19
29
  }
30
+
20
31
  let customRandom = (alphabet, defaultSize, getRandom) => {
32
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
33
+ // values closer to the alphabet size. The bitmask calculates the closest
34
+ // `2^31 - 1` number, which exceeds the alphabet size.
35
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
21
36
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
37
+ // Though, the bitmask solution is not perfect since the bytes exceeding
38
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
39
+ // the random bytes redundancy has to be satisfied.
40
+
41
+ // Note: every hardware random generator call is performance expensive,
42
+ // because the system call for entropy collection takes a lot of time.
43
+ // So, to avoid additional system calls, extra bytes are requested in advance.
44
+
45
+ // Next, a step determines how many random bytes to generate.
46
+ // The number of random bytes gets decided upon the ID size, mask,
47
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
48
+ // according to benchmarks).
22
49
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
50
+
23
51
  return (size = defaultSize) => {
24
52
  let id = ''
25
53
  while (true) {
26
54
  let bytes = getRandom(step)
55
+ // A compact alternative for `for (let i = 0; i < step; i++)`.
27
56
  let i = step
28
57
  while (i--) {
58
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
29
59
  id += alphabet[bytes[i] & mask] || ''
30
60
  if (id.length === size) return id
31
61
  }
32
62
  }
33
63
  }
34
64
  }
65
+
35
66
  let customAlphabet = (alphabet, size = 21) =>
36
67
  customRandom(alphabet, size, random)
68
+
37
69
  let nanoid = (size = 21) => {
38
- fillPool((size -= 0))
70
+ // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution
71
+ fillPool((size |= 0))
39
72
  let id = ''
73
+ // We are reading directly from the random pool to avoid creating new array
40
74
  for (let i = poolOffset - size; i < poolOffset; i++) {
75
+ // It is incorrect to use bytes exceeding the alphabet size.
76
+ // The following mask reduces the random byte in the 0-255 value
77
+ // range to the 0-63 value range. Therefore, adding hacks, such
78
+ // as empty string fallback or magic numbers, is unneccessary because
79
+ // the bitmask trims bytes down to the alphabet size.
41
80
  id += urlAlphabet[pool[i] & 63]
42
81
  }
43
82
  return id
44
83
  }
84
+
45
85
  export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
@@ -1,21 +1,34 @@
1
+ // This alphabet uses `A-Za-z0-9_-` symbols.
2
+ // The order of characters is optimized for better gzip and brotli compression.
3
+ // References to the same file (works both for gzip and brotli):
4
+ // `'use`, `andom`, and `rict'`
5
+ // References to the brotli default dictionary:
6
+ // `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf`
1
7
  let urlAlphabet =
2
8
  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
9
+
3
10
  let customAlphabet = (alphabet, defaultSize = 21) => {
4
11
  return (size = defaultSize) => {
5
12
  let id = ''
6
- let i = size
13
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
14
+ let i = size | 0
7
15
  while (i--) {
16
+ // `| 0` is more compact and faster than `Math.floor()`.
8
17
  id += alphabet[(Math.random() * alphabet.length) | 0]
9
18
  }
10
19
  return id
11
20
  }
12
21
  }
22
+
13
23
  let nanoid = (size = 21) => {
14
24
  let id = ''
15
- let i = size
25
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
26
+ let i = size | 0
16
27
  while (i--) {
28
+ // `| 0` is more compact and faster than `Math.floor()`.
17
29
  id += urlAlphabet[(Math.random() * 64) | 0]
18
30
  }
19
31
  return id
20
32
  }
33
+
21
34
  module.exports = { nanoid, customAlphabet }