CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-undici-types

A stand-alone types package for Undici HTTP client library

Pending
Overview
Eval results
Files

http-api.mddocs/

HTTP API Functions

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.

Capabilities

Request Function

Performs HTTP requests with promise-based API.

/**
 * Perform an HTTP request using the global dispatcher
 * @param url - The URL to request
 * @param options - Request configuration options
 * @returns Promise resolving to response data
 */
function request(
  url: string | URL,
  options?: Dispatcher.RequestOptions
): Promise<Dispatcher.ResponseData>;

interface Dispatcher.RequestOptions extends Dispatcher.DispatchOptions {
  /** Dispatcher to use instead of global dispatcher */
  dispatcher?: Dispatcher;
  
  /** Maximum number of redirects to follow */
  maxRedirections?: number;
  
  /** Throw error for non-2xx status codes */
  throwOnError?: boolean;
  
  /** Request signal for cancellation */
  signal?: AbortSignal;
}

interface Dispatcher.ResponseData {
  statusCode: number;
  headers: Record<string, string | string[]>;
  body: Readable;
  trailers: Record<string, string>;
  opaque: unknown;
  context: object;
}

Usage Examples:

import { request } from "undici-types";

// Simple GET request
const response = await request("https://api.example.com/users");
console.log(response.statusCode);
console.log(await response.body.text());

// POST request with JSON body
const response = await request("https://api.example.com/users", {
  method: "POST",
  headers: {
    "content-type": "application/json"
  },
  body: JSON.stringify({
    name: "John Doe",
    email: "john@example.com"
  })
});

// Request with custom options
const response = await request("https://api.example.com/data", {
  method: "GET",
  headersTimeout: 10000,
  bodyTimeout: 30000,
  maxRedirections: 5,
  throwOnError: true,
  signal: AbortSignal.timeout(15000)
});

Stream Function

High-performance streaming HTTP requests with custom response handling.

/**
 * Perform a streaming HTTP request with custom response processing
 * Faster alternative to request() for streaming scenarios
 * @param url - The URL to request
 * @param options - Request configuration options
 * @param factory - Function to create response stream processor
 * @returns Promise resolving to processed stream data
 */
function stream(
  url: string | URL,
  options: Dispatcher.RequestOptions,
  factory: Dispatcher.StreamFactory
): Promise<Dispatcher.StreamData>;

interface Dispatcher.StreamFactory {
  (data: {
    statusCode: number;
    headers: Record<string, string | string[]>;
    opaque: unknown;
  }): Writable;
}

interface Dispatcher.StreamData {
  opaque: unknown;
}

Usage Examples:

import { stream } from "undici-types";
import { createWriteStream } from "fs";

// Stream response to file
await stream(
  "https://example.com/large-file.zip",
  { method: "GET" },
  ({ statusCode, headers }) => {
    console.log(`Response: ${statusCode}`);
    console.log(`Content-Length: ${headers['content-length']}`);
    return createWriteStream("./download.zip");
  }
);

// Stream processing with custom transform
await stream(
  "https://api.example.com/stream",
  { method: "GET" },
  ({ statusCode, headers }) => {
    return new Transform({
      transform(chunk, encoding, callback) {
        // Process each chunk
        const processed = processChunk(chunk);
        callback(null, processed);
      }
    });
  }
);

Pipeline Function

Advanced streaming with full control over request and response streams.

/**
 * Create a pipeline for streaming HTTP requests with full stream control
 * @param url - The URL to request
 * @param options - Pipeline configuration options
 * @param handler - Pipeline handler function
 * @returns Promise resolving to pipeline data
 */
function pipeline(
  url: string | URL,
  options: Dispatcher.PipelineOptions,
  handler: Dispatcher.PipelineHandler
): Promise<Dispatcher.PipelineData>;

interface Dispatcher.PipelineOptions extends Dispatcher.RequestOptions {
  /** Object mode for stream */
  objectMode?: boolean;
}

interface Dispatcher.PipelineHandler {
  (data: {
    statusCode: number;
    headers: Record<string, string | string[]>;
    opaque: unknown;
    body: Readable;
  }): Readable | Writable | Transform;
}

interface Dispatcher.PipelineData {
  opaque: unknown;
}

Usage Examples:

import { pipeline } from "undici-types";
import { Transform } from "stream";

// Pipeline with transformation
await pipeline(
  "https://api.example.com/data",
  { method: "GET" },
  ({ statusCode, headers, body }) => {
    console.log(`Status: ${statusCode}`);
    
    return body
      .pipe(new Transform({
        objectMode: true,
        transform(chunk, encoding, callback) {
          const data = JSON.parse(chunk);
          callback(null, JSON.stringify(data.items) + '\n');
        }
      }))
      .pipe(createWriteStream('./processed.jsonl'));
  }
);

Connect Function

Establishes two-way communication channels for protocols like WebSocket.

/**
 * Establish a two-way communication channel
 * Used for WebSocket connections and protocol upgrades
 * @param url - The URL to connect to
 * @param options - Connection options
 * @returns Promise resolving to connection data
 */
function connect(
  url: string | URL,
  options?: Dispatcher.ConnectOptions
): Promise<Dispatcher.ConnectData>;

interface Dispatcher.ConnectOptions extends Dispatcher.DispatchOptions {
  /** Connection signal for cancellation */
  signal?: AbortSignal;
  
  /** Custom dispatcher to use */
  dispatcher?: Dispatcher;
}

interface Dispatcher.ConnectData {
  statusCode: number;
  headers: Record<string, string | string[]>;
  socket: Duplex;
  opaque: unknown;
}

Usage Examples:

import { connect } from "undici-types";

// Establish WebSocket connection
const { socket, statusCode, headers } = await connect(
  "ws://localhost:8080/ws",
  {
    headers: {
      "upgrade": "websocket",
      "connection": "upgrade",
      "sec-websocket-key": generateWebSocketKey(),
      "sec-websocket-version": "13"
    }
  }
);

console.log(`WebSocket connection: ${statusCode}`);
socket.write("Hello WebSocket!");

socket.on('data', (data) => {
  console.log('Received:', data.toString());
});

Upgrade Function

Performs HTTP protocol upgrades for advanced protocols.

/**
 * Perform HTTP protocol upgrade
 * Used for switching from HTTP to other protocols
 * @param url - The URL to upgrade
 * @param options - Upgrade options
 * @returns Promise resolving to upgrade data
 */
function upgrade(
  url: string | URL,
  options?: Dispatcher.UpgradeOptions
): Promise<Dispatcher.UpgradeData>;

interface Dispatcher.UpgradeOptions extends Dispatcher.DispatchOptions {
  /** Protocol to upgrade to */
  upgrade: string;
  
  /** Upgrade signal for cancellation */
  signal?: AbortSignal;
  
  /** Custom dispatcher to use */
  dispatcher?: Dispatcher;
}

interface Dispatcher.UpgradeData {
  headers: Record<string, string | string[]>;
  socket: Duplex;
  opaque: unknown;
}

Usage Examples:

import { upgrade } from "undici-types";

// Upgrade to HTTP/2
const { socket, headers } = await upgrade(
  "https://example.com/",
  {
    upgrade: "h2c",
    headers: {
      "connection": "upgrade, http2-settings",
      "upgrade": "h2c",
      "http2-settings": generateHttp2Settings()
    }
  }
);

// Use upgraded connection
socket.write(createHttp2Frame());

// Upgrade to custom protocol
const { socket } = await upgrade(
  "https://api.example.com/stream",
  {
    upgrade: "custom-protocol",
    headers: {
      "connection": "upgrade",
      "upgrade": "custom-protocol",
      "custom-header": "protocol-data"
    }
  }
);

Global Dispatcher Management

Functions for managing the global dispatcher used by convenience functions.

/**
 * Set the global dispatcher used by convenience functions
 * @param dispatcher - The dispatcher instance to use globally
 */
function setGlobalDispatcher(dispatcher: Dispatcher): void;

/**
 * Get the current global dispatcher
 * @returns The current global dispatcher instance
 */
function getGlobalDispatcher(): Dispatcher;

/**
 * Set the global origin for relative URLs
 * @param origin - The origin to use for relative URLs
 */
function setGlobalOrigin(origin: string | URL): void;

/**
 * Get the current global origin
 * @returns The current global origin
 */
function getGlobalOrigin(): string | undefined;

Usage Examples:

import { 
  setGlobalDispatcher, 
  getGlobalDispatcher,
  setGlobalOrigin,
  Agent,
  request 
} from "undici-types";

// Set up global configuration
const agent = new Agent({ connections: 100 });
setGlobalDispatcher(agent);
setGlobalOrigin("https://api.example.com");

// Now convenience functions use the global configuration
const response = await request("/users"); // Uses global origin and dispatcher

// Check current configuration
const currentDispatcher = getGlobalDispatcher();
console.log(currentDispatcher === agent); // true

Install with Tessl CLI

npx tessl i tessl/npm-undici-types

docs

connection-management.md

cookies.md

error-handling.md

http-api.md

http-clients.md

index.md

interceptors.md

testing-mocking.md

utilities.md

web-standards.md

tile.json