or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

browser-integration.mdcollections.mdcoroutines.mdindex.mdio-encoding.mdjavascript-interop.mdmath-time.mdreflection.mduuid.mdw3c-dom-apis.md

index.mddocs/

0

# Kotlin Standard Library for JavaScript

1

2

The Kotlin Standard Library for JavaScript provides JavaScript-specific extensions to the Kotlin standard library, enabling developers to write Kotlin code that compiles to JavaScript while maintaining full interoperability with existing JavaScript ecosystems. It includes comprehensive type-safe bindings for W3C web standards, JavaScript-specific collection implementations, platform-specific I/O operations, and essential runtime support for Kotlin language features in JavaScript environments.

3

4

## Package Information

5

6

- **Package Name**: kotlin-stdlib-js

7

- **Package Type**: maven

8

- **Language**: Kotlin

9

- **Installation**: Include in Gradle build: `implementation("org.jetbrains.kotlin:kotlin-stdlib-js:2.2.0")`

10

11

## Core Imports

12

13

```kotlin

14

// Core JavaScript interop

15

import kotlin.js.*

16

17

// DOM and browser APIs (W3C bindings included in kotlin-stdlib-js)

18

import org.w3c.dom.*

19

import org.w3c.xhr.*

20

import org.w3c.files.*

21

22

// Collections

23

import kotlin.collections.*

24

25

// Coroutines

26

import kotlin.coroutines.*

27

28

// Reflection

29

import kotlin.reflect.*

30

31

```

32

33

**Note**:

34

- Browser utilities like `kotlinx.browser.*` and `kotlinx.dom.*` require additional dependencies and are not part of kotlin-stdlib-js. The `kotlin.browser.*` package in stdlib-js contains deprecated APIs.

35

- UUID APIs in `kotlin.uuid.*` are experimental and require `@OptIn(ExperimentalUuidApi::class)` to use.

36

37

## Basic Usage

38

39

```kotlin

40

import kotlin.js.*

41

import org.w3c.dom.*

42

43

// JavaScript interop

44

val result = js("Math.max(1, 2, 3)") // Execute JavaScript code

45

val jsonObj = json("name" to "John", "age" to 30) // Create JSON objects

46

47

// JSON operations

48

val jsonString = JSON.stringify(jsonObj)

49

val parsed = JSON.parse<dynamic>(jsonString)

50

51

// Type-safe collections

52

val list = arrayListOf("apple", "banana", "orange")

53

val map = hashMapOf("key1" to "value1", "key2" to "value2")

54

55

// Promises and async operations

56

val promise = Promise.resolve("Success")

57

promise.then { result ->

58

js("console.log('Promise resolved: ' + result)")

59

}

60

61

// Dynamic type operations

62

val anyValue: Any = "test"

63

val dynamicValue = anyValue.asDynamic()

64

val typeString = jsTypeOf(anyValue) // Returns "string"

65

```

66

67

## Architecture

68

69

The Kotlin Standard Library for JavaScript is built around several key components:

70

71

- **JavaScript Interop Layer**: Direct integration with JavaScript runtime through dynamic typing, JSON support, and inline JS execution

72

- **W3C DOM Bindings**: Complete type-safe bindings for browser APIs including DOM, WebGL, Service Workers, and Media APIs

73

- **Collection Implementations**: JavaScript-optimized implementations of Kotlin collection interfaces

74

- **Coroutine Runtime**: JavaScript-specific coroutine execution using generators and event loop integration

75

- **Reflection System**: Runtime type information and JavaScript class interoperability

76

- **Browser Integration**: Direct access to browser globals, local storage, and DOM utilities

77

78

## Capabilities

79

80

### JavaScript Interoperability

81

82

Core JavaScript interop functionality for seamless integration with JavaScript code, including dynamic typing, JSON manipulation, and Promise support.

83

84

```kotlin { .api }

85

// Execute JavaScript code inline

86

external fun js(code: String): dynamic

87

88

// JavaScript type checking

89

external fun jsTypeOf(a: Any?): String

90

91

// External declarations placeholder

92

external val definedExternally: Nothing

93

94

// Dynamic type casting

95

inline fun Any?.asDynamic(): dynamic

96

inline fun <T> Any?.unsafeCast(): T

97

98

// JSON support

99

external interface Json {

100

operator fun get(propertyName: String): Any?

101

operator fun set(propertyName: String, value: Any?)

102

}

103

fun json(vararg pairs: Pair<String, Any?>): Json

104

fun Json.add(other: Json): Json

105

external object JSON {

106

fun stringify(o: Any?): String

107

fun stringify(o: Any?, replacer: ((key: String, value: Any?) -> Any?)): String

108

fun stringify(o: Any?, replacer: ((key: String, value: Any?) -> Any?)?, space: Int): String

109

fun stringify(o: Any?, replacer: ((key: String, value: Any?) -> Any?)?, space: String): String

110

fun stringify(o: Any?, replacer: Array<String>): String

111

fun stringify(o: Any?, replacer: Array<String>, space: Int): String

112

fun stringify(o: Any?, replacer: Array<String>, space: String): String

113

fun <T> parse(text: String): T

114

fun <T> parse(text: String, reviver: ((key: String, value: Any?) -> Any?)): T

115

}

116

117

// Promise support

118

external class Promise<out T>(executor: (resolve: (T) -> Unit, reject: (Throwable) -> Unit) -> Unit) {

119

fun <S> then(onFulfilled: ((T) -> S)?): Promise<S>

120

fun <S> then(onFulfilled: ((T) -> S)?, onRejected: ((Throwable) -> S)?): Promise<S>

121

fun <S> catch(onRejected: (Throwable) -> S): Promise<S>

122

fun finally(onFinally: () -> Unit): Promise<T>

123

companion object {

124

fun <S> all(promise: Array<out Promise<S>>): Promise<Array<out S>>

125

fun <S> race(promise: Array<out Promise<S>>): Promise<S>

126

fun reject(e: Throwable): Promise<Nothing>

127

fun <S> resolve(e: S): Promise<S>

128

fun <S> resolve(e: Promise<S>): Promise<S>

129

}

130

}

131

```

132

133

[JavaScript Interoperability](./javascript-interop.md)

134

135

### W3C DOM and Browser APIs

136

137

Comprehensive type-safe bindings for W3C web standards including DOM manipulation, HTTP requests, file handling, media APIs, and WebGL.

138

139

```kotlin { .api }

140

// Core DOM interfaces

141

external interface Document : Node

142

external interface Element : Node

143

external interface HTMLElement : Element

144

145

// Event handling

146

external interface Event

147

external interface EventTarget {

148

fun addEventListener(type: String, listener: EventListener)

149

}

150

151

// HTTP requests

152

external fun fetch(input: String, init: RequestInit? = definedExternally): Promise<Response>

153

external interface Response {

154

val ok: Boolean

155

val status: Short

156

fun text(): Promise<String>

157

fun json(): Promise<dynamic>

158

}

159

160

// File API

161

external interface File : Blob {

162

val name: String

163

val lastModified: Number

164

}

165

external interface FileReader : EventTarget {

166

fun readAsText(file: Blob)

167

val result: String?

168

}

169

```

170

171

[W3C DOM and Browser APIs](./w3c-dom-apis.md)

172

173

### Collections

174

175

JavaScript-optimized implementations of Kotlin collection interfaces with specialized performance characteristics for JavaScript runtime.

176

177

```kotlin { .api }

178

// Mutable collection implementations

179

actual class ArrayList<E> : AbstractMutableList<E>

180

actual class HashMap<K, V> : AbstractMutableMap<K, V>

181

actual class HashSet<E> : AbstractMutableSet<E>

182

actual class LinkedHashMap<K, V> : AbstractMutableMap<K, V>

183

actual class LinkedHashSet<E> : AbstractMutableSet<E>

184

185

// String-optimized collections

186

fun <V> stringMapOf(vararg pairs: Pair<String, V>): MutableMap<String, V>

187

fun stringSetOf(vararg elements: String): MutableSet<String>

188

```

189

190

[Collections](./collections.md)

191

192

### Coroutines

193

194

JavaScript-specific coroutine support with generator-based execution and event loop integration for asynchronous programming.

195

196

```kotlin { .api }

197

// Core coroutine intrinsics

198

fun <T> (suspend () -> T).startCoroutineUninterceptedOrReturn(completion: Continuation<T>): Any?

199

fun <T> (suspend () -> T).createCoroutineUnintercepted(completion: Continuation<T>): Continuation<Unit>

200

fun <T> Continuation<T>.intercepted(): Continuation<T>

201

202

// Cancellation support

203

class CancellationException : IllegalStateException

204

```

205

206

[Coroutines](./coroutines.md)

207

208

### Reflection

209

210

Runtime reflection capabilities with JavaScript class interoperability for dynamic type inspection and instance creation.

211

212

```kotlin { .api }

213

// Core reflection interfaces

214

actual interface KClass<T : Any> {

215

val simpleName: String?

216

val qualifiedName: String?

217

}

218

actual interface KFunction<out R> : KCallable<R>

219

actual interface KProperty<out V> : KCallable<V>

220

221

// JavaScript integration

222

external interface JsClass<T : Any>

223

val <T : Any> KClass<T>.js: JsClass<T>

224

val <T : Any> JsClass<T>.kotlin: KClass<T>

225

fun <T : Any> KClass<T>.createInstance(): T

226

```

227

228

[Reflection](./reflection.md)

229

230

### Browser Integration

231

232

Direct access to browser globals, DOM utilities, and local storage for web application development.

233

234

```kotlin { .api }

235

// Browser globals

236

external val window: Window

237

external val document: Document

238

external val localStorage: Storage

239

external val sessionStorage: Storage

240

241

// DOM utilities

242

fun Document.createElement(name: String, init: Element.() -> Unit): Element

243

fun Element.addClass(vararg cssClasses: String)

244

fun Element.removeClass(vararg cssClasses: String)

245

fun Element.hasClass(cssClass: String): Boolean

246

fun Node.clear()

247

```

248

249

[Browser Integration](./browser-integration.md)

250

251

### Math and Time

252

253

JavaScript-adapted mathematical functions and time/date utilities with proper type conversions and JavaScript Date integration.

254

255

```kotlin { .api }

256

// Time conversions

257

fun Instant.toJSDate(): Date

258

fun Date.toKotlinInstant(): Instant

259

260

// Duration units

261

actual enum class DurationUnit {

262

NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, DAYS

263

}

264

265

// Math functions (sample - full set available)

266

fun sin(x: Double): Double

267

fun cos(x: Double): Double

268

fun sqrt(x: Double): Double

269

fun pow(base: Double, exp: Double): Double

270

```

271

272

[Math and Time Utilities](./math-time.md)

273

274

### IO and Encoding

275

276

Base64 encoding support and I/O operations optimized for JavaScript runtime environments.

277

278

```kotlin { .api }

279

// Base64 encoding

280

object Base64 {

281

fun encode(source: ByteArray): ByteArray

282

fun decode(source: ByteArray): ByteArray

283

fun encodeToString(source: ByteArray): String

284

fun decodeFromString(source: String): ByteArray

285

}

286

```

287

288

[IO and Encoding](./io-encoding.md)

289

290

### UUID Support

291

292

**⚠️ EXPERIMENTAL API**: Secure UUID generation using Web Crypto API with platform-specific implementations for JavaScript environments.

293

294

```kotlin { .api }

295

// UUID functions (experimental, requires @OptIn(ExperimentalUuidApi::class))

296

@ExperimentalUuidApi

297

internal fun secureRandomUuid(): Uuid

298

```

299

300

[UUID Support](./uuid.md)

301

302

## Types

303

304

```kotlin { .api }

305

// Core JavaScript types

306

external interface dynamic

307

308

// JSON interface

309

external interface Json {

310

operator fun get(key: String): Any?

311

operator fun set(key: String, value: Any?)

312

}

313

314

// Promise type

315

external class Promise<out T> {

316

constructor(executor: (resolve: (T) -> Unit, reject: (Throwable) -> Unit) -> Unit)

317

}

318

319

// Regular expressions

320

external class RegExp {

321

constructor(pattern: String, flags: String? = definedExternally)

322

fun test(string: String): Boolean

323

fun exec(string: String): RegExpMatch?

324

}

325

326

external interface RegExpMatch {

327

val index: Int

328

val input: String

329

}

330

```