UNPKG

@techmely/utils

Version:

Collection of helpful JavaScript / TypeScript utils

52 lines (48 loc) 1.45 kB
import './chunk-NYLAFCGV.mjs'; import { webcrypto } from 'node:crypto'; var POOL_SIZE_MULTIPLIER = 128; var pool; var poolOffset; function fillPool(bytes) { if (!pool || pool.length < bytes) { pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER); webcrypto.getRandomValues(pool); poolOffset = 0; } else if (poolOffset + bytes > pool.length) { webcrypto.getRandomValues(pool); poolOffset = 0; } poolOffset += bytes; } function random(bytes) { fillPool(bytes -= 0); return pool.subarray(poolOffset - bytes, poolOffset); } function customRandom(alphabet, defaultSize, getRandom) { let mask = (2 << 31 - Math.clz32(alphabet.length - 1 | 1)) - 1; let step = Math.ceil(1.6 * mask * defaultSize / alphabet.length); return (size = defaultSize) => { let id = ""; while (true) { let bytes = getRandom(step); let i = step; while (i--) { id += alphabet[bytes[i] & mask] || ""; if (id.length === size) return id; } } }; } function customAlphabet(alphabet, size = 21) { return customRandom(alphabet, size, random); } // src/id.ts var generateId = customAlphabet( "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ); var DEFAULT_PREFIX_ID_LENGTH = 22; function generatePrefixId(prefix = "key", length = DEFAULT_PREFIX_ID_LENGTH) { return `${prefix}_${generateId(length)}`; } export { DEFAULT_PREFIX_ID_LENGTH, generateId, generatePrefixId };