uuidv7

repository·main·Indexed 42 days ago

https://github.com/liosk/uuidv7

A high-performance JavaScript implementation of UUID version 7 (RFC 9562) providing monotonically increasing, time-ordered identifiers. Version 1.2.1 supports Node.js, browsers, and Deno, featuring the V7Generator class for clock rollback handling, a UUID class for manipulation and comparison, and support for UUIDv4 generation.

Tokens
2.9K
Snippets
11
Records
12
Agent score
53%

What's inside uuidv7

  1. Understand the UUIDv7 bit layout and monotonicity

    main

    The UUIDv7 implementation follows RFC 9562 with a specific bit layout designed for time-based sorting:

    • unix_ts_ms (48 bits): Unix timestamp in milliseconds.
    • ver (4 bits): Set to 0111 (version 7).
    • counter (42 bits): Ensures increasing order within the same millisecond. If the counter overflows, the library increments the unix_ts_ms field to maintain monotonicity.
    • var (2 bits): Set to 10.
    • rand (32 bits): Cryptographically strong random bits.

    Monotonicity and Clock Rollbacks

    UUIDv7 relies on the system clock. If the clock rolls back slightly, the library reuses the previous unix_ts_ms to maintain order. However, if the rollback is significant (default > 10 seconds), the generator resets, which may break the increasing order. Use V7Generator.generateOrAbort() to detect these events.

  2. Install and use uuidv7

    main

    You can use uuidv7 in Node.js, browsers, or Deno to generate version 7 UUIDs.

    Node.js / NPM

    Install via npm and import the uuidv7 function.

    Browsers and Deno

    Import directly from unpkg.

    CLI

    You can generate UUIDs directly from your terminal using npx.

    Use the -n flag to specify the number of UUIDs to generate.

    // Node.js
    import { uuidv7 } from "uuidv7";
    const result = uuidv7();
    
    // Browsers/Deno
    import { uuidv7 } from "https://unpkg.com/uuidv7@^1";
    const result = uuidv7();
    
    // CLI
    $ npx uuidv7
    $ npx uuidv7 -n 4
  3. Convert UUIDs to Uuid25 format

    main

    For a condensed, sortable, case-insensitive, 25-digit Base36 representation, you can use the uuid25 project in conjunction with uuidv7obj.

    Example workflow:

    1. Generate a uuidv7obj.
    2. Pass its bytes to Uuid25.fromBytes().
    3. Use methods like .toHyphenated(), .toUrn(), or .toBraced() to format the output.
    import { uuidv7obj } from "uuidv7";
    import { Uuid25 } from "uuid25";
    
    const uuid25 = Uuid25.fromBytes(uuidv7obj().bytes);
    
    console.log(uuid25.value);          // e.g., "03a2s63x4x0b9mev9e88i7gpm"
    console.log(uuid25.toHex());        // e.g., "0189f8068f1a79b6bb21123c6accc25a"
    console.log(uuid25.toHyphenated()); // e.g., "0189f806-8f1a-79b6-bb21-123c6accc25a"
    console.log(uuid25.toBraced());      // e.g., "{0189f806-8f1a-79b6-bb21-123c6accc25a}"
    console.log(uuid25.toUrn());        // e.g., "urn:uuid:0189f806-8f1a-79b6-bb21-123c6accc25a"
  4. Use V7Generator for custom state and monotonic guarantees

    main

    The V7Generator class allows you to maintain a separate counter state from the global generator. It is useful for managing independent sequences or handling system clock rollbacks.

    It provides two generation methods:

    1. generate(): Standard generation.
    2. generateOrAbort(): A fallible method that returns undefined if a significant clock rollback (default > 10 seconds) occurs, allowing you to handle potential breaks in monotonicity explicitly.
    import { V7Generator } from "uuidv7";
    
    const g = new V7Generator();
    const x = g.generate();
    const y = g.generateOrAbort();
    
    if (y === undefined) {
      throw new Error("The clock went backwards by ten seconds!");
    }
  5. Generate UUIDv4 and UUID objects

    main

    In addition to version 7, this library supports version 4 UUID generation and provides object-oriented representations of UUIDs.

    • uuidv4(): Returns a version 4 UUID string.
    • uuidv7obj(): Returns a UUID object representing the ID as a 16-byte array. This object provides methods for comparison, cloning, and inspecting the version/variant.
    • uuidv4obj(): Returns a version 4 UUID object.
    import { uuidv7, uuidv4, uuidv7obj } from "uuidv7";
    
    // String outputs
    const v7 = uuidv7(); // "017fe537-bb13-7c35-b52a-cb5490cce7be"
    const v4 = uuidv4(); // "83229083-75c3-4da5-8378-f88ef1a2bcd1"
    
    // Object output
    const object = uuidv7obj();
    console.log(object.bytes); // Uint8Array(16)
    console.log(String(object)); // "017fea6b-b877-7aef-b422-57db9ed15e9d"
    
    // Object methods
    object.getVariant(); // "VAR_10"
    object.getVersion(); // 7
    object.clone();
    object.compareTo(otherObject);
  6. Manage monotonic UUID generation with V7Generator

    main

    The V7Generator class provides fine-grained control over the generation of UUIDv7, specifically to ensure monotonicity (increasing order) even during clock rollbacks.

    Monotonicity and Rollbacks

    UUIDv7 is time-ordered. If the system clock moves backward, the generator can handle this in two ways:

    1. generate(): Reuses the previous timestamp for a period defined by rollbackAllowance (default 10,000ms) to maintain order. If the rollback is larger than the allowance, it resets the generator and breaks monotonicity.
    2. generateOrAbort(): Returns undefined if a significant clock rollback occurs, preventing the generation of non-monotonic IDs.

    Customization

    • setRollbackAllowance(number): Configures how much clock rollback is tolerated before resetting.
    • Custom RNG: You can pass a custom random number generator in the constructor that implements nextUint32(): number.
    import { V7Generator } from 'uuidv7';
    
    const generator = new V7Generator();
    
    // Configure tolerance for clock drift
    generator.setRollbackAllowance(5000); // 5 seconds
    
    // Generate monotonically
    const id1 = generator.generate();
    const id2 = generator.generate();
    
    // Safe generation that returns undefined on large rollbacks
    const safeId = generator.generateOrAbort();
    if (safeId) {
      console.log(safeId.toString());
    }
  7. Generate UUIDv7 strings and objects

    main

    Use the top-level functions uuidv7() and uuidv7obj() to generate UUID version 7 identifiers.

    • uuidv7(): Returns the canonical 8-4-4-4-12 hyphenated hexadecimal string.
    • uuidv7obj(): Returns a UUID object instance, which allows for more advanced operations like comparison or parsing.

    Note: These functions use a shared global V7Generator instance by default.

    import { uuidv7, uuidv7obj } from 'uuidv7';
    
    // Get a string representation
    const idString = uuidv7(); // "xxxxxxxx-xxxx-7xxx-yxxx-xxxxxxxxxxxx"
    
    // Get a UUID object for advanced usage
    const idObj = uuidv7obj();
    console.log(idObj.toString());
  8. Use the UUID class for manipulation and comparison

    main

    The UUID class represents a 128-bit UUID. It provides methods for parsing, formatting, and comparing UUIDs.

    Key Methods:

    • UUID.parse(uuid: string): Creates a UUID object from various string formats (32-digit hex, hyphenated, braced, or URN).
    • toString(): Returns the canonical 8-4-4-4-12 hyphenated string.
    • toHex(): Returns the 32-digit hexadecimal string without hyphens.
    • equals(other: UUID): Checks if two UUID objects are identical.
    • compareTo(other: UUID): Returns a negative integer, zero, or positive integer if this UUID is less than, equal to, or greater than the other.
    • isNil() / isMax(): Checks if the UUID is the Nil or Max UUID.
    • getVariant(): Returns the variant field value (e.g., VAR_10, NIL, MAX).
    • getVersion(): Returns the version number (e.g., 7).
    import { UUID } from 'uuidv7';
    
    // Parsing a string
    const uuid = UUID.parse('0189dcd5-5311-7d40-8db0-9496a2eef37b');
    
    // Comparison
    if (uuid.compareTo(anotherUuid) > 0) {
      console.log('uuid is greater than anotherUuid');
    }
    
    // Formatting
    console.log(uuid.toString()); // "0189dcd5-5311-7d40-8db0-9496a2eef37b"
    console.log(uuid.toHex());    // "0189dcd553117d408db09496a2eef37b"
  9. Generate UUIDv4

    main

    The library also provides support for generating standard UUID version 4 (random) identifiers.

    • uuidv4(): Returns a UUIDv4 string.
    • uuidv4obj(): Returns a UUID object instance representing a UUIDv4.
    import { uuidv4, uuidv4obj } from 'uuidv7';
    
    const v4String = uuidv4();
    const v4Obj = uuidv4obj();
  10. Create UUIDs from raw fields

    main

    If you need to construct a UUID from specific components, use UUID.fromFieldsV7. This is useful for reconstructing UUIDs from database fields or custom protocols.

    Parameters:

    • unixTsMs: 48-bit Unix timestamp in milliseconds.
    • randA: 12-bit random value.
    • randBHi: Higher 30 bits of the 62-bit random value.
    • randBLo: Lower 32 bits of the 62-bit random value.

    Note: This method throws a RangeError if any value is outside its allowed bit-range.

    import { UUID } from 'uuidv7';
    
    const uuid = UUID.fromFieldsV7(
      Date.now(), // unixTsMs
      0xfff,      // randA
      0x3fffffff, // randBHi
      0xffffffff  // randBLo
    );
  11. Reference the uuidv7 CLI flags

    main

    The following flags are available when using the uuidv7 command line interface:

    -n, --count <value>
        Specify the number of UUIDv7 strings to generate. Must be a positive integer.
    -h, --help
        Display usage information and exit.
  12. Use the uuidv7 CLI to generate UUIDv7 strings

    main

    The uuidv7 CLI tool allows you to generate one or more UUIDv7 strings directly in your terminal. By default, it generates a single UUIDv7 string and outputs it to stdout.

    # Generate a single UUIDv7
    $ uuidv7
    
    # Generate 5 UUIDv7 strings
    $ uuidv7 -n 5