CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-uuid

RFC9562 UUIDs

Pending
Overview
Eval results
Files

uuid-utilities.mddocs/

UUID Utilities

Essential utility functions for working with UUIDs including parsing, stringifying, validation, and version detection.

Capabilities

Parse UUID String

Converts a UUID string to its binary representation as a Uint8Array.

/**
 * Convert UUID string to byte array representation
 * @param uuid - Valid UUID string in canonical format
 * @returns Uint8Array of 16 bytes representing the UUID
 * @throws TypeError if UUID string is invalid
 */
function parse(uuid: string): Uint8Array;

Usage Examples:

import { parse } from "uuid";

// Parse a valid UUID string
const uuid = '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d';
const bytes = parse(uuid);
// ⇨ Uint8Array(16) [155, 29, 235, 77, 59, 125, 75, 173, 155, 221, 43, 13, 123, 61, 203, 109]

// Access individual bytes
console.log(bytes[0]);  // ⇨ 155 (first byte)
console.log(bytes.length); // ⇨ 16

// Parse throws on invalid UUID
try {
  parse('invalid-uuid');
} catch (error) {
  console.log(error.message); // ⇨ 'Invalid UUID'
}

Stringify Byte Array

Converts a byte array back to a UUID string in canonical format.

/**
 * Convert byte array to UUID string format
 * @param arr - Array of 16 bytes representing a UUID
 * @param offset - Starting offset in array (default: 0)
 * @returns UUID string in canonical format (lowercase with hyphens)
 * @throws TypeError if resulting UUID is invalid
 */
function stringify(arr: Uint8Array, offset?: number): string;

Unsafe Stringify Byte Array

Converts a byte array to a UUID string without validation for performance-critical applications.

/**
 * Convert byte array to UUID string without validation
 * @param arr - Array of 16 bytes representing a UUID
 * @param offset - Starting offset in array (default: 0)
 * @returns UUID string in canonical format (lowercase with hyphens)
 * @warning No validation performed - ensure input is valid UUID bytes
 */
function unsafeStringify(arr: Uint8Array, offset?: number): string;

Usage Examples:

import { stringify, unsafeStringify, parse } from "uuid";

// Create byte array manually
const bytes = new Uint8Array([
  155, 29, 235, 77, 59, 125, 75, 173,
  155, 221, 43, 13, 123, 61, 203, 109
]);

const uuidString = stringify(bytes);
// ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

// Performance-critical path with known valid bytes
const fastUuid = unsafeStringify(bytes);
// ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d' (no validation)

// Round-trip conversion
const original = '550e8400-e29b-41d4-a716-446655440000';
const parsed = parse(original);
const restored = stringify(parsed);
console.log(original === restored); // ⇨ true

// Using offset for buffer operations
const buffer = new Uint8Array(32);
// ... UUID bytes written starting at position 8
const uuidFromBuffer = stringify(buffer, 8);
const fastUuidFromBuffer = unsafeStringify(buffer, 8);

Validate UUID

Tests whether a value is a valid UUID string according to RFC9562 format.

/**
 * Test if value is a valid UUID string
 * @param uuid - Value to test (can be any type)
 * @returns Boolean indicating whether the value is a valid UUID string
 */
function validate(uuid: unknown): boolean;

Usage Examples:

import { validate } from "uuid";

// Valid UUIDs
console.log(validate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d')); // ⇨ true
console.log(validate('00000000-0000-0000-0000-000000000000')); // ⇨ true (NIL UUID)
console.log(validate('FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF')); // ⇨ true (case insensitive)

// Invalid UUIDs
console.log(validate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6')); // ⇨ false (too short)
console.log(validate('9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6dd')); // ⇨ false (too long)
console.log(validate('9b1deb4d_3b7d_4bad_9bdd_2b0d7b3dcb6d')); // ⇨ false (wrong separator)
console.log(validate('not-a-uuid')); // ⇨ false
console.log(validate(null)); // ⇨ false
console.log(validate(undefined)); // ⇨ false
console.log(validate(123)); // ⇨ false

// Type guard usage
function processUuid(value: unknown) {
  if (validate(value)) {
    // TypeScript knows value is a valid UUID string
    console.log(`Processing UUID: ${value.toUpperCase()}`);
  } else {
    console.log('Invalid UUID provided');
  }
}

Get UUID Version

Extracts and returns the version number from a UUID string.

/**
 * Extract and return the version number from UUID string
 * @param uuid - Valid UUID string
 * @returns Version number (1-7) indicating the UUID type
 * @throws TypeError if UUID string is invalid
 */
function version(uuid: string): number;

Usage Examples:

import { version, v1, v3, v4, v5, v6, v7 } from "uuid";

// Check versions of generated UUIDs
const v1Id = v1();
const v4Id = v4();
const v7Id = v7();

console.log(version(v1Id)); // ⇨ 1
console.log(version(v4Id)); // ⇨ 4  
console.log(version(v7Id)); // ⇨ 7

// Version-specific processing
function handleUuid(uuid: string) {
  if (!validate(uuid)) {
    throw new Error('Invalid UUID');
  }
  
  const ver = version(uuid);
  
  switch (ver) {
    case 1:
    case 6:
      console.log('Timestamp-based UUID');
      break;
    case 3:
    case 5:
      console.log('Namespace-based UUID');
      break;
    case 4:
      console.log('Random UUID');
      break;
    case 7:
      console.log('Unix Epoch time UUID');
      break;
    default:
      console.log(`UUID version ${ver}`);
  }
}

// Check existing UUID versions
console.log(version('550e8400-e29b-41d4-a716-446655440000')); // ⇨ 4
console.log(version('6ba7b810-9dad-11d1-80b4-00c04fd430c8')); // ⇨ 1

// Version extraction throws on invalid UUID
try {
  version('invalid-uuid');
} catch (error) {
  console.log(error.message); // ⇨ 'Invalid UUID'
}

String to Bytes Conversion

Converts a string to its UTF-8 byte array representation for use with namespace-based UUID generation.

/**
 * Convert string to byte array using UTF-8 encoding
 * @param str - String to convert to bytes
 * @returns Uint8Array representation of the string in UTF-8
 */
function stringToBytes(str: string): Uint8Array;

Usage Examples:

import { stringToBytes, v5 } from "uuid";

// Convert string for namespace UUID generation
const nameBytes = stringToBytes("my-resource-name");
const resourceId = v5(nameBytes, v5.DNS);

// Compare with direct string usage (equivalent)
const directId = v5("my-resource-name", v5.DNS);
console.log(resourceId === directId); // ⇨ true

// Useful for non-ASCII strings
const unicodeBytes = stringToBytes("資源名称");
const unicodeId = v5(unicodeBytes, v5.DNS);

// Manual UTF-8 encoding comparison
const manualBytes = new TextEncoder().encode("my-resource-name");
console.log(stringToBytes("my-resource-name").every((byte, i) => byte === manualBytes[i])); // ⇨ true

Internal Testing Functions

Functions exported for internal testing purposes only. These should not be used in production code.

/**
 * Update V1 state (exported for testing only)
 * @param state - V1 state object
 * @param now - Current timestamp
 * @param rnds - Random bytes
 * @returns Updated state object
 * @internal
 */
function updateV1State(state: V1State, now: number, rnds: Uint8Array): V1State;

/**
 * Update V7 state (exported for testing only)  
 * @param state - V7 state object
 * @param now - Current timestamp
 * @param rnds - Random bytes
 * @returns Updated state object
 * @internal
 */
function updateV7State(state: V7State, now: number, rnds: Uint8Array): V7State;

⚠️ Warning: These functions are exported for internal testing purposes only and should not be used in production code. Their behavior may change without notice.

Combined Usage Patterns

Common patterns combining multiple utility functions:

import { v4, parse, stringify, validate, version } from "uuid";

// Safe UUID processing pipeline
function processUuidSafely(input: unknown): { valid: boolean; info?: any } {
  if (!validate(input)) {
    return { valid: false };
  }
  
  const ver = version(input as string);
  const bytes = parse(input as string);
  const canonical = stringify(bytes);
  
  return {
    valid: true,
    info: {
      version: ver,
      canonical: canonical,
      bytes: Array.from(bytes),
      length: bytes.length
    }
  };
}

// UUID normalization
function normalizeUuid(uuid: string): string {
  if (!validate(uuid)) {
    throw new Error('Invalid UUID format');
  }
  
  // Parse and stringify to ensure canonical format
  return stringify(parse(uuid));
}

// Example: normalize mixed case UUID
const mixedCase = 'A1B2C3D4-E5F6-1234-ABCD-123456789ABC';
const normalized = normalizeUuid(mixedCase);
// ⇨ 'a1b2c3d4-e5f6-1234-abcd-123456789abc'

Install with Tessl CLI

npx tessl i tessl/npm-uuid

docs

constants-conversions.md

index.md

uuid-generation.md

uuid-utilities.md

tile.json