or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

connection-management.mdcookies.mderror-handling.mdhttp-api.mdhttp-clients.mdindex.mdinterceptors.mdtesting-mocking.mdutilities.mdweb-standards.md

http-api.mddocs/

0

# HTTP API Functions

1

2

Convenience functions for common HTTP operations without requiring explicit client instantiation. These functions use the global dispatcher and provide a simplified interface for one-off requests.

3

4

## Capabilities

5

6

### Request Function

7

8

Performs HTTP requests with promise-based API.

9

10

```typescript { .api }

11

/**

12

* Perform an HTTP request using the global dispatcher

13

* @param url - The URL to request

14

* @param options - Request configuration options

15

* @returns Promise resolving to response data

16

*/

17

function request(

18

url: string | URL,

19

options?: Dispatcher.RequestOptions

20

): Promise<Dispatcher.ResponseData>;

21

22

interface Dispatcher.RequestOptions extends Dispatcher.DispatchOptions {

23

/** Dispatcher to use instead of global dispatcher */

24

dispatcher?: Dispatcher;

25

26

/** Maximum number of redirects to follow */

27

maxRedirections?: number;

28

29

/** Throw error for non-2xx status codes */

30

throwOnError?: boolean;

31

32

/** Request signal for cancellation */

33

signal?: AbortSignal;

34

}

35

36

interface Dispatcher.ResponseData {

37

statusCode: number;

38

headers: Record<string, string | string[]>;

39

body: Readable;

40

trailers: Record<string, string>;

41

opaque: unknown;

42

context: object;

43

}

44

```

45

46

**Usage Examples:**

47

48

```typescript

49

import { request } from "undici-types";

50

51

// Simple GET request

52

const response = await request("https://api.example.com/users");

53

console.log(response.statusCode);

54

console.log(await response.body.text());

55

56

// POST request with JSON body

57

const response = await request("https://api.example.com/users", {

58

method: "POST",

59

headers: {

60

"content-type": "application/json"

61

},

62

body: JSON.stringify({

63

name: "John Doe",

64

email: "john@example.com"

65

})

66

});

67

68

// Request with custom options

69

const response = await request("https://api.example.com/data", {

70

method: "GET",

71

headersTimeout: 10000,

72

bodyTimeout: 30000,

73

maxRedirections: 5,

74

throwOnError: true,

75

signal: AbortSignal.timeout(15000)

76

});

77

```

78

79

### Stream Function

80

81

High-performance streaming HTTP requests with custom response handling.

82

83

```typescript { .api }

84

/**

85

* Perform a streaming HTTP request with custom response processing

86

* Faster alternative to request() for streaming scenarios

87

* @param url - The URL to request

88

* @param options - Request configuration options

89

* @param factory - Function to create response stream processor

90

* @returns Promise resolving to processed stream data

91

*/

92

function stream(

93

url: string | URL,

94

options: Dispatcher.RequestOptions,

95

factory: Dispatcher.StreamFactory

96

): Promise<Dispatcher.StreamData>;

97

98

interface Dispatcher.StreamFactory {

99

(data: {

100

statusCode: number;

101

headers: Record<string, string | string[]>;

102

opaque: unknown;

103

}): Writable;

104

}

105

106

interface Dispatcher.StreamData {

107

opaque: unknown;

108

}

109

```

110

111

**Usage Examples:**

112

113

```typescript

114

import { stream } from "undici-types";

115

import { createWriteStream } from "fs";

116

117

// Stream response to file

118

await stream(

119

"https://example.com/large-file.zip",

120

{ method: "GET" },

121

({ statusCode, headers }) => {

122

console.log(`Response: ${statusCode}`);

123

console.log(`Content-Length: ${headers['content-length']}`);

124

return createWriteStream("./download.zip");

125

}

126

);

127

128

// Stream processing with custom transform

129

await stream(

130

"https://api.example.com/stream",

131

{ method: "GET" },

132

({ statusCode, headers }) => {

133

return new Transform({

134

transform(chunk, encoding, callback) {

135

// Process each chunk

136

const processed = processChunk(chunk);

137

callback(null, processed);

138

}

139

});

140

}

141

);

142

```

143

144

### Pipeline Function

145

146

Advanced streaming with full control over request and response streams.

147

148

```typescript { .api }

149

/**

150

* Create a pipeline for streaming HTTP requests with full stream control

151

* @param url - The URL to request

152

* @param options - Pipeline configuration options

153

* @param handler - Pipeline handler function

154

* @returns Promise resolving to pipeline data

155

*/

156

function pipeline(

157

url: string | URL,

158

options: Dispatcher.PipelineOptions,

159

handler: Dispatcher.PipelineHandler

160

): Promise<Dispatcher.PipelineData>;

161

162

interface Dispatcher.PipelineOptions extends Dispatcher.RequestOptions {

163

/** Object mode for stream */

164

objectMode?: boolean;

165

}

166

167

interface Dispatcher.PipelineHandler {

168

(data: {

169

statusCode: number;

170

headers: Record<string, string | string[]>;

171

opaque: unknown;

172

body: Readable;

173

}): Readable | Writable | Transform;

174

}

175

176

interface Dispatcher.PipelineData {

177

opaque: unknown;

178

}

179

```

180

181

**Usage Examples:**

182

183

```typescript

184

import { pipeline } from "undici-types";

185

import { Transform } from "stream";

186

187

// Pipeline with transformation

188

await pipeline(

189

"https://api.example.com/data",

190

{ method: "GET" },

191

({ statusCode, headers, body }) => {

192

console.log(`Status: ${statusCode}`);

193

194

return body

195

.pipe(new Transform({

196

objectMode: true,

197

transform(chunk, encoding, callback) {

198

const data = JSON.parse(chunk);

199

callback(null, JSON.stringify(data.items) + '\n');

200

}

201

}))

202

.pipe(createWriteStream('./processed.jsonl'));

203

}

204

);

205

```

206

207

### Connect Function

208

209

Establishes two-way communication channels for protocols like WebSocket.

210

211

```typescript { .api }

212

/**

213

* Establish a two-way communication channel

214

* Used for WebSocket connections and protocol upgrades

215

* @param url - The URL to connect to

216

* @param options - Connection options

217

* @returns Promise resolving to connection data

218

*/

219

function connect(

220

url: string | URL,

221

options?: Dispatcher.ConnectOptions

222

): Promise<Dispatcher.ConnectData>;

223

224

interface Dispatcher.ConnectOptions extends Dispatcher.DispatchOptions {

225

/** Connection signal for cancellation */

226

signal?: AbortSignal;

227

228

/** Custom dispatcher to use */

229

dispatcher?: Dispatcher;

230

}

231

232

interface Dispatcher.ConnectData {

233

statusCode: number;

234

headers: Record<string, string | string[]>;

235

socket: Duplex;

236

opaque: unknown;

237

}

238

```

239

240

**Usage Examples:**

241

242

```typescript

243

import { connect } from "undici-types";

244

245

// Establish WebSocket connection

246

const { socket, statusCode, headers } = await connect(

247

"ws://localhost:8080/ws",

248

{

249

headers: {

250

"upgrade": "websocket",

251

"connection": "upgrade",

252

"sec-websocket-key": generateWebSocketKey(),

253

"sec-websocket-version": "13"

254

}

255

}

256

);

257

258

console.log(`WebSocket connection: ${statusCode}`);

259

socket.write("Hello WebSocket!");

260

261

socket.on('data', (data) => {

262

console.log('Received:', data.toString());

263

});

264

```

265

266

### Upgrade Function

267

268

Performs HTTP protocol upgrades for advanced protocols.

269

270

```typescript { .api }

271

/**

272

* Perform HTTP protocol upgrade

273

* Used for switching from HTTP to other protocols

274

* @param url - The URL to upgrade

275

* @param options - Upgrade options

276

* @returns Promise resolving to upgrade data

277

*/

278

function upgrade(

279

url: string | URL,

280

options?: Dispatcher.UpgradeOptions

281

): Promise<Dispatcher.UpgradeData>;

282

283

interface Dispatcher.UpgradeOptions extends Dispatcher.DispatchOptions {

284

/** Protocol to upgrade to */

285

upgrade: string;

286

287

/** Upgrade signal for cancellation */

288

signal?: AbortSignal;

289

290

/** Custom dispatcher to use */

291

dispatcher?: Dispatcher;

292

}

293

294

interface Dispatcher.UpgradeData {

295

headers: Record<string, string | string[]>;

296

socket: Duplex;

297

opaque: unknown;

298

}

299

```

300

301

**Usage Examples:**

302

303

```typescript

304

import { upgrade } from "undici-types";

305

306

// Upgrade to HTTP/2

307

const { socket, headers } = await upgrade(

308

"https://example.com/",

309

{

310

upgrade: "h2c",

311

headers: {

312

"connection": "upgrade, http2-settings",

313

"upgrade": "h2c",

314

"http2-settings": generateHttp2Settings()

315

}

316

}

317

);

318

319

// Use upgraded connection

320

socket.write(createHttp2Frame());

321

322

// Upgrade to custom protocol

323

const { socket } = await upgrade(

324

"https://api.example.com/stream",

325

{

326

upgrade: "custom-protocol",

327

headers: {

328

"connection": "upgrade",

329

"upgrade": "custom-protocol",

330

"custom-header": "protocol-data"

331

}

332

}

333

);

334

```

335

336

## Global Dispatcher Management

337

338

Functions for managing the global dispatcher used by convenience functions.

339

340

```typescript { .api }

341

/**

342

* Set the global dispatcher used by convenience functions

343

* @param dispatcher - The dispatcher instance to use globally

344

*/

345

function setGlobalDispatcher(dispatcher: Dispatcher): void;

346

347

/**

348

* Get the current global dispatcher

349

* @returns The current global dispatcher instance

350

*/

351

function getGlobalDispatcher(): Dispatcher;

352

353

/**

354

* Set the global origin for relative URLs

355

* @param origin - The origin to use for relative URLs

356

*/

357

function setGlobalOrigin(origin: string | URL): void;

358

359

/**

360

* Get the current global origin

361

* @returns The current global origin

362

*/

363

function getGlobalOrigin(): string | undefined;

364

```

365

366

**Usage Examples:**

367

368

```typescript

369

import {

370

setGlobalDispatcher,

371

getGlobalDispatcher,

372

setGlobalOrigin,

373

Agent,

374

request

375

} from "undici-types";

376

377

// Set up global configuration

378

const agent = new Agent({ connections: 100 });

379

setGlobalDispatcher(agent);

380

setGlobalOrigin("https://api.example.com");

381

382

// Now convenience functions use the global configuration

383

const response = await request("/users"); // Uses global origin and dispatcher

384

385

// Check current configuration

386

const currentDispatcher = getGlobalDispatcher();

387

console.log(currentDispatcher === agent); // true

388

```