UNPKG

alinea

Version:

[![npm](https://img.shields.io/npm/v/alinea.svg)](https://npmjs.org/package/alinea) [![install size](https://packagephobia.com/badge?p=alinea)](https://packagephobia.com/result?p=alinea)

67 lines (65 loc) 1.73 kB
import "../chunks/chunk-U5RRZUYZ.js"; // src/core/Id.ts import { crypto } from "@alinea/iso"; var BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; function base62(view) { if (view.byteLength !== 20) { throw new Error("incorrect buffer size"); } let str = new Array(27).fill("0"); let n = 27; let bp = new Array(5); bp[0] = view.getUint32(0, false); bp[1] = view.getUint32(4, false); bp[2] = view.getUint32(8, false); bp[3] = view.getUint32(12, false); bp[4] = view.getUint32(16, false); const srcBase = 4294967296n; const dstBase = 62n; while (bp.length != 0) { let quotient = []; let remainder = 0; for (const c of bp) { let value = BigInt(c) + BigInt(remainder) * srcBase; let digit = value / dstBase; remainder = Number(value % dstBase); if (quotient.length !== 0 || digit !== 0n) { quotient.push(Number(digit)); } } n--; str[n] = BASE62.charAt(remainder); bp = quotient; } return str.join(""); } function toEpoch(timestamp, desc) { if (!desc) { return Math.round(timestamp / 1e3) - 14e8; } return 4294967295 - (Math.round(timestamp / 1e3) - 14e8); } function randomBytes() { return crypto.getRandomValues(new Uint8Array(16)); } function generate(desc = false, timestamp = Date.now()) { const buf = new ArrayBuffer(20); const view = new DataView(buf); const ts = toEpoch(timestamp, desc); let offset = 0; view.setUint32(offset, ts, false); offset += 4; const rnd = randomBytes(); for (const b of rnd) { view.setUint8(offset++, b); } if (desc) return "z" + base62(view); return base62(view); } function createId() { return generate(); } export { createId };