MCPcopy Index your code
hub / github.com/aarondcohen/id128

github.com/aarondcohen/id128 @v1.6.3

Chat with this repo
repository ↗ · DeepWiki ↗ · release v1.6.3 ↗ · + Follow
343 symbols 870 edges 48 files 0 documented · 0% updated 23mo ago★ 3441 open issues
What it actually does AI analysis from the code graph — generated when you open this
loading…
README

Id128

Generate 128-bit unique identifiers for various specifications. In particular: - ULID - Monotonic ULID - UUID 1 (Variant 1 Version 1) - UUID 4 (Variant 1 Version 4) - UUID 6 (Variant 1 Version 6) - Nil UUID (Variant 0 Version 0) - Uuid (Unknown Variant and Version)

Common Usage

const {
    Ulid,
    UlidMonotonic,
    Uuid,
    Uuid1,
    Uuid4,
    Uuid6,
    UuidNil,
    idCompare,
    idEqual,
} = require('id128');

// Id factories
[
    Ulid,
    UlidMonotonic,
    Uuid1,
    Uuid4,
    Uuid6,
    UuidNil,
].forEach((IdType) => {
    // Identify the factory
    console.log(IdType.name);

    // Generate a new id
    const id = IdType.generate();

    // Get the smallest valid id
    const min = IdType.MIN();

    // Get the largest valid id
    const max = IdType.MAX();

    // Type-check the id
    console.log(id instanceof IdType.type)

    // Compare ids
    console.log(id.equal(id));
    console.log(! id.equal(min));
    console.log(! id.equal(max));
    console.log(id.compare(min) === 1);
    console.log(id.compare(id) === 0);
    console.log(id.compare(max) === -1);

    // Encode the id in its canonical form
    const canonical = id.toCanonical();
    console.log(canonical);

    // Encode the id for efficient db storage
    const raw = id.toRaw();
    console.log(raw);

    // Verify a canonically formatted id
    console.log(IdType.isCanonical(canonical));

    // Decode a valid canonically formatted id
    console.log(id.equal(IdType.fromCanonical(canonical)));

    // Decode a canonically formatted id, skipping validation
    console.log(id.equal(IdType.fromCanonicalTrusted(canonical)));

    // Verify a raw formatted id
    console.log(IdType.isRaw(raw));

    // Decode a valid raw formatted id
    console.log(id.equal(IdType.fromRaw(raw)));

    // Decode a raw formatted id, skipping validation
    console.log(id.equal(IdType.fromRawTrusted(raw)));
});

// Uuid Factory
[0, 1, 4, 6].forEach((version) => {
    // Generate a new id
    const id = Uuid.generate({ version });

    // Get the smallest valid id
    const min = Uuid.MIN({ version });

    // Get the largest valid id
    const max = Uuid.MAX({ version });

    // Type-check the id
    console.log(id instanceof Uuid.type)

    // Encode the id in its canonical form
    const canonical = id.toCanonical();
    console.log(canonical);

    // Encode the id for efficient db storage
    const raw = id.toRaw();
    console.log(raw);

    // Decode a valid canonically formatted id
    console.log(id.equal(Uuid.fromCanonical(canonical)));

    // Decode a canonically formatted id, skipping validation
    console.log(id.equal(Uuid.fromCanonicalTrusted(canonical)));

    // Decode a valid raw formatted id
    console.log(id.equal(Uuid.fromRaw(raw)));

    // Decode a raw formatted id, skipping validation
    console.log(id.equal(Uuid.fromRawTrusted(raw)));
});

// Static Utilities

// Equate arbitrary ids
console.log(idEqual(Ulid.generate(), Uuid4.generate()))

// Compare arbitrary ids
console.log(idCompare(Ulid.generate(), Uuid4.generate()))

Common Factory Properties

name

Return the name of the generated id type.

type

Return the type of the generated id instances for type-checking with the instanceof operator.

Common Factory Methods

.construct(bytes) => id

Return a new id instance without validating the bytes.

.generate() => id

Return a new id instance.

.MIN() => id

Return the id instance with the smallest valid value.

.MAX() => id

Return the id instance with the largest valid value.

.fromCanonical(canonical_string) => id

Decode an id from its canonical representation. Throw InvalidEncoding if the string is undecodable.

.fromCanonicalTrusted(canonical_string) => id

Decode an id from its canonical representation. Skip validation and assume the input is decodable.

.fromRaw(raw_string) => id

Decode an id from its raw representation. Throw InvalidEncoding if the string is undecodable.

.fromRawTrusted(raw_string) => id

Decode an id from its raw representation. Skip validation and assume the input is decodable.

.toCanonical(id) => canonical_string

Encode the given id in the canonical form. Throw InvalidBytes if the id is not 128-bit conformant.

.toRaw(id) => raw_string

Encode the given id in the raw form. Throw InvalidBytes if the id is not 128-bit conformant.

.isCanonical(canonical_string) => (true|false)

Verify if a string is a valid canonical encoding.

.isRaw(raw_string) => (true|false)

Verify if a string is a valid raw encoding.

Common Instance Properties

bytes

Return the actual byte array representing the id.

Common Instance Methods

.clone() => deep_copy

Return a new instance of the id with the same bit signature.

.compare(other) => (-1|0|1)

Determine how this id is ordered against another.

.equal(other) => (true|false)

Determine if this id has the same bytes as another.

.toCanonical() => canonical_string

Encode this id in its canonical form.

.toRaw() => raw_string

Encode this id in its raw form.

Namespace Static Utilities

idCompare(left_id, right_id) => (-1|0|1)

Determine if the left id is less than | equal to | greater than the right id using lexicographical byte order.

idEqual(left_id, right_id) => (true|false)

Determine if 2 ids have the same byte value.

Ulid

const { Ulid } = require('id128');

Ulid, as specified, has some nice properties: - collision resistant: 80-bits of randomness - k-ordered: prefixed with millisecond precision timestamp - database friendly: fits within a uuid and generally appends to the index - human friendly: canonically encodes as a case-insensitive Crockford 32 number

It is useful when you need a distributed domain unique id.

Additional Instance Properties

time

Return a Date object for the epoch milliseconds encoded in the id.

Additional Factory Methods

.generate({ time }) => id

Return a new id instance. Set any argument to null or undefined to trigger its default behavior.

time defaults to the current time. It can be given either as a Date object or epoch milliseconds (milliseconds since January 1st, 1970). Throw InvalidEpoch for times before the epoch or after approximately August 2nd, 10889. This is provided mostly for unit tests.

Byte Format

Format tttt tttt tttt rrrr rrrr rrrr rrrr rrrr where: - t is 4 bits of time - r is 4 bits of random

UlidMonotonic

const { UlidMonotonic } = require('id128');

UlidMonotonic is inspired by the specification: - collision resistant: 15-bits of random seeded clock sequence plus 64-bits of randomness - total ordered: prefixed with millisecond precision timestamp plus 15-bit clock sequence - database friendly: fits within a uuid and generally appends to the index - human friendly: canonically encodes as a case-insensitive Crockford 32 number

It is useful when you need to guarantee a process unique id.

Additional Instance Properties

time

Return a Date object for the epoch milliseconds encoded in the id.

Additional Factory Methods

.generate({ time }) => id

Return a new id instance. Set any argument to null or undefined to trigger its default behavior.

time defaults to the current time. It can be given either as a Date object or epoch milliseconds (milliseconds since January 1st, 1970). Extra caution is required since setting a future time and subsequently calling generate guarantees usage of the clock sequence. Throw InvalidEpoch for times before the epoch or after approximately August 2nd, 10889. Throw ClockSequenceOverflow when the clock sequence is exhausted. This is provided mostly for unit tests.

.reset()

Return the clock sequence to its starting position. This is provided mostly for unit tests.

Byte Format

Format tttt tttt tttt cccc rrrr rrrr rrrr rrrr where: - t is 4 bits of time - c is 4 bits of random-seeded clock sequence - r is 4 bits of random

More specifically, the clock sequence is a counter. When the first id for a new timestamp is generated, the clock sequence is seeded with random bits and the left-most clock sequence bit is set to 0, reserving 2^15 clock ticks. Whenever a time from the past seeds the generator, the previous id's time and clock sequence are used instead, with the clock sequence incremented by 1. This guarantees strict local monotonicity and preserves lexical ordering and general randomness.

Without a seeded time, UlidMonotonic is unlikely to exceed the clock sequence (the clock sequence supports generating a new id every 31 nanoseconds). However, in the unlikely event of an overflow, id generation is aborted.

Uuid1

const { Uuid1 } = require('id128');

Uuid1 implements the RFC 4122 time specification: - time-based: encodes the current millisecond timestamp - location-based: encodes the mac address of the machine

While this mostly adheres to the spec, there are a few nuances in the handling of time. Instead of encoding time as 100-nanoseconds since the Gregorian epoch, 48 bits encode milliseconds since the Gregorian epoch time and 12 bits count past time collisions, resetting whenever given a new future time. There are a few benefits: - high precision time is unreliable in the browser so this ensures better precision - the max supported date is now around the year 10502 instead of around 5236 - generating 4096 ids/ms (~4,000,000 ids/s) is wildly unlikely in real world uses - in the rare hi-res overflow, the count simply spills over to the clock sequence

Additional Instance Properties

clock_sequence

Return the clock sequence encoded in the id.

hires_time

Return the number of prior ids generated while time stood still.

node

Return the MAC address encoded in the id.

time

Return a Date object for the epoch milliseconds encoded in the id.

variant

Return the variant as encoded in the id. Should be 1.

version

Return the version as encoded in the id. Should be 1.

Additional Factory Methods

.generate({ node, time }) => id

Return a new id instance. Set any argument to null or undefined to trigger its default behavior.

time defaults to the current time. It can be given either as a Date object or Gregorian milliseconds (milliseconds since October 15th, 1582). Extra caution is required since setting a future time and subsequently calling generate guarantees usage of the hi-res counter and clock sequence. Throw InvalidEpoch for times before the Gregorian epoch or after approximately May 17, 10502. This is provided mostly for unit tests.

node defaults to the MAC address, or a random multicast address when the MAC address is unavailable. It can be given as an array of 6 bytes.

.reset()

Return the hi-res counter to its starting position and generate a new random clock sequence seed. This is provided mostly for unit tests.

Byte Format

Format llll lnnn mmmm vhhh tccc aaaa aaaa aaaa where: - l is 4 bits of low millisecond time - n is 4 bits of hi-res time - m is 4 bits of mid millisecond time - v is 4 bits of the version - h is 4 bits of high millisecond time - t is 2 bits of the variant followed by 2 bits of the clock sequence - c is 4 bits of the clock sequence - a is 4 bits of the machine address

Uuid4

const { Uuid4 } = require('id128');

Uuid4 implements the RFC 4122 random uuid specification:

  • 122 random bits
  • 2 bits reserved for the variant (1)
  • 4 bits reserved for the version (4)

It is useful when you need a well-supported globally unique id.

Additional Instance Properties

variant

Return the variant as encoded in the id. Should be 1.

version

Return the version as encoded in the id. Should be 4.

Byte Format

Format rrrr rrrr rrrr vrrr trrr rrrr rrrr rrrr where: - r is 4 bits of random - v is 4 bits of the version - t is 2 bits of the variant followed by 2 bits of random

Uuid6

const { Uuid6 } = require('id128');

Uuid6 implements this controversial blog post: - time-based: encodes the current millisecond timestamp - location-based: encodes the mac address of the machine

This is essentially the same implementation as Uuid1, however the time bits are arranged in lexicographical order. If you're looking for a spacial UUID that is optimized for clustered indices, consider Uuid6 as a viable option.

Additional Instance Properties

clock_sequence

Return the clock sequence encoded in the id.

hires_time

Return the number of prior ids generated while time stood still.

node

Return the MAC address encoded in the id.

time

Return a Date object for the epoch milliseconds encoded in the id.

variant

Return the variant as encoded in the id. Should be 1.

version

Return the version as encoded in the id. Should be 6.

Additional Factory Methods

.generate({ node, time }) => id

Return a new id instance. Set any argument to null or undefined to trigger its default behavior.

time defaults to the current time. It can be given either as a Date object or Gregorian milliseconds (milliseconds since October 15th, 1582). Extra caution is required since setting a future time and subsequently calling generate guarantees usage of the hi-res counter and clock sequence. Throw InvalidEpoch for times before the Gregorian epoch or after approximately May 17, 10502. This is provided mostly for unit tests.

node defaults to the MAC address, or a random multicast address when the MAC address is unavailable. It can be given as an array of 6 bytes.

.reset()

Return the hi-res counter to its starting position and generate a new random clock sequence seed. This is provided mostly for unit tests.

Byte Format

Format mmmm mmmm mmmm vnnn tccc aaaa aaaa aaaa where: - m is 4 bits of millisecond time - v is 4 bits of the

Extension points exported contracts — how you extend this code

UlidFactory (Interface)
(no doc) [8 implementers]
index.d.ts
UlidFactory (Interface)
(no doc) [8 implementers]
types/index.d.ts
UlidMonotonicFactory (Interface)
(no doc) [8 implementers]
index.d.ts
UlidMonotonicFactory (Interface)
(no doc) [8 implementers]
types/index.d.ts
UuidFactory (Interface)
(no doc) [8 implementers]
index.d.ts
UuidFactory (Interface)
(no doc) [8 implementers]
types/index.d.ts
Uuid1Factory (Interface)
(no doc) [8 implementers]
index.d.ts
Uuid1Factory (Interface)
(no doc) [8 implementers]
types/index.d.ts

Core symbols most depended-on inside this repo

equal
called by 92
types/index.d.ts
generate
called by 73
types/index.d.ts
MIN
called by 47
types/index.d.ts
subject
called by 46
test/common/machine.js
MAX
called by 38
types/index.d.ts
toRaw
called by 29
types/index.d.ts
toCanonical
called by 28
types/index.d.ts
subject
called by 22
test/id/uuid-1.js

Shape

Method 164
Function 72
Interface 54
Class 53

Languages

TypeScript100%

Modules by API surface

types/index.d.ts55 symbols
index.d.ts55 symbols
src/factory/id.js25 symbols
test/factory/versioned-id.js15 symbols
test/id/shared.js14 symbols
src/id/uuid-6.js14 symbols
src/id/uuid-1.js14 symbols
test/factory/id.js13 symbols
src/common/exception.js13 symbols
src/factory/versioned-id.js9 symbols
src/coder/base.js9 symbols
src/id/uuid.js8 symbols

For agents

$ claude mcp add id128 \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page