UNPKG

@ai2070/l0

Version:

L0: The Missing Reliability Substrate for AI

85 lines 2.23 kB
let externalV7; try { const { v7 } = require("uuid"); if (typeof v7 === "function") externalV7 = v7; } catch { } export function uuidv7() { if (externalV7) { return externalV7(); } return internalV7(); } const _state = { msecs: -Infinity, seq: 0, }; function getRandomBytes(length) { const bytes = new Uint8Array(length); if (typeof crypto !== "undefined" && crypto.getRandomValues) { crypto.getRandomValues(bytes); } else { for (let i = 0; i < length; i++) { bytes[i] = Math.floor(Math.random() * 256); } } return bytes; } function updateV7State(state, now, rnds) { if (now > state.msecs) { state.seq = (rnds[6] << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]; state.msecs = now; } else { state.seq = (state.seq + 1) | 0; if (state.seq === 0) { state.msecs++; } } } function bytesToUuid(bytes) { const hex = Array.from(bytes) .map((b) => b.toString(16).padStart(2, "0")) .join(""); return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; } export function internalV7() { const now = Date.now(); const rnds = getRandomBytes(16); updateV7State(_state, now, rnds); const msecs = _state.msecs; const seq = _state.seq; const buf = new Uint8Array(16); let ts = msecs; buf[5] = ts & 0xff; ts = Math.floor(ts / 256); buf[4] = ts & 0xff; ts = Math.floor(ts / 256); buf[3] = ts & 0xff; ts = Math.floor(ts / 256); buf[2] = ts & 0xff; ts = Math.floor(ts / 256); buf[1] = ts & 0xff; ts = Math.floor(ts / 256); buf[0] = ts & 0xff; buf[6] = 0x70 | ((seq >>> 28) & 0x0f); buf[7] = (seq >>> 20) & 0xff; buf[8] = 0x80 | ((seq >>> 14) & 0x3f); buf[9] = (seq >>> 6) & 0xff; buf[10] = ((seq << 2) & 0xff) | (rnds[10] & 0x03); buf[11] = rnds[11]; buf[12] = rnds[12]; buf[13] = rnds[13]; buf[14] = rnds[14]; buf[15] = rnds[15]; return bytesToUuid(buf); } export function _resetState() { _state.msecs = -Infinity; _state.seq = 0; } //# sourceMappingURL=uuid.js.map