UNPKG

@techmely/utils

Version:

Collection of helpful JavaScript / TypeScript utils

67 lines (62 loc) 2.06 kB
/*! * @techmely/utils * Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com> * MIT Licensed */ "use strict"; (() => { var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) { if (typeof require !== "undefined") return require.apply(this, arguments); throw Error('Dynamic require of "' + x + '" is not supported'); }); // ../../node_modules/nanoid/index.js var import_node_crypto = __require("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); import_node_crypto.webcrypto.getRandomValues(pool); poolOffset = 0; } else if (poolOffset + bytes > pool.length) { import_node_crypto.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)}`; } })();