UNPKG

@earendil-works/pi-coding-agent

Version:

Coding agent CLI with read, bash, edit, write tools and session management

3 lines (2 loc) • 1.53 kB
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); var MAX_SEQUENCE=(1n<<41n)-1n,lastOrdinaryTimestamp=-1,sequence;function uuidv7(timestampMs){let requestedTimestamp=timestampMs??Date.now();if(!Number.isInteger(requestedTimestamp)||requestedTimestamp<0||requestedTimestamp>0xffffffffffff)throw new RangeError(`UUIDv7 timestamp must be an integer between 0 and ${0xffffffffffff}`);let effectiveTimestamp=timestampMs===void 0?Math.max(requestedTimestamp,lastOrdinaryTimestamp):timestampMs;timestampMs===void 0&&(lastOrdinaryTimestamp=effectiveTimestamp);let bytes=new Uint8Array(16);if(globalThis.crypto.getRandomValues(bytes),sequence===void 0)sequence=BigInt(bytes[1])<<32n|BigInt(bytes[2])<<24n|BigInt(bytes[3])<<16n|BigInt(bytes[4])<<8n|BigInt(bytes[5]);else{if(sequence===MAX_SEQUENCE)throw new RangeError("UUIDv7 generator sequence exhausted");sequence++}let timestamp=BigInt(effectiveTimestamp);for(let index=5;index>=0;index--)bytes[index]=Number(timestamp>>BigInt((5-index)*8))&255;bytes[6]=112|Number(sequence>>37n&0x0fn),bytes[7]=Number(sequence>>29n&0xffn),bytes[8]=128|Number(sequence>>23n&0x3fn),bytes[9]=Number(sequence>>15n&0xffn),bytes[10]=Number(sequence>>7n&0xffn),bytes[11]=Number((sequence&0x7fn)<<1n)|bytes[11]&1;let hex=Array.from(bytes,byte=>byte.toString(16).padStart(2,"0"));return`${hex.slice(0,4).join("")}-${hex.slice(4,6).join("")}-${hex.slice(6,8).join("")}-${hex.slice(8,10).join("")}-${hex.slice(10).join("")}`}export{uuidv7};