CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-jetbrains-kotlin--kotlin-stdlib-js

Kotlin Standard Library for JavaScript target with comprehensive W3C DOM bindings and JavaScript interoperability features.

Pending
Overview
Eval results
Files

uuid.mddocs/

UUID Support

⚠️ EXPERIMENTAL API: The UUID API is experimental and requires opt-in annotation @ExperimentalUuidApi to use.

Secure UUID generation using Web Crypto API with platform-specific implementations for JavaScript environments. This module provides cryptographically secure UUID generation optimized for JavaScript runtime.

Capabilities

Secure UUID Generation

Generate cryptographically secure UUIDs using the Web Crypto API.

/**
 * Generate cryptographically secure random UUID using Web Crypto API
 * @ExperimentalUuidApi This API is experimental and may change in future versions
 */
@ExperimentalUuidApi
internal fun secureRandomUuid(): Uuid

/**
 * UUID class representing a 128-bit universally unique identifier
 */
class Uuid {
    /**
     * Convert UUID to string representation
     */
    override fun toString(): String
    
    /**
     * Convert UUID to byte array
     */
    fun toByteArray(): ByteArray
    
    /**
     * Get most significant 64 bits
     */
    val mostSignificantBits: Long
    
    /**
     * Get least significant 64 bits  
     */
    val leastSignificantBits: Long
    
    companion object {
        /**
         * Parse UUID from string representation
         */
        fun parse(uuidString: String): Uuid
        
        /**
         * Create UUID from byte array
         */
        fun fromByteArray(byteArray: ByteArray): Uuid
        
        /**
         * Create UUID from most and least significant bits
         */
        fun fromLongs(mostSignificantBits: Long, leastSignificantBits: Long): Uuid
        
        /**
         * Generate random UUID (uses secure random if available)
         */
        fun random(): Uuid
        
        /**
         * NIL UUID (all zeros)
         */
        val NIL: Uuid
    }
}

Usage Examples:

import kotlin.uuid.*

@OptIn(ExperimentalUuidApi::class)
fun uuidExample() {
    // Generate secure random UUID
    val uuid = secureRandomUuid()
    console.log("Generated UUID: $uuid")
// Output: "f47ac10b-58cc-4372-a567-0e02b2c3d479"

// Parse UUID from string
val uuidString = "123e4567-e89b-12d3-a456-426614174000"
val parsedUuid = Uuid.parse(uuidString)
console.log("Parsed UUID: $parsedUuid")

// Generate random UUID (alternative method)
val randomUuid = Uuid.random()
console.log("Random UUID: $randomUuid")

// Work with UUID components
val testUuid = secureRandomUuid()
val mostSig = testUuid.mostSignificantBits
val leastSig = testUuid.leastSignificantBits
console.log("Most significant bits: ${mostSig.toString(16)}")
console.log("Least significant bits: ${leastSig.toString(16)}")

// Convert to byte array
val byteArray = testUuid.toByteArray()
val reconstructed = Uuid.fromByteArray(byteArray)
console.log("Original: $testUuid")
console.log("Reconstructed: $reconstructed")
console.log("Equal: ${testUuid == reconstructed}") // true

// Create from components
val customUuid = Uuid.fromLongs(0x123e4567e89b12d3L, 0xa456426614174000L)
console.log("Custom UUID: $customUuid")

// NIL UUID
val nilUuid = Uuid.NIL
console.log("NIL UUID: $nilUuid") // "00000000-0000-0000-0000-000000000000"

UUID Validation and Formatting

Validate and format UUID strings with proper error handling.

/**
 * Validate UUID string format
 */
fun String.isValidUuid(): Boolean

/**
 * Exception thrown for invalid UUID format
 */
class IllegalArgumentException : RuntimeException {
    constructor()
    constructor(message: String?)
    constructor(message: String?, cause: Throwable?)
}

Usage Examples:

import kotlin.uuid.*

// Validate UUID strings
val validUuid = "f47ac10b-58cc-4372-a567-0e02b2c3d479"
val invalidUuid = "not-a-uuid"

console.log("Valid: ${validUuid.isValidUuid()}") // true
console.log("Invalid: ${invalidUuid.isValidUuid()}") // false

// Error handling for parsing
try {
    val uuid = Uuid.parse("invalid-uuid-format")
} catch (e: IllegalArgumentException) {
    console.error("Invalid UUID format: ${e.message}")
}

// Safe parsing function
fun parseUuidSafely(uuidString: String): Uuid? {
    return try {
        if (uuidString.isValidUuid()) {
            Uuid.parse(uuidString)
        } else {
            null
        }
    } catch (e: IllegalArgumentException) {
        null
    }
}

val safeUuid = parseUuidSafely("f47ac10b-58cc-4372-a567-0e02b2c3d479")
console.log("Safely parsed: $safeUuid")

Web Crypto API Integration

Direct integration with browser Web Crypto API for secure random number generation.

/**
 * Web Crypto API interfaces (used internally)
 */
external interface Crypto {
    fun getRandomValues(array: Uint8Array): Uint8Array
}

/**
 * Browser crypto object
 */
external val crypto: Crypto

/**
 * Typed array for unsigned 8-bit integers
 */
external interface Uint8Array {
    val length: Int
    operator fun get(index: Int): Byte
    operator fun set(index: Int, value: Byte)
}

Usage Examples:

import kotlin.uuid.*

// The secureRandomUuid() function uses Web Crypto API internally
// This provides cryptographically secure randomness in browsers

// Generate multiple UUIDs
val uuids = (1..5).map { secureRandomUuid() }
uuids.forEach { uuid ->
    console.log("UUID $it: $uuid")
}

// Use in data classes
data class User(
    val id: Uuid = secureRandomUuid(),
    val name: String,
    val email: String
)

val user = User(name = "Alice", email = "alice@example.com")
console.log("User ID: ${user.id}")

// Session management
class Session(
    val sessionId: Uuid = secureRandomUuid(),
    val userId: String,
    val createdAt: Double = js("Date.now()")
)

val session = Session(userId = "user123")
console.log("Session: ${session.sessionId}")

Types

// UUID class
class Uuid {
    val mostSignificantBits: Long
    val leastSignificantBits: Long
    
    override fun toString(): String
    fun toByteArray(): ByteArray
    
    companion object {
        fun parse(uuidString: String): Uuid
        fun fromByteArray(byteArray: ByteArray): Uuid
        fun fromLongs(mostSignificantBits: Long, leastSignificantBits: Long): Uuid
        fun random(): Uuid
        val NIL: Uuid
    }
}

// UUID generation functions
fun secureRandomUuid(): Uuid

// Validation extensions
fun String.isValidUuid(): Boolean

// Exception types
class IllegalArgumentException : RuntimeException

// Web Crypto API (internal)
external interface Crypto {
    fun getRandomValues(array: Uint8Array): Uint8Array
}
external val crypto: Crypto
external interface Uint8Array

Install with Tessl CLI

npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-stdlib-js

docs

browser-integration.md

collections.md

coroutines.md

index.md

io-encoding.md

javascript-interop.md

math-time.md

reflection.md

uuid.md

w3c-dom-apis.md

tile.json