idkitx
Version:
Generates compact, URL-safe IDs optimized for humans and database performance. Supports random, deterministic, and sequential modes for idempotency, deduplication, and index efficiency.
48 lines • 2.04 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.generateId = exports.encodeCharset = exports.CROCKFORD = exports.BASE62 = void 0;
const crypto_1 = require("crypto");
exports.BASE62 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
exports.CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; // No I, L, O, U
function encodeCharset(input, length, charset) {
let num = typeof input === 'bigint'
? input
: BigInt(`0x${input.toString('hex')}`);
const chars = [];
const base = BigInt(charset.length);
while (chars.length < length) {
const index = Number(num % base);
chars.unshift(charset[index]);
num /= base;
}
return chars.join('');
}
exports.encodeCharset = encodeCharset;
/**
* Generates a compact, encoded ID.
*
* - Random by default
* - Deterministic if `input` is provided
* - Sequential if `sequential: true`
*/
function generateId(options = {}) {
const { input, sequential = false, length = options.sequential ? 16 : 10, alphabet = 'base62', } = options;
const charset = alphabet === 'crockford' ? exports.CROCKFORD : exports.BASE62;
if (input) {
const hash = (0, crypto_1.createHash)('sha256').update(input).digest();
return encodeCharset(hash, length, charset);
}
if (sequential) {
if (length < 16)
throw new Error('Sequential ID length must be at least 16 to include timestamp prefix');
const timestamp = Date.now().toString(36).padStart(8, '0');
const randLength = length - 8;
const randomBytesNeeded = Math.ceil((randLength * Math.log2(charset.length)) / 8);
const randPart = encodeCharset((0, crypto_1.randomBytes)(randomBytesNeeded), randLength, charset);
return timestamp + randPart;
}
const raw = (0, crypto_1.randomBytes)(Math.ceil((length * Math.log2(charset.length)) / 8));
return encodeCharset(raw, length, charset);
}
exports.generateId = generateId;
//# sourceMappingURL=generateId.js.map