@cldmv/uuid is an extended UUID specification designed for RFC inclusion. It formally extends RFC 4122/9562 with custom variant structures for issuer-based identification and enhanced timestamp variants, and ships a complete implementation of the standard RFC UUID versions alongside it.
The custom variants (TA, TB, IA) live in the variant 111 namespace, so they never collide with standard RFC UUIDs, and the same UUID class parses, validates and inspects both. The package has no runtime dependencies and runs in Node.js and in browser bundles.
RFC-ready custom UUID variants, with every standard RFC UUID version included.
- Breaking:
require("@cldmv/uuid")returns the module object: the CommonJS entry is now the generic shim, sorequire()gives the same exports asimport,{ default, UUID, uuid, ISSUER_CATEGORIES }, not theUUIDclass. Useconst { UUID } = require("@cldmv/uuid"), and call statics on it (UUID.v4(),UUID.NIL)..UUID,.uuidand destructuring keep working; ESMimportis unchanged (#141, fixes #140). - Breaking:
@cldmv/uuid/mainis removed: the deprecated alias is gone; import@cldmv/uuid, which exports the same objects (#154). - The issuer registry is private: its data and entries are no longer reachable from outside, everything it returns is a frozen copy, and the reserved and bundled Category A and B entries are ratified and can't be changed (#148).
- One file per module:
dist/mirrorssrc/instead of shipping a tsup bundle per subpath, so shared code loads once; the exports are unchanged (#152, fixes #138). ci.ymlcancels superseded runs onnextandhotfixes(#142, fixes #139).- View full v3.0.0 Changelog
- v2.1.0 (November 2026):
@cldmv/uuid/entropypublishes theEntropySourcehelpers and@cldmv/uuid/hashgainssha256(#136, resolves #135) (Changelog) - v2.0.1 (November 2026): one set of detail fields for every UUID, RFC or custom (
nullwhere a field doesn't apply),validate()takes strings, andUUID.v1()/UUID.v6()write the right time (#120, fixes #119, #123 and #124) (Changelog) - v2.0.0 (November 2026): full-range timestamps;
TA()/TB()mint versions 5 and 6, whose byte order follows time, plusUUID.compare()andUUID.migrate()to versions 5/6. Breaking: thegetTimestamp()type and byte order against stored 3/4 ids (#117, fixes #100) (Changelog) - v1.5.0 (November 2026):
UUID.entropy()builds a per-tick counter, seed fingerprint and random bits into the entropy forTA()/TB()so ids from one instance never repeat in a tick; tests also run againstdist/(#103, fixes #102) (Changelog)
π For complete version history and detailed release notes, see the docs/changelog/ folder.
- π RFC-Ready Specification: Extended variant (111) with formal bit layout and entropy analysis
- π§ Issuer Variant: 10-bit ID space (0-1023) with categorized allocation (Technology, Open Source, Reserved)
- β±οΈ Timestamp Variants: Signed 70-bit timestamps (TA=seconds, TB=milliseconds) with negative timestamp support
- π― Type-Safe: ESM-first with complete TypeScript definitions
- β‘ High Performance: Optimized bit manipulation, 90K+ UUIDs/sec
- π Collision-Resistant: Cryptographic entropy sources with validation
- π¦ Zero Dependencies: No external runtime dependencies
- π§ͺ Thoroughly Tested: 170+ tests covering all specification requirements
- β Bonus: RFC Support: Complete v1/v3/v4/v5/v6/v7 implementation included
This library implements a new UUID specification that formally extends the RFC 4122/9562 namespace with:
- Custom Variant Structure (111): Entry into extended namespace via bits 64-66
- Subvariant System: Timestamp (00) and Issuer (01) branches with reserved expansion slots
- Issuer-Based Identification: 10-bit issuer ID system with categorized allocation ranges
- Enhanced Timestamp Variants: Signed 70-bit timestamps supporting pre-epoch dates with proper lexicographic ordering
- Formal Bit Layout: Precisely specified field positions maintaining RFC compatibility
The specification is designed for formal RFC submission and includes comprehensive implementation details, entropy requirements, and collision resistance analysis.
- Node.js: >=16.12.0 for
import(the package'sengines.nodefloor). Any modern browser bundler works too, through thebrowserexport condition. - CommonJS (
require()): needs Node.js ^20.19.0 or >=22.13.0.dist/index.cjsis a few lines that load the ESM build through Node's synchronousrequire(esm), sorequire()returns the same exports asimport, as the module object ({ default, UUID, uuid, ISSUER_CATEGORIES }). Node.js versions withoutrequire(esm)get a clearERR_REQUIRE_ESMerror; on those, load the package withimport()instead. - Development: developing this package needs Node.js 22.22.0 or later (
devEngines).
npm install @cldmv/uuidThe primary focus of this library is the new custom UUID specification designed for RFC submission:
import { UUID } from "@cldmv/uuid";
// TA: Timestamp Variant (seconds precision, subvariant 00, mints version 5)
const taUUID = UUID.TA(); // Current time in seconds
const taWithTime = UUID.TA(Math.floor(Date.now() / 1000)); // Explicit timestamp
const taNegative = UUID.TA(-60); // 60 seconds before Unix epoch
// TB: Timestamp Variant (milliseconds precision, subvariant 00, mints version 6)
const tbUUID = UUID.TB(); // Current time in milliseconds
const tbWithTime = UUID.TB(Date.now()); // Explicit timestamp
const tbNegative = UUID.TB(-315619200000); // January 1, 1960
// IA: Issuer Variant v1 (subvariant 01)
const iaUUID = UUID.IA(404); // Spec Originator Reserved ID
const iaOpen = UUID.IA(0); // Unassigned/Open
const iaTech = UUID.IA(100); // Category A (Well-Recognized Technology)
const iaOSS = UUID.IA(300); // Category B (Open Source Ecosystem)
// Extract specification-compliant data
const info = taUUID.getInfo();
console.log(info);
// {
// uuid: "80000000-01ac-...",
// isUUID: true, // a well-formed UUID
// isCLDMV: true, // a CLDMV id (bits 64-66 = 111)
// variant: 7,
// variantFamily: "CLDMV",
// subvariant: 0, // bits 67-68: 00 (Timestamp Variant)
// version: 5, // bits 75-78: 0101 (v5 = seconds, full layout)
// fullVersion: "7.0.5", // variant.subvariant.version
// variantIdentifier: "TA",
// issuerID: null, // only Issuer Variants have one
// issuerCategory: null,
// timestamp: 1766203054,
// timestampUnit: "s",
// date: "2025-12-20T03:57:34.000Z",
// isIssuerVariant: false,
// isTimestampVariant: true
// }
const iaInfo = iaUUID.getInfo();
console.log(iaInfo);
// {
// ...same keys,
// subvariant: 1, // bits 67-68: 01 (Issuer Variant)
// version: 1,
// variantIdentifier: "IA",
// issuerID: 404, // bits 79-88: 10-bit issuer ID
// issuerCategory: "Spec Originator",
// timestamp: null, timestampUnit: null, date: null,
// isIssuerVariant: true,
// isTimestampVariant: false
// }import { UUID } from "@cldmv/uuid";
// Generate RFC 4122/9562 standard UUIDs
const v1 = UUID.v1(); // Timestamp-based
const v4 = UUID.v4(); // Random
const v7 = UUID.v7(); // Unix Epoch (sortable)
// Namespace-based (deterministic)
const v5 = UUID.v5("hello.example.com", UUID.DNS);
// Validate and parse
if (UUID.validateRFC(v4)) {
const bytes = UUID.parse(v4);
const version = UUID.version(v4);
}CommonJS works the same way on Node.js ^20.19.0 or >=22.13.0:
const { UUID } = require("@cldmv/uuid"); // also uuid, ISSUER_CATEGORIES and default
const id = UUID.TB();UUIDs automatically convert to strings when used in string contexts. This provides a seamless developer experience:
import { UUID } from "@cldmv/uuid";
const uuid = UUID.TA();
// Direct usage - automatically converts to string
console.log(uuid); // a454aa7f-8000-019b-e003-cd2480cc8b40
console.log("UUID: " + uuid); // UUID: a454aa7f-8000-019b-e003-cd2480cc8b40
console.log(`UUID: ${uuid}`); // UUID: a454aa7f-8000-019b-e003-cd2480cc8b40
// JSON serialization - automatically converts to string
const obj = { id: uuid };
JSON.stringify(obj); // {"id":"a454aa7f-8000-019b-e003-cd2480cc8b40"}
// Comparisons work as expected
uuid == uuid.toString(); // true
uuid.valueOf() === uuid.toString(); // true
// Get buffer when needed
const buffer = uuid.toBuffer(); // <Buffer a4 54 aa 7f 80 00 01 9b e0 03 cd 24 80 cc 8b 40>The UUID class implements valueOf(), Symbol.toPrimitive, and toJSON() to ensure proper string coercion in all contexts. Use toBuffer() when you explicitly need the raw binary representation.
π UUID detail reference (Markdown version): what getInfo(), the instance and static methods, validate() and validateDetailed() return for one id of every RFC version, the Nil, Max and Microsoft ids, and each kind of CLDMV id.
The core API for the RFC-ready custom UUID specification.
Timestamp Variant v5 - Seconds precision (Subvariant 00)
Creates a UUID with a signed 70-bit timestamp in seconds from Unix epoch. Supports negative timestamps for dates before January 1, 1970. TA() mints version 5, the full layout, so ids sort by byte order across the whole range. Versions 1 (legacy layout, 1.3.1 and earlier) and 3 (ordered layout, 1.4.0 to 1.5.x) are still decoded (see Migrating stored ids to versions 5 and 6).
Parameters:
timestamp(number|bigint|string|Date, optional): Timestamp in seconds, any whole number within Β±(2^69 - 1) (see Timestamp range and inputs). Defaults toMath.floor(Date.now() / 1000)entropy(Buffer, optional): Custom entropy data (optional bits)
Returns: UUID instance
Bit Layout:
- Bits 0: Sign bit (0=negative, 1=positive)
- Bits 1-63: Magnitude bits 68..6 (full layout: most significant bit first across the whole magnitude)
- Bits 64-66: Variant =
111(custom namespace) - Bits 67-68: Subvariant =
00(Timestamp Variant) - Bits 69-74: Magnitude bits 5..0
- Bits 75-78: Version =
0101(v5 = seconds, full layout) - Bits 79-127: Entropy (49 bits)
const uuid = UUID.TA(); // Current time (seconds)
const uuid2 = UUID.TA(1766203054); // Explicit timestamp (seconds)
const uuid3 = UUID.TA(-60); // 60 seconds before epoch
// Extract timestamp
const timestamp = uuid.getTimestamp(); // Returns seconds (a bigint past Β±(2^53 - 1))
const date = new Date(Number(timestamp) * 1000); // Convert to DateTimestamp Variant v6 - Milliseconds precision (Subvariant 00)
Creates a UUID with a signed 70-bit timestamp in milliseconds from Unix epoch. Supports negative timestamps for dates before January 1, 1970. TB() mints version 6, the full layout, so ids sort by byte order across the whole range. Versions 2 (legacy layout, 1.3.1 and earlier) and 4 (ordered layout, 1.4.0 to 1.5.x) are still decoded (see Migrating stored ids to versions 5 and 6).
Parameters:
timestamp(number|bigint|string|Date, optional): Timestamp in milliseconds, any whole number within Β±(2^69 - 1) (see Timestamp range and inputs). Defaults toDate.now()entropy(Buffer, optional): Custom entropy data (optional bits)
Returns: UUID instance
Bit Layout:
- Bits 0: Sign bit (0=negative, 1=positive)
- Bits 1-63: Magnitude bits 68..6 (full layout: most significant bit first across the whole magnitude)
- Bits 64-66: Variant =
111(custom namespace) - Bits 67-68: Subvariant =
00(Timestamp Variant) - Bits 69-74: Magnitude bits 5..0
- Bits 75-78: Version =
0110(v6 = milliseconds, full layout) - Bits 79-127: Entropy (49 bits)
const uuid = UUID.TB(); // Current time (milliseconds)
const uuid2 = UUID.TB(1766203054902); // Explicit timestamp (ms)
const uuid3 = UUID.TB(-315619200000); // January 1, 1960
// Extract timestamp
const timestamp = uuid.getTimestamp(); // Returns milliseconds (a bigint past Β±(2^53 - 1))
const date = new Date(Number(timestamp)); // Convert to DateThe timestamp is a sign bit plus a 69-bit magnitude, so TA and TB hold any whole number from -(2^69 - 1) to 2^69 - 1: about Β±18.7 trillion years in seconds (TA) and Β±18.7 billion years in milliseconds (TB), before and after 1970. Every value in that range goes in and comes back out exactly.
- number: any finite number. A fractional value is floored toward -Infinity, so
UUID.TA(Date.now() / 1000)stores the second it falls in. Past 2^53 a number is taken exactly as the double it is. - bigint: exact across the whole range, e.g.
UUID.TB(2n ** 69n - 1n). - string: a decimal integer, e.g.
UUID.TB("-590295810358705651711"). This is the exact form that survives JSON, which can't carry a bigint. - Date: milliseconds for TB, floored seconds for TA. A
Dateonly spans about Β±275,760 years from 1970, so pass a number, bigint or string for times past that.
Anything the format can't hold (a magnitude past 2^69 - 1, NaN, Infinity, a malformed string, an invalid Date) throws a RangeError, and a value of another type throws a TypeError, rather than encoding a different time.
getTimestamp() returns a number while the value is a safe integer (Β±(2^53 - 1), about Β±285,000 years for TB) and an exact bigint past that; getTimestampBigInt() always returns a bigint.
Sort order: for TA and TB (versions 5 and 6), byte order (and so the string order and a database's uuid order) follows time across the whole range, -(2^69 - 1) to 2^69 - 1. Versions 3 and 4, minted by 1.4.0 to 1.5.x, keep the top 6 magnitude bits after the variant field, so their byte order follows time only from -(2^63 - 1) to 2^63 - 1 (about Β±292 billion years in seconds, Β±292 million years in milliseconds); they still decode exactly past that. UUID.compare orders any mix of versions and layouts by time.
Builds the entropy argument for UUID.TA() / UUID.TB() from an optional seed. TA() and TB() don't change; the helper only fills the bytes they read. Two calls in one module instance on the same tick (millisecond by default) never return the same bytes, with or without a seed, at any bits of 12 or more.
Parameters:
options.seed(string|Uint8Array, optional): Its SHA-1 fills the 16 seed bits, so ids made with one seed share them. Without a seed those bits are random. The empty string counts as a seed.options.precision("ms"|"s", optional): Tick length for the counter."ms"(default) matchesTB().TA()stores seconds, so use"s"with it: the default"ms"would handTA()a millisecondtimestamp, which it stores as seconds, far in the future.options.bits(number, optional): How much entropy to fill, in bits. The default, 49, is exactly whatTA()/TB()keep and gives the layout below. Any whole number of 0 or more works, limited only by memory (the array has to be allocated, so a length like2 ** 53 - 1fails); see Length below.options.onOverflow("wait"|"advance", optional): What happens when the counter runs out inside one tick."wait"spins until the clock reaches the next tick;"advance"moves to the next tick straight away, ahead of the clock. The default is"wait"for"ms"and"advance"for"s", where a wait could block for up to a second.
Returns: a 16-byte Uint8Array with bits 79-127 filled and the rest zero (with bits, the last bits bits are filled, and the array is Math.ceil(bits / 8) bytes once that is more than 16), plus a timestamp property: the tick the counter was taken on (milliseconds, or seconds with precision: "s").
Bit layout (the 49 bits TA()/TB() keep, bit 79 is the lowest bit of byte 9):
- Bits 79-90: Counter (12 bits). Starts each tick at a random value in 0-2047 and counts up to 4095, so a module instance gets at least 2048 values per tick. As the most significant field, it also makes ids from one instance in one tick sort in the order they were made.
- Bits 91-106: Seed (16 bits). The first 16 bits of SHA-1 of the seed (UTF-8 for a string, the bytes as given for a
Uint8Array), or random without a seed. - Bits 107-127: Random (21 bits), from the package's secure random source.
Length: bits changes how much is filled, not what goes in it. The same three fields, in the same order, fill the last bits bits of the array: the 12-bit counter, the 16-bit seed fingerprint, then random bits for whatever is left. A length longer than 49 gets more random bits. A short length cuts the fields where it runs out:
- 28 bits: the counter and the full seed fingerprint, no random bits.
- 12 to 27 bits: the counter and only the top bits of the fingerprint (none at 12), so different seeds can share them.
- Under 12 bits: only the counter's low bits, so values repeat inside one tick after 2^
bitscalls. At 0 the array is all zero.
TA() and TB() keep only bits 79-127, so pass them the default; other lengths are for using the entropy yourself.
Always stamp the id with the returned timestamp: UUID.TB(e.timestamp, e). The no-repeat guarantee covers the (tick, counter) pair, so it only holds when the id carries the helper's tick. Passing undefined lets TB() read the clock itself, which gives up the guarantee whenever the two differ: on counter overflow, with "advance", or after the clock steps back.
Scope of the guarantee: the counter lives in the module's own state, so it is per module instance and per worker or thread. Between instances, uniqueness rests on chance: at the default length, two with the same seed that each mint an id on the same tick collide with probability about 2^-32 for that pair (2^-11 for the same counter start, times 2^-21 for the random bits), and about 2^-48 with no seed.
Clock: the tick never moves backwards. If the clock goes back, the helper stays on the last tick it used and keeps counting, and on overflow it advances instead of waiting for the clock to catch up (also when the clock steps back during a wait). A wait also gives up after 1,000,000 readings with no change and advances the tick itself, so a frozen Date.now() (fake timers in a test suite, for example) can't hang it; the ids stay unique because they are stamped with the returned timestamp. In browsers that coarsen Date.now() (some fingerprinting protections round it to 16.7 ms or 100 ms), an "ms" wait can spin for that long; pass onOverflow: "advance" there if blocking matters.
Browser-safe: the helper uses only the package's rng and hash modules, which switch to Web Crypto and a pure-JS SHA-1 under the browser condition.
// TB, milliseconds
const e = UUID.entropy({ seed: "rummage Β· main" });
const id = UUID.TB(e.timestamp, e);
// No seed: the seed bits are random, the counter still prevents repeats
const r = UUID.entropy();
const id2 = UUID.TB(r.timestamp, r);
// TA, seconds: precision "s" (overflow advances by default), stamped with the second used
const s = UUID.entropy({ seed: "rummage Β· main", precision: "s" });
const id3 = UUID.TA(s.timestamp, s);
// 64 bits of seeded entropy for your own use: counter, seed fingerprint, 36 random bits
const k = UUID.entropy({ seed: "rummage Β· main", bits: 64 });
const key = k.subarray(8); // the last 8 bytesIssuer Variant v1 (Subvariant 01)
Creates a UUID with a 10-bit issuer identification field. The issuer ID space (0-1023) is divided into categorized allocation ranges.
Parameters:
issuerID(number): Issuer ID (0-1023, required)- 0: Unassigned/Open
- 1: Drafter Reserved
- 2-255: Category A (Well-Recognized Technology Entities)
- 256-511: Category B (Open Source Ecosystem Contributors)
- 404: Spec Originator Reserved
- 512-1023: Future RFC expansion (β₯16 ID blocks)
entropy(Buffer, optional): Custom entropy data (optional bits)
Returns: UUID instance
Bit Layout:
- Bits 0-63: Random data / application-specific
- Bits 64-66: Variant =
111(custom namespace) - Bits 67-68: Subvariant =
01(Issuer Variant) - Bits 69-74: Reserved for version-specific use
- Bits 75-78: Version =
0001(v1) - Bits 79-88: Issuer ID (10 bits)
- Bits 89-127: Entropy (39 bits)
const uuid = UUID.IA(404); // Spec Originator
const uuid2 = UUID.IA(0); // Unassigned/Open
const uuid3 = UUID.IA(100); // Category A
// Extract issuer information
const issuerID = uuid.getIssuerID(); // Returns 404
const category = uuid.getIssuerCategory(); // Returns "Spec Originator"The custom UUID methods support multiple naming styles for developer convenience:
// Ultra-short (recommended)
UUID.TA(); // Timestamp v5 (seconds)
UUID.TB(); // Timestamp v6 (milliseconds)
UUID.IA(404); // Issuer v1
// Short form with explicit version
UUID.timestamp(Math.floor(Date.now() / 1000), 3); // TA equivalent
UUID.timestamp(Date.now(), 4); // TB equivalent
UUID.issuer(404, 1); // IA equivalent
// Full method names
UUID.createTimestampVariant(Date.now(), 4);
UUID.createIssuerVariant(404, 1);Get UUID as standard hyphenated string format.
Note: UUIDs automatically convert to strings in string contexts, so explicitly calling toString() is usually not necessary.
const str = uuid.toString();
// => '9cf3cd36-8000-019b-e002-6009483ccba3'
// Automatic string conversion (no need to call toString)
console.log(uuid); // Same output
console.log(`UUID: ${uuid}`); // Same outputGet UUID as 16-byte Buffer for binary operations.
const buffer = uuid.toBuffer();
// => <Buffer 9c f3 cd 36 80 00 01 9b e0 02 60 09 48 3c cb a3>Returns the string representation of the UUID. This method enables automatic string coercion.
const value = uuid.valueOf();
// => '9cf3cd36-8000-019b-e002-6009483ccba3'
// Enables automatic coercion
String(uuid); // Same as uuid.valueOf()
uuid + ""; // Same as uuid.valueOf()Returns the string representation for JSON serialization.
const obj = { id: uuid };
JSON.stringify(obj);
// => '{"id":"9cf3cd36-8000-019b-e002-6009483ccba3"}'Describes any UUID, CLDMV or RFC, with the same fields. The UUID detail reference (Markdown) shows the full output for every kind of id. A field the id's variant doesn't define is null. fullVersion is variant.subvariant.version as numbers, with 0 for a part the id doesn't have; it identifies the kind of id and isn't meant to be compared like a semver version.
| Field | CLDMV id (variant 111) |
RFC 4122/9562 id |
|---|---|---|
uuid |
canonical string | canonical string |
isUUID |
true |
true for version 1-8, Nil and Max; NCS, Microsoft and RFC-variant ids with version 0 or 9-15 are false |
isCLDMV |
true |
false |
variant |
7 (prefix 111) |
2 (prefix 10), Nil and Max included; Microsoft 6, NCS 0. getVariant() returns the raw bits 64-66, which read 4 or 5 on an RFC id |
variantFamily |
"CLDMV" |
"RFC 4122/9562" (Nil and Max included); other ids are "NCS" or "Microsoft" |
subvariant |
bits 67-68 | null |
version |
bits 75-78 | bits 48-51, the RFC version |
fullVersion |
"7.<subvariant>.<version>": TA "7.0.5", TB "7.0.6", IA "7.1.1" |
"2.0.<version>": v4 "2.0.4", Nil "2.0.0", Max "2.0.15"; Microsoft "6.0.0", NCS "0.0.0" |
variantIdentifier |
"TA", "TB", "IA", ... |
the RFC version (Nil 0, Max 15) |
issuerID, issuerCategory |
Issuer Variant only | null |
timestamp |
TA: seconds, TB: milliseconds | v7: milliseconds, v1 and v6: 100-ns intervals, all on the Unix epoch; other versions null |
timestampUnit |
"s" or "ms" |
"ms" or "100ns" |
date |
ISO 8601 date of timestamp |
ISO 8601 date of timestamp |
isIssuerVariant, isTimestampVariant |
by subvariant | false |
UUID.TB(1700000000000).getInfo();
// { uuid: "80000006-2f3f-...", isUUID: true, isCLDMV: true, variant: 7, variantFamily: "CLDMV", subvariant: 0, version: 6, fullVersion: "7.0.6",
// variantIdentifier: "TB", issuerID: null, issuerCategory: null, timestamp: 1700000000000, timestampUnit: "ms",
// date: "2023-11-14T22:13:20.000Z", isIssuerVariant: false, isTimestampVariant: true }
new UUID("017f22e2-79b0-7cc3-98c4-dc0c0c07398f").getInfo(); // RFC v7
// { uuid: "017f22e2-...", isUUID: true, isCLDMV: false, variant: 2, variantFamily: "RFC 4122/9562", subvariant: null, version: 7, fullVersion: "2.0.7",
// variantIdentifier: 7, issuerID: null, issuerCategory: null, timestamp: 1645557742000, timestampUnit: "ms",
// date: "2022-02-22T19:22:22.000Z", isIssuerVariant: false, isTimestampVariant: false }timestamp is a number while it is a safe integer and an exact bigint past Β±(2^53 - 1). v1 and v6 timestamps are always bigints, since a count of 100-ns intervals is past 2^53.
Get variant value (bits 64-66). Returns 7 (binary 111) for custom UUIDs and 4 or 5 for RFC UUIDs. getVariant(), getSubvariant() and getVersion() read their bit positions on any id; use getInfo() for fields that depend on the variant.
const variant = uuid.getVariant(); // => 7Get subvariant value (bits 67-68).
const subvariant = uuid.getSubvariant();
// => 0 (0b00) for Timestamp Variants (TA/TB)
// => 1 (0b01) for Issuer Variants (IA)Get version value (bits 75-78).
const version = uuid.getVersion();
// => 5 for TA (1 or 3 for an older TA id), 1 for IA
// => 6 for TB (2 or 4 for an older TB id)The timestamp a UUID holds, on the Unix epoch in the id's own unit: seconds for TA, milliseconds for TB and RFC v7, 100-ns intervals for RFC v1 and v6. Returns null for ids without one (Issuer Variants, RFC v3, v4, v5 and v8). getTimestampUnit() gives the unit.
const ta = UUID.TA(1766203054); // Seconds
const timestamp = ta.getTimestamp(); // => 1766203054 (seconds)
const tb = UUID.TB(1766203054902); // Milliseconds
const timestamp2 = tb.getTimestamp(); // => 1766203054902 (milliseconds)
const ia = UUID.IA(404);
const timestamp3 = ia.getTimestamp(); // => null (Issuer Variant)
const far = UUID.TB(2n ** 60n);
const timestamp4 = far.getTimestamp(); // => 1152921504606846976n (a bigint past Β±(2^53 - 1))
new UUID("017f22e2-79b0-7cc3-98c4-dc0c0c07398f").getTimestamp(); // => 1645557742000 (RFC v7, milliseconds)
new UUID("c232ab00-9414-11ec-b3c8-9f6bdeced846").getTimestamp(); // => 16455577420000000n (RFC v1, 100-ns intervals)Returns a number while the value is a safe integer and an exact bigint past Β±(2^53 - 1) (see Timestamp range and inputs).
The timestamp as a bigint, exact across the whole range. Returns null for ids without a timestamp. Use it where code wants one type for every value.
UUID.TB(1766203054902).getTimestampBigInt(); // => 1766203054902n
UUID.TB(-(2n ** 69n - 1n)).getTimestampBigInt(); // => -590295810358705651711n
UUID.IA(404).getTimestampBigInt(); // => nullThe unit of getTimestamp(): "s" for TA, "ms" for TB and RFC v7, "100ns" for RFC v1 and v6, null for ids without a timestamp.
Get issuer ID from Issuer Variants (bits 79-88). Returns null for every other id: Timestamp Variants, reserved subvariants and RFC ids.
const ia = UUID.IA(404);
const issuerID = ia.getIssuerID(); // => 404
const ta = UUID.TA();
const issuerID2 = ta.getIssuerID(); // => null (Timestamp Variant)Get human-readable issuer category. Returns null for every id that isn't an Issuer Variant.
const ia = UUID.IA(404);
const category = ia.getIssuerCategory(); // => "Spec Originator"
const ia2 = UUID.IA(100);
const category2 = ia2.getIssuerCategory(); // => "Category A (Well-Recognized Tech Entities)"Check if the id is a well-formed UUID: an RFC 4122/9562 id with a defined version (1-8), the RFC Nil or Max id, or a CLDMV id. NCS and Microsoft ids, and RFC-variant ids with version 0 or 9-15, return false.
UUID.TA().isUUID(); // => true
new UUID(UUID.v4()).isUUID(); // => true
new UUID("00000000-0000-0000-c000-000000000046").isUUID(); // => false (Microsoft variant)Check if the id is a CLDMV id: variant bits 64-66 are 111 (TA, TB, IA or a reserved subvariant). The RFC Max id, whose bits are all ones, is an RFC id and returns false.
UUID.TA().isCLDMV(); // => true
new UUID(UUID.v4()).isCLDMV(); // => falseCheck if UUID is a Timestamp Variant (subvariant 00).
const ta = UUID.TA();
const isTimestamp = ta.isTimestampVariant(); // => true
const ia = UUID.IA(404);
const isTimestamp2 = ia.isTimestampVariant(); // => falseTrue for a Timestamp Variant in an older layout: versions 1 and 2 (legacy low-word-first, minted by 1.3.1 and earlier) and versions 3 and 4 (ordered, minted by 1.4.0 to 1.5.x). Use it to select stored ids that UUID.migrate() should rewrite.
new UUID("e7f2b400-0000-018b-e005-c289f23865d3").isLegacyTimestampLayout(); // => true (version 2)
UUID.timestamp(Date.now(), 4).isLegacyTimestampLayout(); // => true (version 4)
UUID.TB().isLegacyTimestampLayout(); // => false (version 6)
UUID.IA(404).isLegacyTimestampLayout(); // => falseCheck if UUID is an Issuer Variant (subvariant 01).
const ia = UUID.IA(404);
const isIssuer = ia.isIssuerVariant(); // => true
const ta = UUID.TA();
const isIssuer2 = ta.isIssuerVariant(); // => falseGet a human-readable identifier for the UUID variant/version. Returns a string identifier for custom variants ("TA", "TB", "IA") or the RFC version number for standard UUIDs.
const ta = UUID.TA();
ta.getVariantIdentifier(); // => "TA"
const tb = UUID.TB();
tb.getVariantIdentifier(); // => "TB"
const ia = UUID.IA(404);
ia.getVariantIdentifier(); // => "IA"
const v4 = UUID.v4();
v4.getVariantIdentifier(); // => 4
const v7 = UUID.v7();
v7.getVariantIdentifier(); // => 7Rewrites a timestamp id in an older layout (versions 1-4) into the full layout (version 5 or 6) and returns a new UUID. input is a UUID, a UUID string or a 16-byte buffer. See Migrating stored ids to versions 5 and 6.
Compares two UUIDs by time, for Array.prototype.sort. a and b are each a UUID, a UUID string or a 16-byte buffer. Returns -1, 0 or 1.
- Ids that hold a timestamp come first, ordered by that time, exactly across the whole Β±(2^69 - 1): TA and TB ids (versions 1-6) and RFC v1, v6 and v7 ids. Seconds, milliseconds and 100-ns intervals go on one scale: a TA id stands for the start of its second.
- Ids with equal times, and every other UUID (RFC v3, v4, v5 and v8, Issuer Variants, which come after all timestamp ids), are ordered by their bytes.
Byte order already follows time for TA and TB ids (versions 5 and 6). Use compare for ids byte order can't sort: a mix of versions (3/4 next to 5/6, or 1/2), TA next to TB, version 3/4 ids past Β±(2^63 - 1), or custom and RFC ids together.
const ids = [UUID.TB(2000), UUID.timestamp(1000, 4), UUID.TA(0)];
ids.sort(UUID.compare).map((id) => id.getVersion()); // => [5, 4, 6]Check a UUID against the specification. Both are async and take a UUID string, a UUID or 16 bytes.
validate() resolves to { isValid, isUUID, isCLDMV, errors, warnings, fields }. fields has the same keys for every id: the getInfo() fields (with timestamp as a bigint, without uuid) plus the raw Timestamp Variant bit fields timestampLayout ("full", "ordered" or "legacy"), timestampSign, timestampSegmentA (bits 1-63), timestampContinuation (bits 69-74) and timestampMagnitude, and isImmutableReserved for issuer IDs 0, 1 and 404. Fields that don't apply are null. Errors come from a CLDMV id that breaks the specification; warnings flag a reserved subvariant, an issuer ID in the future RFC range (512-1023) or poor entropy.
validateDetailed() adds sections.bitLayout (variant, subvariant, version, issuerID, timestampSign, timestampSegmentA, timestampContinuation, again null where they don't apply) and sections.entropy: entropyBits counts the random bits (49 for TA/TB, 109 for IA, 122 for RFC v4, 74 for RFC v7, null where there is no random field) and analysis.bitBalance is the share of them set to 1.
const { isValid, fields } = await UUID.validate("8000018b-cfe5-6800-e009-c289f23865d3");
// isValid: true, fields.variantIdentifier: "TB", fields.timestamp: 1700000000000n, fields.timestampLayout: "ordered"Detect the variant identifier from any UUID (string, buffer, or UUID instance). Returns a string identifier for custom variants or version number for RFC variants.
// Custom variants return string identifiers
UUID.detectVariant("a454aa7f-8000-019b-e003-cd2480cc8b40"); // => "TA"
UUID.detectVariant(taUuid.toBuffer()); // => "TA"
// RFC variants return version numbers
UUID.detectVariant("6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b"); // => 4
UUID.detectVariant("018da58e-42e0-7b67-9f36-8e7e5f5b9c38"); // => 7
// Works with UUID instances
UUID.detectVariant(UUID.IA(404)); // => "IA"Parameters:
uuid(string|Uint8Array|UUID): UUID to detect variant from
Returns: String identifier ("TA", "TB", "IA", etc.) or version number (1-8) for RFC UUIDs
Complete implementation of RFC 4122/9562 standard UUID versions (bonus feature).
Generate a version 1 (timestamp) UUID.
const uuid = UUID.v1();
const customUuid = UUID.v1({
msecs: Date.now(),
nsecs: 0,
clockseq: 0x1234,
node: [0x01, 0x02, 0x03, 0x04, 0x05, 0x06]
});Generate a version 3 (namespace with MD5) UUID.
const uuid = UUID.v3("hello.example.com", UUID.DNS);Generate a version 4 (random) UUID.
const uuid = UUID.v4();
const customUuid = UUID.v4({ random: customRandomBytes });Generate a version 5 (namespace with SHA-1) UUID.
const uuid = UUID.v5("hello.example.com", UUID.DNS);Generate a version 6 (reordered timestamp) UUID.
const uuid = UUID.v6();
const customUuid = UUID.v6({ msecs: Date.now() });Generate a version 7 (Unix Epoch time-based) UUID. Sortable and monotonic.
const uuid = UUID.v7();
const customUuid = UUID.v7({ msecs: Date.now() });Generate a version 8 (custom/experimental) UUID. Version 8 provides an RFC-compatible format for experimental or vendor-specific UUID formats. The only requirement is that variant and version bits are set correctly; all other bits can be filled with custom data.
const uuid = UUID.v8(); // Random data
const customUuid = UUID.v8({
data: new Uint8Array(16) // Your custom 16 bytes
});Parameters:
options.data(Uint8Array, optional): Custom 16-byte data to use. If not provided, uses cryptographically random bytes.options.buf(Uint8Array, optional): Buffer to write UUID into.options.offset(number, optional): Offset in buffer to start writing.
Returns: UUID string or buffer (if options.buf provided)
Convert UUID string to byte array.
const bytes = UUID.parse("6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b");
// => Uint8Array(16) [110, 192, 189, 127, ...]Convert byte array to UUID string.
const uuid = UUID.stringify(bytes);
// => '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b'Validate RFC UUID string format.
const isValid = UUID.validateRFC("6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b");
// => trueDetect RFC version of a UUID.
const version = UUID.version("6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b");
// => 4UUID.NIL; // '00000000-0000-0000-0000-000000000000'
UUID.MAX; // 'ffffffff-ffff-ffff-ffff-ffffffffffff'
// Standard namespaces for v3/v5
UUID.DNS; // DNS namespace
UUID.URL; // URL namespace
UUID.OID; // ISO OID namespace
UUID.X500; // X.500 DN namespaceEntropySource is a set of static helpers for sizing and checking the randomness behind ids. It lives on its own subpath, so importing the package root does not load it. It works on Uint8Array (Node Buffers work as inputs) and runs in browsers: bytes come from @cldmv/uuid/rng and SHA-256 from @cldmv/uuid/hash, both of which have browser variants.
import { EntropySource } from "@cldmv/uuid/entropy";
// Random bits needed for a one-in-a-billion collision chance across a million ids (birthday bound)
EntropySource.calculateRequiredEntropy(1e-9, 1_000_000); // => 69
const bytes = EntropySource.generateSecureBytes(16); // Uint8Array(16) from the platform CSPRNG
EntropySource.generateEntropy(130); // 17 bytes: bits rounded up to whole bytes
// Sanity-check a byte source
const report = EntropySource.validateEntropyQuality(bytes);
report.passed; // true for a healthy source
report.tests.bitBalance; // { passed, value, min, max, description }| Method | Returns |
|---|---|
generateSecureBytes(byteCount) |
byteCount random bytes |
generateEntropy(bits) |
Random bytes, bits rounded up to whole bytes |
calculateRequiredEntropy(probability, count) |
Random bits needed to keep the collision chance across count ids at or below probability |
validateEntropyQuality(bytes) |
A report with four checks: not all zeros, not all ones, set-bit share within 4 standard deviations of 50% (the window narrows as the input grows), no long run of one bit value |
generateValidatedEntropy(byteCount, [maxAttempts=10]) |
Random bytes that pass validateEntropyQuality, retrying up to maxAttempts times |
mixEntropySources(sources) |
The XOR of the byte arrays, as long as the longest (shorter ones padded with zeros) |
createTimestampIndependentEntropy(timestamp, [additionalBytes=16]) |
SHA-256 of the timestamp plus additionalBytes fresh random bytes (32 bytes) |
estimateShannonEntropy(bytes) |
Estimated bits of information from byte-value frequencies |
analyzeEntropySource(generator, [sampleCount=100]) |
Repeated-output and timing warnings for a generator function |
validateEntropyQuality catches a broken or stuck source; it doesn't prove randomness. A fair source fails it about once in 16,000 checks at any length.
The custom UUID specification uses variant 111 (bits 64-66) as the entry point into the extended namespace, maintaining full compatibility with RFC 4122/9562:
Bit Layout (128 bits total):
βββββββββββββββ¬βββββββββββ¬ββββββββββββ¬βββββββββββ¬ββββββββββ¬ββββββββββββββ¬βββββββββββ
β 0-63 β 64-66 β 67-68 β 69-74 β 75-78 β 79-88 β 89-127 β
βββββββββββββββΌβββββββββββΌββββββββββββΌβββββββββββΌββββββββββΌββββββββββββββΌβββββββββββ€
β Time/Data β Variant β Subvariantβ Reserved β Version β Issuer ID β Entropy β
β β (111) β (00/01) β β β (Issuer V.) β β
βββββββββββββββ΄βββββββββββ΄ββββββββββββ΄βββββββββββ΄ββββββββββ΄ββββββββββββββ΄βββββββββββ
Timestamp Variant (Subvariant 00):
- Bits 0: Sign bit (0=negative, 1=positive)
- Bits 1-63: Timestamp magnitude. Versions 5 and 6: bits 68..6, most significant bit first. Versions 3 and 4: bits 62..0, most significant bit first. Versions 1 and 2: low 32 bits at bits 1-32, magnitude bits 62..32 at bits 33-63
- Bits 64-66: Variant = 111
- Bits 67-68: Subvariant = 00
- Bits 69-74: Timestamp magnitude. Versions 5 and 6: bits 5..0. Versions 1-4: bits 68..63
- Bits 75-78: Version (1, 3 and 5 = seconds; 2, 4 and 6 = milliseconds)
- Bits 79-127: Entropy (49 bits)
Issuer Variant (Subvariant 01):
- Bits 0-63: Random/application data
- Bits 64-66: Variant = 111
- Bits 67-68: Subvariant = 01
- Bits 69-74: Reserved (version-specific)
- Bits 75-78: Version
- Bits 79-88: Issuer ID (10 bits, 0-1023)
- Bits 89-127: Entropy (39 bits)
- 00 (Timestamp Variant): Time-based identification with signed 70-bit timestamps
- 01 (Issuer Variant): Organization/entity-based identification with 10-bit issuer space
- 10 (Reserved): Future specification expansion
- 11 (Reserved): Future specification expansion
The 10-bit issuer ID space (0-1023) is formally divided into categories:
| Range | Category | Description | Status |
|---|---|---|---|
| 0 | Unassigned/Open | Available for open/unregistered use | Immutable |
| 1 | Drafter Reserved | Reserved for specification drafter | Immutable |
| 2-255 | Category A | Well-Recognized Technology Entities | Assignable |
| 256-511 | Category B | Open Source Ecosystem Contributors | Assignable |
| 404 | Spec Originator | Reserved for specification originator | Immutable |
| 512-1023 | Future RFC | Reserved for future RFC expansion (β₯16 ID blocks) | Reserved |
Immutable Allocations: IDs 0, 1, and 404 are permanently reserved and cannot be reassigned.
The timestamp variants use a signed 70-bit representation that maintains lexicographic sort order:
Positive Timestamps (after Unix epoch):
- Sign bit (bit 0) = 1
- Magnitude stored directly in bits 1-69
Negative Timestamps (before Unix epoch):
- Sign bit (bit 0) = 0
- Stored value =
(2^69 - 1) - abs(magnitude) - This ordering rule ensures negative timestamps sort correctly
Example:
// January 1, 1960 (10 years before epoch)
const timestamp = -315619200000; // milliseconds
const uuid = UUID.TB(timestamp);
// The negative value is encoded to preserve sort order:
// - Sign bit = 0 (negative)
// - Stored = (2^69 - 1) - 315619200000
// - Extraction reverses: -(2^69 - stored)
const extracted = uuid.getTimestamp();
console.log(extracted === timestamp); // trueTimestamp Variants (49 bits entropy):
- Birthday bound: 99.99% no collision probability at ~16.7M UUIDs
- Per-second generation capacity: Safe up to millions of UUIDs/second
- Cryptographically secure entropy source (Node.js crypto.randomBytes)
Issuer Variants (39 bits entropy):
- Birthday bound: 99.99% no collision probability at ~522K UUIDs
- Combined with issuer ID: Effective namespace isolation per issuer
- Suitable for distributed generation with known issuer assignment
Version field (bits 75-78) is always positioned consistently across all subvariants:
Timestamp Variant Versions:
- v1 (0001): Seconds precision, legacy low-word-first layout. Written by 1.3.1 and earlier, still decoded
- v2 (0010): Milliseconds precision, legacy low-word-first layout. Written by 1.3.1 and earlier, still decoded
- v3 (0011): Seconds precision, ordered layout. Written by 1.4.0 to 1.5.x, still decoded
- v4 (0100): Milliseconds precision, ordered layout. Written by 1.4.0 to 1.5.x, still decoded
- v5 (0101): Seconds precision, full layout (magnitude most significant bit first). Minted by
UUID.TA() - v6 (0110): Milliseconds precision, full layout (magnitude most significant bit first). Minted by
UUID.TB() - v7+: Reserved for future timestamp variants
Versions 5 and 6 write magnitude bits 68..6 at bits 1-63 and bits 5..0 at bits 69-74, so the byte order of the UUID, a hex string and a database uuid column follow the timestamp across the whole Β±(2^69 - 1). Versions 3 and 4 write bits 62..32 at bits 1-31, bits 31..0 at bits 32-63 and bits 68..63 at bits 69-74, which sorts within Β±(2^63 - 1). Versions 1 and 2 write the low 32 bits at bits 1-32 and the upper 31 at bits 33-63, which only sorts inside one 2^32 window (49.7 days for milliseconds, 136 years for seconds). getTimestamp() and the validators pick the layout from the version, so ids minted by earlier releases decode exactly as before.
Issuer Variant Versions:
- v1 (0001): Basic issuer identification
- v2+: Reserved for future issuer-based variants
UUID.TA() and UUID.TB() mint versions 5 and 6 since 2.0.0. Ids you already stored carry versions 1 and 2 (1.3.1 and earlier) or 3 and 4 (1.4.0 to 1.5.x) and keep working: they decode to the same timestamp. To bring them to the full layout, run UUID.migrate() on each stored id.
import { UUID } from "@cldmv/uuid";
const legacy = "e7f2b400-0000-018b-e005-c289f23865d3"; // version 2, minted by 1.3.1
const uuid = new UUID(legacy);
uuid.isLegacyTimestampLayout(); // => true, select these rows
const migrated = UUID.migrate(legacy); // a new UUID, version 6
migrated.toString(); // => "80000006-2f3f-95a0-e00d-c289f23865d3"
migrated.getTimestamp(); // => 1700000000000 (same as before)
UUID.migrate("8000018b-cfe5-6800-e009-c289f23865d3").toString(); // version 4 -> the same version 6 idWhat migrate does:
- Versions 1 and 3 become 5, versions 2 and 4 become 6. The sign, the timestamp value and the 49 entropy bits (bits 79-127) are copied unchanged; the timestamp bits are rewritten in the full layout, including bits 69-74.
- The mapping is deterministic: the same old id always produces the same new id, and a version 2 id and its version 4 migration both end up at the same version 6 id. Foreign keys and references can be rewritten consistently by migrating every column that holds the id.
- It is idempotent. An id already at version 5 or 6, and any non-timestamp UUID (RFC UUIDs, issuer variants), comes back as an equal copy.
- It accepts a
UUID, a string or a 16-byte buffer, and throws only on input that cannot be parsed.
Per row: read the stored id, call UUID.migrate(id) (or check new UUID(id).isLegacyTimestampLayout() first to find the rows that need it), and write back migrated.toString() or migrated.toBuffer().
Until every row is migrated, old and new ids don't sort together by byte order: each layout sorts by time among its own ids, but a version 3/4 id sorts after a version 5/6 id of the same time. Sort with UUID.compare in the meantime, or migrate first.
import { UUID } from "@cldmv/uuid";
// Current time (TA uses seconds, TB uses milliseconds)
const ta = UUID.TA(); // Defaults to Math.floor(Date.now() / 1000)
const tb = UUID.TB(); // Defaults to Date.now()
console.log("TA UUID:", ta.toString());
console.log("TB UUID:", tb.toString());
// Extract and display timestamps
const taTime = ta.getTimestamp(); // Returns seconds
const tbTime = tb.getTimestamp(); // Returns milliseconds
console.log("TA Timestamp (s):", taTime);
console.log("TA Date:", new Date(taTime * 1000).toISOString());
console.log("TB Timestamp (ms):", tbTime);
console.log("TB Date:", new Date(tbTime).toISOString());
// Historical dates (negative timestamps)
const historical = UUID.TB(-315619200000); // January 1, 1960
console.log("Historical UUID:", historical.toString());
console.log("Date:", new Date(historical.getTimestamp()).toUTCString());
// => Fri, 01 Jan 1960 00:00:00 GMTimport { UUID } from "@cldmv/uuid";
// Generate UUIDs with different issuer categories
const specOriginator = UUID.IA(404);
const openUse = UUID.IA(0);
const techEntity = UUID.IA(100); // Category A
const ossProject = UUID.IA(300); // Category B
// Extract issuer information
console.log("Spec Originator:");
console.log(" ID:", specOriginator.getIssuerID()); // => 404
console.log(" Category:", specOriginator.getIssuerCategory());
// => "Spec Originator"
console.log("\nTechnology Entity:");
console.log(" ID:", techEntity.getIssuerID()); // => 100
console.log(" Category:", techEntity.getIssuerCategory());
// => "Category A: Well-Recognized Technology Entities"
// Validate variant structure
const info = specOriginator.getInfo();
console.log("\nFull Specification Data:");
console.log(" Variant (bits 64-66):", info.variant); // => 7 (111)
console.log(" Subvariant (bits 67-68):", info.subvariant); // => 1 (01)
console.log(" Version (bits 75-78):", info.version); // => 1
console.log(" Issuer ID (bits 79-88):", info.issuerID); // => 404import { UUID } from "@cldmv/uuid";
const ta = UUID.TA();
const ia = UUID.IA(404);
console.log("TA Info:");
console.log(" Variant:", ta.getVariant()); // => 7 (111)
console.log(" Subvariant:", ta.getSubvariant()); // => 0 (00)
console.log(" Version:", ta.getVersion()); // => 1
console.log(" Is Timestamp Variant:", ta.isTimestampVariant()); // => true
console.log(" Is Issuer Variant:", ta.isIssuerVariant()); // => false
console.log(" Timestamp:", ta.getTimestamp()); // => number (seconds)
console.log(" Issuer ID:", ta.getIssuerID()); // => null
console.log("\nIA Info:");
console.log(" Variant:", ia.getVariant()); // => 7 (111)
console.log(" Subvariant:", ia.getSubvariant()); // => 1 (01)
console.log(" Version:", ia.getVersion()); // => 1
console.log(" Is Timestamp Variant:", ia.isTimestampVariant()); // => false
console.log(" Is Issuer Variant:", ia.isIssuerVariant()); // => true
console.log(" Timestamp:", ia.getTimestamp()); // => null
console.log(" Issuer ID:", ia.getIssuerID()); // => 404
// Both TA and TB share subvariant 00 (differ only in version)
const tb = UUID.TB();
console.log("\nSubvariant Relationships:");
console.log(" TA subvariant:", ta.getSubvariant()); // => 0
console.log(" TB subvariant:", tb.getSubvariant()); // => 0
console.log(" IA subvariant:", ia.getSubvariant()); // => 1
console.log(" TA version:", ta.getVersion()); // => 3 (seconds)
console.log(" TB version:", tb.getVersion()); // => 4 (milliseconds)import { UUID } from "@cldmv/uuid";
// RFC standard versions (bonus feature)
const uuids = {
v1: UUID.v1(),
v3: UUID.v3("example.com", UUID.DNS),
v4: UUID.v4(),
v5: UUID.v5("example.com", UUID.DNS),
v6: UUID.v6(),
v7: UUID.v7()
};
console.log("Generated RFC UUIDs:", uuids);
// Deterministic UUID generation
const uuid1 = UUID.v5("hello", UUID.DNS);
const uuid2 = UUID.v5("hello", UUID.DNS);
console.log(uuid1 === uuid2); // true
// Sortable UUIDs with v7
const sortable = [UUID.v7({ msecs: Date.now() }), UUID.v7({ msecs: Date.now() + 1000 }), UUID.v7({ msecs: Date.now() + 2000 })];
console.log("Chronological order:", sortable.sort());
// Validation and parsing
const v4 = UUID.v4();
if (UUID.validateRFC(v4)) {
const bytes = UUID.parse(v4);
const version = UUID.version(v4);
console.log("Valid UUID v" + version);
}The library is optimized for high-performance UUID generation with collision resistance:
- Custom UUID Generation: ~90,000+ UUIDs/second
- RFC v4 Generation: ~90,000+ UUIDs/second
- RFC v7 Generation: ~95,000+ UUIDs/second
- Zero Collisions: Tested with 100,000+ UUID generation runs
- Efficient Bit Operations: Direct bit manipulation without string conversions
- Cryptographically Secure: Uses Node.js crypto.randomBytes() for entropy
- Proper Entropy Validation: All generated UUIDs validated for entropy quality
See the custom UUID specification in action with a comprehensive human-readable demonstration:
npm run demoThis interactive demonstration script showcases the RFC-ready specification:
- TA (Timestamp v5): Generates UUID with seconds precision, extracts timestamp
- TB (Timestamp v6): Generates UUID with milliseconds precision, extracts timestamp
- IA (Issuer v1): Generates UUID with issuer ID 404, shows issuer category
- Bit Field Verification: Displays all specification fields (variant, subvariant, version, issuer ID)
- Negative Timestamps: Demonstrates pre-epoch date support with proper encoding
- Subvariant Relationships: Confirms TA/TB share subvariant 00, IA uses 01
- Uniqueness Testing: Generates 10,000 of each variant, verifies no collisions
- Roundtrip Validation: Tests string/buffer conversion preserves all data
Example output excerpt:
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
UUID.TA() - Timestamp Variant (Seconds Precision)
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Generated UUID:
b4a30f57-0000-0000-e003-b9b0f01b1d06
Extracted Data:
β Variant (bits 64-66) : 7 (expected: 7)
β Subvariant (bits 67-68) : 0 (expected: 0)
β Version (bits 75-78) : 1 (expected: 1)
β Is Timestamp Variant : true (expected: true)
Timestamp Information:
β Extracted Timestamp (s) : 1766203054 (expected: 1766203054)
Human Readable : Friday, December 19, 2025 at 07:57:34 PM PST
ISO 8601 : 2025-12-20T03:57:34.000Z
The code lives in src/. npm run build (scripts/build.mjs) minifies each file in src/ on its own into the same path under dist/, with nothing bundled, and that is what the package publishes (dist/ is gitignored and rebuilt by prepack):
src/index.mjsβdist/index.mjs: the ESM entry.src/index.cjsβdist/index.cjs: the CommonJS entry, copied verbatim. Itrequire()s the siblingindex.mjs.src/lib/{rng,bytes,hash}{,-browser}.mjsβdist/lib/: the./rng,./bytesand./hashsubpaths.src/lib/entropy-sources.mjsβdist/lib/entropy-sources.mjs: the./entropysubpath, one file for Node and browsers.
npm run types:build regenerates the declarations in types/src/.
In a checkout, the package resolves to dist/ by default. The uuid-dev export condition switches it to src/, so you can run the source without building:
node --conditions=uuid-dev app.mjs
# or once per shell
export NODE_OPTIONS=--conditions=uuid-devThe test suites run against src/ through this condition.
npm test # Run all tests (Vitest suites on src/, the entry tests, the suites on dist/, then the type tests)
npm run test:watch # Watch mode
npm run test:cjs # Build, then check the dist/ and src/ entries (Node's built-in test runner)
npm run test:dist # Build, then run the Vitest suites against dist/ instead of src/
npm run test:types # Build, then type-check a packed consumer project
npm run coverage # With coverage- 170+ comprehensive tests covering the complete specification
- Custom UUID Specification Tests:
- Bit layout validation (variant, subvariant, version positioning)
- Timestamp extraction and roundtrip (positive and negative)
- Issuer ID extraction and category mapping
- Subvariant relationships (TA/TB share 00, IA uses 01)
- Negative timestamp encoding and ordering
- RFC UUID Compliance Tests (v1, v3, v4, v5, v6, v7)
- Collision Resistance Tests (100K+ UUID generation)
- Integration Tests (entropy validation, format conversion)
- Bit Manipulation Tests (low-level operations)
All tests pass with 100% specification compliance.
Full TypeScript definitions included for both custom and RFC UUID APIs:
import { UUID } from "@cldmv/uuid";
// Custom UUID specification (RFC-ready)
const ta: string = UUID.TA().toString();
const tb: string = UUID.TB().toString();
const ia: string = UUID.IA(404).toString();
// Instance methods with proper types
const uuid = new UUID(ta);
const variant: number = uuid.getVariant(); // 7
const subvariant: number = uuid.getSubvariant(); // 0 or 1
const version: number = uuid.getVersion();
const timestamp: number | bigint | null = uuid.getTimestamp(); // bigint past Β±(2^53 - 1), null for Issuer Variant
const exact: bigint | null = uuid.getTimestampBigInt();
const sorted: string[] = [ta, tb].sort(UUID.compare);
const issuerID: number | null = uuid.getIssuerID(); // null for Timestamp Variant
const category: string | null = uuid.getIssuerCategory();
// Standard RFC UUIDs
const v4: string = UUID.v4();
const bytes: Uint8Array = UUID.parse(v4);
const rfcVersion: string | number | null = UUID.version(v4); // 4 here; "TA" / "TB" / "IA" for the custom variantsThe complete formal specification is available in uuid-spec.md, including:
- Detailed bit layout diagrams
- Entropy requirement calculations (Birthday Bound analysis)
- Negative timestamp encoding algorithms
- Issuer ID allocation policies
- Version numbering conventions
- Collision resistance proofs
- RFC submission rationale
- UUID detail reference: every detail method's output for each kind of id, generated from the library (
npm run docs:build) and published with each release - UUID detail reference, Markdown: the same reference as a page in the repository (
npm run docs:details)
- Changelog: per-version release notes for every release since v1.0.0
- RFC 4122 - Original UUID specification
- RFC 9562 - Updated UUID specification with v6, v7, v8
- uuid - Standard RFC 4122 UUID implementation (Node.js)
- ulid - Universally Unique Lexicographically Sortable Identifier
This specification extends the RFC namespace with custom variant 111, maintaining full compatibility with existing RFC 4122/9562 UUIDs.
Contributions to the specification and implementation are welcome! This project aims for RFC standardization, so contributions should maintain:
- Specification Compliance: All changes must align with the formal specification
- Backward Compatibility: Immutable fields (variant, subvariant positions) cannot change
- Comprehensive Testing: New features require corresponding test coverage
- Documentation: Changes to the specification must update uuid-spec.md
- npm: @cldmv/uuid
- GitHub: CLDMV/uuid
- Issues: GitHub Issues
- Specification: uuid-spec.md
- Changelog: docs/changelog/
- Sponsor: GitHub Sponsors
Apache-2.0 Β© Shinrai / CLDMV. See LICENSE for the full text.
This specification and implementation are provided for RFC standardization consideration.
Specification Status: Implementation complete, designed for RFC submission.
Made with β€οΈ by CLDMV