@langchain/core
Version:
Core LangChain.js abstractions and schemas
57 lines (56 loc) • 1.94 kB
JavaScript
const require_stringify = require("./stringify.cjs");
const require_rng = require("./rng.cjs");
//#region src/utils/uuid/v7.ts
const _state = {};
function v7(options, buf, offset) {
let bytes;
if (options) bytes = v7Bytes(options.random ?? options.rng?.() ?? require_rng.default(), options.msecs, options.seq, buf, offset);
else {
const now = Date.now();
const rnds = require_rng.default();
updateV7State(_state, now, rnds);
bytes = v7Bytes(rnds, _state.msecs, _state.seq, buf, offset);
}
return buf ?? require_stringify.unsafeStringify(bytes);
}
function updateV7State(state, now, rnds) {
state.msecs ??= -Infinity;
state.seq ??= 0;
if (now > state.msecs) {
state.seq = rnds[6] << 23 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
state.msecs = now;
} else {
state.seq = state.seq + 1 | 0;
if (state.seq === 0) state.msecs++;
}
return state;
}
function v7Bytes(rnds, msecs, seq, buf, offset = 0) {
if (rnds.length < 16) throw new Error("Random bytes length must be >= 16");
if (!buf) {
buf = new Uint8Array(16);
offset = 0;
} else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
msecs ??= Date.now();
seq ??= rnds[6] * 127 << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
buf[offset++] = msecs / 1099511627776 & 255;
buf[offset++] = msecs / 4294967296 & 255;
buf[offset++] = msecs / 16777216 & 255;
buf[offset++] = msecs / 65536 & 255;
buf[offset++] = msecs / 256 & 255;
buf[offset++] = msecs & 255;
buf[offset++] = 112 | seq >>> 28 & 15;
buf[offset++] = seq >>> 20 & 255;
buf[offset++] = 128 | seq >>> 14 & 63;
buf[offset++] = seq >>> 6 & 255;
buf[offset++] = seq << 2 & 255 | rnds[10] & 3;
buf[offset++] = rnds[11];
buf[offset++] = rnds[12];
buf[offset++] = rnds[13];
buf[offset++] = rnds[14];
buf[offset++] = rnds[15];
return buf;
}
//#endregion
exports.default = v7;
//# sourceMappingURL=v7.cjs.map