1 | import crypto from 'crypto'
|
---|
2 | import { urlAlphabet } from './url-alphabet/index.js'
|
---|
3 | const POOL_SIZE_MULTIPLIER = 128
|
---|
4 | let pool, poolOffset
|
---|
5 | let fillPool = bytes => {
|
---|
6 | if (!pool || pool.length < bytes) {
|
---|
7 | pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
|
---|
8 | crypto.randomFillSync(pool)
|
---|
9 | poolOffset = 0
|
---|
10 | } else if (poolOffset + bytes > pool.length) {
|
---|
11 | crypto.randomFillSync(pool)
|
---|
12 | poolOffset = 0
|
---|
13 | }
|
---|
14 | poolOffset += bytes
|
---|
15 | }
|
---|
16 | let random = bytes => {
|
---|
17 | fillPool(bytes)
|
---|
18 | return pool.subarray(poolOffset - bytes, poolOffset)
|
---|
19 | }
|
---|
20 | let customRandom = (alphabet, size, getRandom) => {
|
---|
21 | let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
|
---|
22 | let step = Math.ceil((1.6 * mask * size) / alphabet.length)
|
---|
23 | return () => {
|
---|
24 | let id = ''
|
---|
25 | while (true) {
|
---|
26 | let bytes = getRandom(step)
|
---|
27 | let i = step
|
---|
28 | while (i--) {
|
---|
29 | id += alphabet[bytes[i] & mask] || ''
|
---|
30 | if (id.length === size) return id
|
---|
31 | }
|
---|
32 | }
|
---|
33 | }
|
---|
34 | }
|
---|
35 | let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)
|
---|
36 | let nanoid = (size = 21) => {
|
---|
37 | fillPool(size)
|
---|
38 | let id = ''
|
---|
39 | for (let i = poolOffset - size; i < poolOffset; i++) {
|
---|
40 | id += urlAlphabet[pool[i] & 63]
|
---|
41 | }
|
---|
42 | return id
|
---|
43 | }
|
---|
44 | export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
|
---|