UNPKG

1.21 kBPlain TextView Raw
1import { customAlphabet } from 'nanoid'
2import { customAlphabet as customAlphabetAsync } from 'nanoid/async'
3import { customAlphabet as customAlphabetNonSecure } from 'nanoid/non-secure'
4
5export const ALPHABET_NUMBER = '0123456789'
6export const ALPHABET_LOWERCASE = 'abcdefghijklmnopqrstuvwxyz'
7export const ALPHABET_UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
8export const ALPHABET_ALPHANUMERIC_LOWERCASE = [ALPHABET_NUMBER, ALPHABET_LOWERCASE].join('')
9export const ALPHABET_ALPHANUMERIC_UPPERCASE = [ALPHABET_NUMBER, ALPHABET_UPPERCASE].join('')
10export const ALPHABET_ALPHANUMERIC = [ALPHABET_NUMBER, ALPHABET_LOWERCASE, ALPHABET_UPPERCASE].join(
11 '',
12)
13
14/**
15 * Generate cryptographically-secure string id.
16 * Powered by `nanoid`.
17 */
18export function stringId(length = 16, alphabet = ALPHABET_ALPHANUMERIC_LOWERCASE): string {
19 return customAlphabet(alphabet, length)()
20}
21
22export async function stringIdAsync(
23 length = 16,
24 alphabet = ALPHABET_ALPHANUMERIC_LOWERCASE,
25): Promise<string> {
26 return await customAlphabetAsync(alphabet, length)()
27}
28
29export function stringIdUnsafe(length = 16, alphabet = ALPHABET_ALPHANUMERIC_LOWERCASE): string {
30 return customAlphabetNonSecure(alphabet, length)()
31}