Kotlin Standard Library for experimental WebAssembly JS platform providing core functionality and JavaScript interoperability
—
I/O operations, time management, random number generation, UUID support, and reflection services optimized for WebAssembly platform.
Console output operations for WebAssembly applications.
/**
* Prints line separator to standard output
*/
fun println()
/**
* Prints given message and line separator to standard output
* @param message Message to print (can be any type)
*/
fun println(message: Any?)
/**
* Prints given message to standard output
* @param message Message to print (can be any type)
*/
fun print(message: Any?)
/**
* Throws UnsupportedOperationException (not supported in K/Wasm)
* @return String (never returns)
* @throws UnsupportedOperationException Always thrown
*/
fun readln(): String
/**
* Throws UnsupportedOperationException (not supported in K/Wasm)
* @return String? (never returns)
* @throws UnsupportedOperationException Always thrown
*/
fun readlnOrNull(): String?Usage Examples:
// Basic console output
println("Hello, WebAssembly!")
println(42)
println(listOf("a", "b", "c"))
print("Loading")
print(".")
print(".")
print(".")
println(" Done!")
// Note: Input operations are not supported
try {
val input = readln() // This will throw UnsupportedOperationException
} catch (e: UnsupportedOperationException) {
println("Input not supported in WebAssembly")
}Time and duration handling with monotonic time source and instant support.
/**
* Monotonic time source using performance.now() or Date.now()
*/
object MonotonicTimeSource : TimeSource.WithComparableMarks {
/**
* Creates time mark for current moment
* @return ValueTimeMark Time mark representing current time
*/
fun markNow(): ValueTimeMark
/**
* Calculates elapsed duration from given time mark
* @param timeMark Starting time mark
* @return Duration Elapsed time duration
*/
fun elapsedFrom(timeMark: ValueTimeMark): Duration
/**
* Adjusts time mark by given duration
* @param timeMark Original time mark
* @param duration Duration to adjust by
* @return ValueTimeMark Adjusted time mark
*/
fun adjustReading(timeMark: ValueTimeMark, duration: Duration): ValueTimeMark
/**
* Calculates difference between two time marks
* @param one First time mark
* @param another Second time mark
* @return Duration Difference between time marks
*/
fun differenceBetween(one: ValueTimeMark, another: ValueTimeMark): Duration
}
/**
* Gets current system time as Instant
* @return Instant Current system time
*/
fun systemClockNow(): Instant
/**
* Throws UnsupportedOperationException (serialization only supported in K/JVM)
* @param instant Instant to serialize
* @return Any (never returns)
* @throws UnsupportedOperationException Always thrown
*/
internal fun serializedInstant(instant: Instant): Any
/**
* Formats double value to exact number of decimal places
* @param value Double value to format
* @param decimals Number of decimal places
* @return String Formatted string representation
*/
internal fun formatToExactDecimals(value: Double, decimals: Int): String
/**
* Always true for duration assertions
*/
internal val durationAssertionsEnabled: Boolean
/**
* Represents time mark reading as Double
*/
internal typealias ValueTimeMarkReading = DoubleUsage Examples:
import kotlin.time.*
// Measure execution time
val timeSource = TimeSource.Monotonic
val startMark = timeSource.markNow()
// Perform some operation
repeat(1000000) {
// Some work
}
val elapsed = timeSource.elapsedFrom(startMark)
println("Operation took: $elapsed")
// Work with instants
val now = Clock.System.now()
println("Current time: $now")
// Duration formatting
val duration = 1.5.seconds
println("Duration: ${duration.toString()}")Platform-specific random number generation using JavaScript Math.random().
/**
* Creates default platform Random instance using JavaScript Math.random()
* @return Random Platform-specific random number generator
*/
fun defaultPlatformRandom(): RandomUsage Examples:
import kotlin.random.Random
// Use default platform random
val random = Random.Default
println("Random int: ${random.nextInt()}")
println("Random double: ${random.nextDouble()}")
println("Random boolean: ${random.nextBoolean()}")
// Random in range
println("Random 1-10: ${random.nextInt(1, 11)}")
println("Random 0.0-1.0: ${random.nextDouble(0.0, 1.0)}")
// Random collection operations
val items = listOf("apple", "banana", "cherry", "date")
println("Random item: ${items.random()}")
val shuffled = items.shuffled()
println("Shuffled: $shuffled")Cryptographically secure UUID generation using browser crypto APIs.
/**
* Generates cryptographically secure random UUID using crypto.getRandomValues
* @return Uuid Cryptographically secure random UUID
*/
fun secureRandomUuid(): UuidUsage Examples:
import kotlin.uuid.Uuid
// Generate secure random UUIDs
val uuid1 = Uuid.random()
println("UUID 1: $uuid1")
val uuid2 = Uuid.random()
println("UUID 2: $uuid2")
// UUIDs are unique
println("UUIDs are different: ${uuid1 != uuid2}")
// Work with UUID properties
println("UUID string: ${uuid1.toString()}")
println("UUID bytes: ${uuid1.toByteArray().contentToString()}")
// Parse UUID from string
val uuidString = "550e8400-e29b-41d4-a716-446655440000"
val parsedUuid = Uuid.parse(uuidString)
println("Parsed UUID: $parsedUuid")Reflection support for external JavaScript classes and Kotlin objects.
/**
* KClass implementation for external JavaScript classes
* @param T Type of the external class
*/
internal class KExternalClassImpl<T : Any> : KClass<T> {
/**
* Simple class name from JavaScript constructor
*/
val simpleName: String?
/**
* Always null for external classes
*/
val qualifiedName: String?
/**
* Checks if value is instance using JavaScript instanceof
* @param value Value to check
* @return Boolean Whether value is instance of this class
*/
fun isInstance(value: Any?): Boolean
/**
* Compare JavaScript constructors
* @param other Other object to compare
* @return Boolean Whether objects are equal
*/
override fun equals(other: Any?): Boolean
/**
* Hash based on simple name
* @return Int Hash code
*/
override fun hashCode(): Int
/**
* String representation
* @return String String representation of the class
*/
override fun toString(): String
}
/**
* Gets KClass for given object, handling both Kotlin and JavaScript external objects
* @param obj Object to get KClass for
* @return KClass<T> KClass instance for the object
*/
internal fun <T : Any> getKClassForObject(obj: Any): KClass<T>Usage Examples:
import kotlin.reflect.KClass
// Get KClass for Kotlin objects
data class User(val name: String, val age: Int)
val user = User("Alice", 25)
val userClass: KClass<User> = user::class
println("Class name: ${userClass.simpleName}")
println("Is instance: ${userClass.isInstance(user)}")
// Work with external JavaScript classes
@JsName("Date")
external class JsDate : JsAny {
fun getTime(): Double
}
val jsDate = js("new Date()") as JsDate
val jsDateClass = jsDate::class
println("JS Class name: ${jsDateClass.simpleName}")
println("Is JS Date: ${jsDateClass.isInstance(jsDate)}")import kotlin.time.*
class PerformanceMonitor {
private val timeSource = TimeSource.Monotonic
fun <T> measureTime(operation: () -> T): Pair<T, Duration> {
val startMark = timeSource.markNow()
val result = operation()
val elapsed = timeSource.elapsedFrom(startMark)
return result to elapsed
}
fun benchmark(name: String, iterations: Int, operation: () -> Unit) {
println("Benchmarking $name...")
val times = mutableListOf<Duration>()
repeat(iterations) {
val (_, elapsed) = measureTime(operation)
times.add(elapsed)
}
val average = times.map { it.inWholeNanoseconds }.average().nanoseconds
val min = times.minOrNull() ?: Duration.ZERO
val max = times.maxOrNull() ?: Duration.ZERO
println("$name results:")
println(" Average: $average")
println(" Min: $min")
println(" Max: $max")
}
}
// Usage
val monitor = PerformanceMonitor()
monitor.benchmark("Array sort", 1000) {
val array = IntArray(1000) { Random.nextInt() }
array.sort()
}enum class LogLevel { DEBUG, INFO, WARN, ERROR }
class Logger(private val name: String) {
fun log(level: LogLevel, message: String, vararg args: Any?) {
val timestamp = Clock.System.now()
val formattedMessage = if (args.isNotEmpty()) {
message.format(*args)
} else {
message
}
println("[$timestamp] ${level.name} $name: $formattedMessage")
}
fun debug(message: String, vararg args: Any?) = log(LogLevel.DEBUG, message, *args)
fun info(message: String, vararg args: Any?) = log(LogLevel.INFO, message, *args)
fun warn(message: String, vararg args: Any?) = log(LogLevel.WARN, message, *args)
fun error(message: String, vararg args: Any?) = log(LogLevel.ERROR, message, *args)
}
// Usage
val logger = Logger("MyApp")
logger.info("Application started")
logger.warn("This is a warning with value: %d", 42)
logger.error("Something went wrong!")class IdGenerator {
private val random = Random.Default
fun generateShortId(): String {
return (1..8)
.map { "0123456789abcdefghijklmnopqrstuvwxyz".random(random) }
.joinToString("")
}
fun generateUuid(): String {
return Uuid.random().toString()
}
fun generateTimestampId(): String {
val timestamp = Clock.System.now().toEpochMilliseconds()
val randomSuffix = random.nextInt(1000, 9999)
return "${timestamp}-${randomSuffix}"
}
}
// Usage
val idGen = IdGenerator()
println("Short ID: ${idGen.generateShortId()}")
println("UUID: ${idGen.generateUuid()}")
println("Timestamp ID: ${idGen.generateTimestampId()}")Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-stdlib-wasm-js