@glandjs/common
Version:
Glands is a web framework for Node.js (@common)
67 lines (66 loc) • 2.24 kB
JavaScript
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.CryptoUUID = void 0;
const node_crypto_1 = require("node:crypto");
class CryptoUUID {
static generate(options, buffer) {
if (buffer && !options) {
return (0, node_crypto_1.randomUUID)();
}
const rnds = this.getEntropy(options);
rnds[6] = (rnds[6] & 0x0f) | this.VERSION;
rnds[8] = (rnds[8] & 0x3f) | this.VARIANT;
if (buffer) {
const offset = options?.offset || 0;
this.validateBuffer(buffer, offset);
buffer.set(rnds, offset);
return buffer;
}
return this.format(rnds);
}
static validate(uuid) {
if (typeof uuid === 'string') {
return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(uuid);
}
return this.isValidBuffer(uuid);
}
static getEntropy(options = {}) {
if (options.random?.length >= 16)
return options.random;
if (options.rng)
return options.rng();
if (this.poolPtr > this.POOL_SIZE - 16) {
(0, node_crypto_1.randomFillSync)(this.pool);
this.poolPtr = 0;
}
return this.pool.slice(this.poolPtr, (this.poolPtr += 16));
}
static format(bytes) {
return [
this.hex(bytes, 0, 4),
this.hex(bytes, 4, 6),
this.hex(bytes, 6, 8),
this.hex(bytes, 8, 10),
this.hex(bytes, 10, 16),
].join('-');
}
static hex(bytes, start, end) {
return Buffer.from(bytes.slice(start, end)).toString('hex');
}
static validateBuffer(buffer, offset) {
if (offset < 0 || offset + 16 > buffer.length) {
throw new RangeError(`Invalid buffer range: ${offset} to ${offset + 16}`);
}
}
static isValidBuffer(buffer) {
return buffer[6] === (this.VERSION & 0x0f) && (buffer[8] & 0xc0) === this.VARIANT;
}
}
exports.CryptoUUID = CryptoUUID;
_a = CryptoUUID;
CryptoUUID.VERSION = 0x40;
CryptoUUID.VARIANT = 0x80;
CryptoUUID.POOL_SIZE = 256;
CryptoUUID.pool = new Uint8Array(_a.POOL_SIZE);
CryptoUUID.poolPtr = _a.POOL_SIZE;