or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.mdkotlinx-dom.mdorg-w3c-additional.mdorg-w3c-dom.mdorg-w3c-events.mdorg-w3c-networking.md

org-w3c-networking.mddocs/

0

# Networking APIs

1

2

Modern networking capabilities including Fetch API for HTTP requests, XMLHttpRequest for legacy support, headers manipulation, and comprehensive CORS handling for web applications.

3

4

## Capabilities

5

6

### Fetch API

7

8

Modern promise-based HTTP request API with comprehensive feature support.

9

10

```kotlin { .api }

11

/**

12

* Make HTTP requests using the Fetch API

13

*/

14

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

15

16

/**

17

* HTTP Request representation

18

*/

19

external class Request(input: dynamic, init: RequestInit = definedExternally) : Body {

20

/** The request method */

21

val method: String

22

/** The request URL */

23

val url: String

24

/** The request headers */

25

val headers: Headers

26

/** The request type */

27

val type: RequestType

28

/** The request destination */

29

val destination: RequestDestination

30

/** The request referrer */

31

val referrer: String

32

/** The request referrer policy */

33

val referrerPolicy: String

34

/** The request mode */

35

val mode: RequestMode

36

/** The request credentials mode */

37

val credentials: RequestCredentials

38

/** The request cache mode */

39

val cache: RequestCache

40

/** The request redirect mode */

41

val redirect: RequestRedirect

42

/** The request integrity */

43

val integrity: String

44

/** Whether to keep the connection alive */

45

val keepalive: Boolean

46

47

/** Clone the request */

48

fun clone(): Request

49

}

50

51

/**

52

* HTTP Response representation

53

*/

54

external class Response(body: dynamic = definedExternally, init: ResponseInit = definedExternally) : Body {

55

/** The response type */

56

val type: ResponseType

57

/** The response URL */

58

val url: String

59

/** Whether the response was redirected */

60

val redirected: Boolean

61

/** The response status code */

62

val status: Short

63

/** Whether the response is successful (200-299) */

64

val ok: Boolean

65

/** The response status text */

66

val statusText: String

67

/** The response headers */

68

val headers: Headers

69

/** The response trailer */

70

val trailer: Promise<Headers>

71

72

/** Clone the response */

73

fun clone(): Response

74

75

companion object {

76

/** Create error response */

77

fun error(): Response

78

/** Create redirect response */

79

fun redirect(url: String, status: Short = definedExternally): Response

80

}

81

}

82

83

/**

84

* Request/Response body interface

85

*/

86

external interface Body {

87

/** Whether the body has been used */

88

val bodyUsed: Boolean

89

/** The body as a ReadableStream */

90

val body: ReadableStream<Uint8Array>?

91

92

/** Read body as ArrayBuffer */

93

fun arrayBuffer(): Promise<ArrayBuffer>

94

/** Read body as Blob */

95

fun blob(): Promise<Blob>

96

/** Read body as FormData */

97

fun formData(): Promise<FormData>

98

/** Read body as JSON */

99

fun json(): Promise<Any?>

100

/** Read body as text */

101

fun text(): Promise<String>

102

}

103

104

/**

105

* HTTP Headers manipulation

106

*/

107

external class Headers(init: dynamic = definedExternally) {

108

/** Append header value */

109

fun append(name: String, value: String)

110

/** Delete header */

111

fun delete(name: String)

112

/** Get header value */

113

fun get(name: String): String?

114

/** Check if header exists */

115

fun has(name: String): Boolean

116

/** Set header value */

117

fun set(name: String, value: String)

118

/** Get header keys */

119

fun keys(): Iterator<String>

120

/** Get header values */

121

fun values(): Iterator<String>

122

/** Get header entries */

123

fun entries(): Iterator<Array<String>>

124

/** Iterate over headers */

125

fun forEach(callback: (String, String, Headers) -> Unit, thisArg: Any = definedExternally)

126

}

127

```

128

129

### Request Configuration

130

131

Request initialization and configuration options.

132

133

```kotlin { .api }

134

/**

135

* Request initialization options

136

*/

137

external interface RequestInit {

138

/** HTTP method */

139

var method: String?

140

/** Request headers */

141

var headers: dynamic

142

/** Request body */

143

var body: dynamic

144

/** Request referrer */

145

var referrer: String?

146

/** Referrer policy */

147

var referrerPolicy: String?

148

/** Request mode (cors, no-cors, same-origin) */

149

var mode: RequestMode?

150

/** Credentials mode */

151

var credentials: RequestCredentials?

152

/** Cache mode */

153

var cache: RequestCache?

154

/** Redirect mode */

155

var redirect: RequestRedirect?

156

/** Subresource integrity */

157

var integrity: String?

158

/** Keep connection alive */

159

var keepalive: Boolean?

160

/** Associated window */

161

var window: Any?

162

}

163

164

/**

165

* Response initialization options

166

*/

167

external interface ResponseInit {

168

/** Status code */

169

var status: Short?

170

/** Status text */

171

var statusText: String?

172

/** Response headers */

173

var headers: dynamic

174

}

175

176

/**

177

* Request types

178

*/

179

enum class RequestType {

180

EMPTY,

181

AUDIO,

182

FONT,

183

IMAGE,

184

SCRIPT,

185

STYLE,

186

TRACK,

187

VIDEO

188

}

189

190

/**

191

* Request destinations

192

*/

193

enum class RequestDestination {

194

DOCUMENT,

195

EMBED,

196

FONT,

197

IMAGE,

198

MANIFEST,

199

MEDIA,

200

OBJECT,

201

REPORT,

202

SCRIPT,

203

SERVICEWORKER,

204

SHAREDWORKER,

205

STYLE,

206

TRACK,

207

VIDEO,

208

WORKER,

209

XSLT

210

}

211

212

/**

213

* Request modes

214

*/

215

enum class RequestMode {

216

NAVIGATE,

217

SAME_ORIGIN,

218

NO_CORS,

219

CORS

220

}

221

222

/**

223

* Request credentials modes

224

*/

225

enum class RequestCredentials {

226

OMIT,

227

SAME_ORIGIN,

228

INCLUDE

229

}

230

231

/**

232

* Request cache modes

233

*/

234

enum class RequestCache {

235

DEFAULT,

236

NO_STORE,

237

RELOAD,

238

NO_CACHE,

239

FORCE_CACHE,

240

ONLY_IF_CACHED

241

}

242

243

/**

244

* Request redirect modes

245

*/

246

enum class RequestRedirect {

247

FOLLOW,

248

ERROR,

249

MANUAL

250

}

251

252

/**

253

* Response types

254

*/

255

enum class ResponseType {

256

BASIC,

257

CORS,

258

DEFAULT,

259

ERROR,

260

OPAQUE,

261

OPAQUEREDIRECT

262

}

263

```

264

265

### XMLHttpRequest

266

267

Legacy HTTP request API with comprehensive feature support.

268

269

```kotlin { .api }

270

/**

271

* XMLHttpRequest for HTTP requests

272

*/

273

external class XMLHttpRequest : XMLHttpRequestEventTarget {

274

/** The request ready state */

275

val readyState: Short

276

/** Request timeout in milliseconds */

277

var timeout: Int

278

/** Whether to send credentials with cross-origin requests */

279

var withCredentials: Boolean

280

/** Upload object for monitoring upload progress */

281

val upload: XMLHttpRequestUpload

282

/** The response URL */

283

val responseURL: String

284

/** The response status */

285

val status: Short

286

/** The response status text */

287

val statusText: String

288

/** The response type */

289

var responseType: XMLHttpRequestResponseType

290

/** The response body */

291

val response: Any?

292

/** The response as text */

293

val responseText: String

294

/** The response as XML document */

295

val responseXML: Document?

296

297

/** Open a request */

298

fun open(method: String, url: String, async: Boolean = definedExternally, user: String? = definedExternally, password: String? = definedExternally)

299

/** Set request header */

300

fun setRequestHeader(name: String, value: String)

301

/** Send the request */

302

fun send(body: dynamic = definedExternally)

303

/** Abort the request */

304

fun abort()

305

/** Get response header */

306

fun getResponseHeader(name: String): String?

307

/** Get all response headers */

308

fun getAllResponseHeaders(): String

309

/** Override MIME type */

310

fun overrideMimeType(mime: String)

311

312

companion object {

313

const val UNSENT: Short = 0

314

const val OPENED: Short = 1

315

const val HEADERS_RECEIVED: Short = 2

316

const val LOADING: Short = 3

317

const val DONE: Short = 4

318

}

319

}

320

321

/**

322

* Base class for XMLHttpRequest event targets

323

*/

324

external interface XMLHttpRequestEventTarget : EventTarget {

325

/** Load start event */

326

var onloadstart: ((ProgressEvent) -> Unit)?

327

/** Progress event */

328

var onprogress: ((ProgressEvent) -> Unit)?

329

/** Abort event */

330

var onabort: ((ProgressEvent) -> Unit)?

331

/** Error event */

332

var onerror: ((ProgressEvent) -> Unit)?

333

/** Load event */

334

var onload: ((ProgressEvent) -> Unit)?

335

/** Timeout event */

336

var ontimeout: ((ProgressEvent) -> Unit)?

337

/** Load end event */

338

var onloadend: ((ProgressEvent) -> Unit)?

339

}

340

341

/**

342

* XMLHttpRequest upload monitoring

343

*/

344

external interface XMLHttpRequestUpload : XMLHttpRequestEventTarget

345

346

/**

347

* Progress event for upload/download monitoring

348

*/

349

external class ProgressEvent(type: String, eventInitDict: ProgressEventInit = definedExternally) : Event {

350

/** Whether length is computable */

351

val lengthComputable: Boolean

352

/** Bytes loaded */

353

val loaded: Double

354

/** Total bytes */

355

val total: Double

356

}

357

358

external interface ProgressEventInit : EventInit {

359

var lengthComputable: Boolean?

360

var loaded: Double?

361

var total: Double?

362

}

363

364

/**

365

* XMLHttpRequest response types

366

*/

367

enum class XMLHttpRequestResponseType {

368

EMPTY,

369

ARRAYBUFFER,

370

BLOB,

371

DOCUMENT,

372

JSON,

373

TEXT

374

}

375

```

376

377

### Form Data

378

379

Form data handling for HTTP requests.

380

381

```kotlin { .api }

382

/**

383

* Form data for HTTP requests

384

*/

385

external class FormData(form: HTMLFormElement = definedExternally) {

386

/** Append form field */

387

fun append(name: String, value: String)

388

/** Append file field */

389

fun append(name: String, blobValue: Blob, filename: String = definedExternally)

390

/** Delete form field */

391

fun delete(name: String)

392

/** Get form field value */

393

fun get(name: String): dynamic

394

/** Get all values for form field */

395

fun getAll(name: String): Array<dynamic>

396

/** Check if form field exists */

397

fun has(name: String): Boolean

398

/** Set form field value */

399

fun set(name: String, value: String)

400

/** Set file field value */

401

fun set(name: String, blobValue: Blob, filename: String = definedExternally)

402

/** Get form field keys */

403

fun keys(): Iterator<String>

404

/** Get form field values */

405

fun values(): Iterator<dynamic>

406

/** Get form field entries */

407

fun entries(): Iterator<Array<dynamic>>

408

/** Iterate over form fields */

409

fun forEach(callback: (dynamic, String, FormData) -> Unit, thisArg: Any = definedExternally)

410

}

411

```

412

413

### URL Manipulation

414

415

URL parsing and manipulation utilities.

416

417

```kotlin { .api }

418

/**

419

* URL parsing and manipulation

420

*/

421

external class URL(url: String, base: String = definedExternally) {

422

/** The complete URL */

423

var href: String

424

/** The URL origin */

425

val origin: String

426

/** The URL protocol */

427

var protocol: String

428

/** The URL username */

429

var username: String

430

/** The URL password */

431

var password: String

432

/** The URL host (hostname:port) */

433

var host: String

434

/** The URL hostname */

435

var hostname: String

436

/** The URL port */

437

var port: String

438

/** The URL pathname */

439

var pathname: String

440

/** The URL search string */

441

var search: String

442

/** The URL search parameters */

443

val searchParams: URLSearchParams

444

/** The URL hash */

445

var hash: String

446

447

companion object {

448

/** Convert domain to ASCII */

449

fun domainToASCII(domain: String): String

450

/** Convert domain to Unicode */

451

fun domainToUnicode(domain: String): String

452

/** Create object URL */

453

fun createObjectURL(obj: dynamic): String

454

/** Revoke object URL */

455

fun revokeObjectURL(url: String)

456

}

457

}

458

459

/**

460

* URL search parameters manipulation

461

*/

462

external class URLSearchParams(init: dynamic = definedExternally) {

463

/** Append parameter */

464

fun append(name: String, value: String)

465

/** Delete parameter */

466

fun delete(name: String)

467

/** Get parameter value */

468

fun get(name: String): String?

469

/** Get all values for parameter */

470

fun getAll(name: String): Array<String>

471

/** Check if parameter exists */

472

fun has(name: String): Boolean

473

/** Set parameter value */

474

fun set(name: String, value: String)

475

/** Sort parameters */

476

fun sort()

477

/** Get parameter keys */

478

fun keys(): Iterator<String>

479

/** Get parameter values */

480

fun values(): Iterator<String>

481

/** Get parameter entries */

482

fun entries(): Iterator<Array<String>>

483

/** Iterate over parameters */

484

fun forEach(callback: (String, String, URLSearchParams) -> Unit, thisArg: Any = definedExternally)

485

/** Convert to string */

486

override fun toString(): String

487

}

488

```

489

490

**Usage Examples:**

491

492

```kotlin

493

import kotlinx.browser.window

494

import org.w3c.fetch.*

495

import org.w3c.xhr.*

496

497

// Basic fetch request

498

suspend fun fetchData(): String {

499

val response = fetch("/api/data").await()

500

if (!response.ok) {

501

throw Exception("HTTP ${response.status}: ${response.statusText}")

502

}

503

return response.text().await()

504

}

505

506

// POST request with JSON

507

suspend fun postJson(data: Any) {

508

val response = fetch("/api/submit", object : RequestInit {

509

override var method = "POST"

510

override var headers = mapOf(

511

"Content-Type" to "application/json",

512

"Accept" to "application/json"

513

)

514

override var body = JSON.stringify(data)

515

}).await()

516

517

if (!response.ok) {

518

throw Exception("Failed to submit data")

519

}

520

}

521

522

// File upload with FormData

523

suspend fun uploadFile(file: File) {

524

val formData = FormData()

525

formData.append("file", file)

526

formData.append("description", "Uploaded file")

527

528

val response = fetch("/api/upload", object : RequestInit {

529

override var method = "POST"

530

override var body = formData

531

}).await()

532

533

val result = response.json().await()

534

console.log("Upload result:", result)

535

}

536

537

// XMLHttpRequest with progress monitoring

538

fun downloadWithProgress(url: String, onProgress: (Double) -> Unit) {

539

val xhr = XMLHttpRequest()

540

541

xhr.onprogress = { event ->

542

if (event.lengthComputable) {

543

val progress = event.loaded / event.total

544

onProgress(progress)

545

}

546

}

547

548

xhr.onload = {

549

console.log("Download complete")

550

}

551

552

xhr.onerror = {

553

console.error("Download failed")

554

}

555

556

xhr.open("GET", url)

557

xhr.send()

558

}

559

560

// Headers manipulation

561

val headers = Headers()

562

headers.set("Authorization", "Bearer token123")

563

headers.set("Content-Type", "application/json")

564

headers.append("Accept", "application/json")

565

566

headers.forEach { value, name, _ ->

567

console.log("$name: $value")

568

}

569

570

// URL manipulation

571

val url = URL("https://example.com/search?q=kotlin")

572

url.searchParams.set("lang", "en")

573

url.searchParams.append("filter", "recent")

574

console.log(url.toString()) // https://example.com/search?q=kotlin&lang=en&filter=recent

575

576

// Custom headers and CORS

577

suspend fun apiCall() {

578

val response = fetch("/api/data", object : RequestInit {

579

override var mode = RequestMode.CORS

580

override var credentials = RequestCredentials.INCLUDE

581

override var headers = mapOf(

582

"X-Custom-Header" to "value",

583

"Accept" to "application/json"

584

)

585

}).await()

586

587

val data = response.json().await()

588

console.log("API response:", data)

589

}

590

```