UNPKG

1.58 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.stringIdBase64Url = exports.stringIdBase64 = exports.stringIdBase62 = exports.stringId = void 0;
4const crypto = require("node:crypto");
5const nanoid_1 = require("./nanoid");
6/**
7 * Generate cryptographically-secure string id.
8 * Powered by `nanoid`.
9 */
10function stringId(length = 16, alphabet = nanoid_1.ALPHABET_ALPHANUMERIC_LOWERCASE) {
11 return (0, nanoid_1.nanoIdCustomAlphabet)(alphabet, length)();
12}
13exports.stringId = stringId;
14/**
15 * Generate a string id of Base62 alphabet (same as "alphanumeric": A-Za-z0-9)
16 *
17 * Length is 16 (non-configurable currently).
18 */
19exports.stringIdBase62 = (0, nanoid_1.nanoIdCustomAlphabet)(nanoid_1.ALPHABET_ALPHANUMERIC, 16);
20/**
21 * Generate a string id of Base64 alphabet: A-Za-z0-9+/
22 *
23 * Default length is 16.
24 * Length should be dividable by 4 (otherwise unexpected length will be produced).
25 *
26 * Dividable by 4 lengths produce ids with no padding `=` characters, which is optimal.
27 */
28function stringIdBase64(size = 16) {
29 return crypto.randomBytes(size * 0.75).toString('base64');
30}
31exports.stringIdBase64 = stringIdBase64;
32/**
33 * Generate a string id of Base64url alphabet: A-Za-z0-9-_
34 *
35 * Default length is 16.
36 * Length should be dividable by 4 (otherwise unexpected length will be produced).
37 *
38 * Base64url always produces strings without a padding character `=`, by design.
39 */
40function stringIdBase64Url(size = 16) {
41 return crypto.randomBytes(size * 0.75).toString('base64url');
42}
43exports.stringIdBase64Url = stringIdBase64Url;