### Browser Usage: LibcurlClient Initialization and HTTP/WebSocket Requests (HTML/JavaScript)
Source: https://context7.com/mercuryworkshop/libcurl-transport/llms.txt
This snippet shows how to initialize LibcurlClient in a browser using its UMD build. It includes examples for making HTTP GET requests and establishing WebSocket connections, demonstrating the library's capabilities for both standard API calls and real-time communication.
```html
Libcurl Transport Demo
Proxy Transport Demo
```
--------------------------------
### Execute HTTP Requests with LibcurlClient
Source: https://context7.com/mercuryworkshop/libcurl-transport/llms.txt
Demonstrates how to use the LibcurlClient's request method to perform GET and POST HTTP requests. It includes examples of setting custom headers, providing request bodies, using abort signals for timeouts, and handling responses. The client must be initialized with a WebSocket endpoint before making requests.
```javascript
import { LibcurlClient } from "@mercuryworkshop/libcurl-transport";
const client = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/"
});
await client.init();
// GET request with custom headers
const getUrl = new URL("https://api.example.com/data");
const getHeaders = [
["User-Agent", "LibcurlTransport/2.0"],
["Accept", "application/json"],
["Authorization", "Bearer token123"]
];
const getResponse = await client.request(
getUrl,
"GET",
null,
getHeaders,
undefined
);
console.log("Status:", getResponse.status); // 200
console.log("Headers:", getResponse.headers); // Raw header array
const data = await getResponse.body.json();
console.log("Data:", data);
// POST request with JSON body and abort signal
const controller = new AbortController();
const postUrl = new URL("https://api.example.com/submit");
const postHeaders = [
["Content-Type", "application/json"],
["Accept", "application/json"]
];
const postBody = JSON.stringify({
username: "user123",
action: "create"
});
setTimeout(() => controller.abort(), 5000); // 5 second timeout
try {
const postResponse = await client.request(
postUrl,
"POST",
postBody,
postHeaders,
controller.signal
);
console.log("Response status:", postResponse.status);
console.log("Response statusText:", postResponse.statusText);
if (postResponse.status === 201) {
const result = await postResponse.body.json();
console.log("Created:", result);
}
} catch (error) {
if (error.name === "AbortError") {
console.error("Request aborted");
} else {
console.error("Request failed:", error);
}
}
// Handling redirects (manual mode)
const redirectUrl = new URL("https://example.com/redirect");
const redirectResponse = await client.request(
redirectUrl,
"GET",
null,
[["User-Agent", "LibcurlTransport"]],
undefined
);
if ([301, 302, 307, 308].includes(redirectResponse.status)) {
const locationHeader = redirectResponse.headers.find(
([key]) => key.toLowerCase() === "location"
);
console.log("Redirect to:", locationHeader[1]);
}
```
--------------------------------
### Initialize libcurl.js Session
Source: https://context7.com/mercuryworkshop/libcurl-transport/llms.txt
Initializes the libcurl.js session asynchronously. This involves loading the WebAssembly module, setting up the WebSocket tunnel endpoint, and configuring connection pool parameters. It must be called before making any requests to ensure the underlying libcurl library is ready and the HTTP session is properly configured. Includes example with timeout handling.
```javascript
import { LibcurlClient } from "@mercuryworkshop/libcurl-transport";
const client = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/",
connections: [60, 50, 6]
});
// Initialize before making requests
await client.init();
if (client.ready) {
console.log("Client initialized successfully");
// Proceed with requests
} else {
console.error("Client failed to initialize");
}
// Using with error handling and timeout
const clientWithTimeout = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/"
});
try {
const initPromise = clientWithTimeout.init();
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Initialization timeout")),
10000)
);
await Promise.race([initPromise, timeoutPromise]);
console.log("libcurl.js ready:", clientWithTimeout.ready);
} catch (error) {
console.error("Initialization failed:", error.message);
}
```
--------------------------------
### Initialize LibcurlClient with Wisp Transport (HTML Script)
Source: https://github.com/mercuryworkshop/libcurl-transport/blob/master/README.md
Shows how to initialize the LibcurlClient using the non-ESM build included in an HTML script tag. This method is useful for projects not using module bundlers.
```javascript
```
--------------------------------
### Establish WebSocket Connection with LibcurlClient
Source: https://context7.com/mercuryworkshop/libcurl-transport/llms.txt
This snippet demonstrates establishing a WebSocket connection using LibcurlClient. It covers initialization, connection parameters like URL, protocols, and headers, and event handlers for open, message, close, and error events. It also shows how to send different message types and gracefully close the connection.
```javascript
import { LibcurlClient } from "@mercuryworkshop/libcurl-transport";
const client = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/"
});
await client.init();
// WebSocket connection with event handlers
const wsUrl = new URL("wss://echo.example.com/socket");
const protocols = ["echo-protocol"];
const headers = [
["Origin", "https://myapp.example.com"],
["User-Agent", "LibcurlTransport/2.0"]
];
let sendMessage, closeConnection;
[sendMessage, closeConnection] = client.connect(
wsUrl,
protocols,
headers,
// onopen
(protocol, extensions) => {
console.log("WebSocket opened");
console.log("Selected protocol:", protocol);
console.log("Extensions:", extensions);
// Send initial message
sendMessage("Hello, WebSocket!");
},
// onmessage
(data) => {
if (typeof data === "string") {
console.log("Text message:", data);
} else if (data instanceof ArrayBuffer) {
console.log("Binary message:", new Uint8Array(data));
} else if (data instanceof Blob) {
console.log("Blob message:", data.size, "bytes");
}
},
// onclose
(code, reason) => {
console.log("WebSocket closed");
console.log("Code:", code);
console.log("Reason:", reason);
},
// onerror
(error) => {
console.error("WebSocket error:", error);
}
);
// Send different message types
sendMessage("Text message");
sendMessage(new ArrayBuffer(8));
sendMessage(new Blob(["data"]));
// Close connection gracefully after 30 seconds
setTimeout(() => {
closeConnection(1000, "Normal closure");
}, 30000);
// Example: Chat application WebSocket
const chatUrl = new URL("wss://chat.example.com/ws");
const [chatSend, chatClose] = client.connect(
chatUrl,
[],
[["Authorization", "Bearer chatToken123"]],
(protocol, extensions) => {
console.log("Connected to chat server");
chatSend(JSON.stringify({ type: "join", room: "general" }));
},
(data) => {
const message = JSON.parse(data);
console.log(`[${message.user}]: ${message.text}`);
// Auto-respond to pings
if (message.type === "ping") {
chatSend(JSON.stringify({ type: "pong" }));
}
},
(code, reason) => {
console.log(`Chat disconnected: ${code} - ${reason}`);
// Implement reconnection logic
},
(error) => {
console.error("Chat error:", error);
}
);
// Send chat message
chatSend(JSON.stringify({
type: "message",
text: "Hello everyone!",
timestamp: Date.now()
}));
```
--------------------------------
### init Method
Source: https://context7.com/mercuryworkshop/libcurl-transport/llms.txt
Initializes the libcurl.js session by loading the WebAssembly module, setting up the WebSocket tunnel endpoint, and configuring connection pool parameters. This asynchronous method must be called before making any requests.
```APIDOC
## init Method
### Description
Initializes the libcurl.js session by loading the WebAssembly module, setting up the WebSocket tunnel endpoint, and configuring connection pool parameters. This asynchronous method must be called before making any requests, ensuring the underlying libcurl library is ready and the HTTP session is properly configured.
### Method
`init()`
### Endpoint
N/A (Instance method)
### Parameters
None
### Request Example
```javascript
import { LibcurlClient } from "@mercuryworkshop/libcurl-transport";
const client = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/",
connections: [60, 50, 6]
});
// Initialize before making requests
await client.init();
if (client.ready) {
console.log("Client initialized successfully");
// Proceed with requests
} else {
console.error("Client failed to initialize");
}
// Using with error handling and timeout
const clientWithTimeout = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/"
});
try {
const initPromise = clientWithTimeout.init();
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Initialization timeout")), 10000)
);
await Promise.race([initPromise, timeoutPromise]);
console.log("libcurl.js ready:", clientWithTimeout.ready);
} catch (error) {
console.error("Initialization failed:", error.message);
}
```
### Response
#### Success Response (void)
This method does not return a value upon successful completion. It modifies the client instance state.
#### Response Example
```json
// No direct JSON response.
// Success is indicated by the client.ready property becoming true.
```
```
--------------------------------
### Initialize LibcurlClient with WsProxy Transport (JavaScript)
Source: https://github.com/mercuryworkshop/libcurl-transport/blob/master/README.md
Illustrates initializing the LibcurlClient to use the wsproxy transport instead of Wisp. Wsproxy treats each TCP connection as a separate WebSocket.
```javascript
import { LibcurlClient } from "@mercuryworkshop/libcurl-transport";
let client = new LibcurlClient({ websocket: "wss://example.com/wisp/", transport: "wsproxy" });
```
--------------------------------
### Initialize LibcurlClient with Wisp Transport (JavaScript)
Source: https://github.com/mercuryworkshop/libcurl-transport/blob/master/README.md
Demonstrates how to initialize the LibcurlClient for encrypted traffic using the Wisp transport. The Wisp proxy server is specified via the 'websocket' option.
```javascript
import { LibcurlClient } from "@mercuryworkshop/libcurl-transport";
let client = new LibcurlClient({ websocket: "wss://example.com/wisp/" });
// pass to proxy
```
--------------------------------
### Initialize Libcurl Transport Client
Source: https://context7.com/mercuryworkshop/libcurl-transport/llms.txt
Constructs a new libcurl transport client. It takes WebSocket server details and connection options. The constructor validates the WebSocket URL format and proxy protocol support, initializing the session configuration. It supports Wisp and wsproxy transport modes, and can be configured with additional proxy settings like SOCKS5h.
```javascript
import { LibcurlClient } from "@mercuryworkshop/libcurl-transport";
// Basic Wisp configuration
const client = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/"
});
// Wsproxy mode with connection limits
const wsproxyclient = new LibcurlClient({
websocket: "wss://proxy.example.com/wsproxy/",
transport: "wsproxy",
connections: [30, 20, 1] // [max_active, cache_limit, per_host_limit]
});
// With additional SOCKS5 proxy
const proxiedClient = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/",
proxy: "socks5h://localhost:1080"
});
// Error handling for invalid configuration
try {
const invalidClient = new LibcurlClient({
websocket: "wss://example.com/wisp" // Missing trailing slash
});
} catch (error) {
console.error("Configuration error:", error.message);
// "The Websocket URL must end with a trailing forward slash."
}
```
--------------------------------
### LibcurlClient Constructor
Source: https://context7.com/mercuryworkshop/libcurl-transport/llms.txt
Creates a new libcurl transport client instance configured with WebSocket proxy server details and connection options. Validates WebSocket URL format, proxy protocol support, and initializes session configuration.
```APIDOC
## LibcurlClient Constructor
### Description
Creates a new libcurl transport client instance configured with WebSocket proxy server details and connection options. The constructor validates WebSocket URL format, proxy protocol support, and initializes the session configuration for subsequent HTTP and WebSocket operations.
### Method
`constructor`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **websocket** (string) - Required - The WebSocket URL for the proxy server (e.g., "wss://proxy.example.com/wisp/"). Must end with a trailing forward slash.
- **transport** (string) - Optional - The transport mode. Can be "wisp" (default) or "wsproxy".
- **connections** (array) - Optional - An array of numbers specifying connection pool limits: `[max_active, cache_limit, per_host_limit]`. Example: `[30, 20, 1]`.
- **proxy** (string) - Optional - The URL for an upstream proxy server (e.g., "socks5h://localhost:1080").
### Request Example
```javascript
import { LibcurlClient } from "@mercuryworkshop/libcurl-transport";
// Basic Wisp configuration
const client = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/"
});
// Wsproxy mode with connection limits
const wsproxyclient = new LibcurlClient({
websocket: "wss://proxy.example.com/wsproxy/",
transport: "wsproxy",
connections: [30, 20, 1]
});
// With additional SOCKS5 proxy
const proxiedClient = new LibcurlClient({
websocket: "wss://proxy.example.com/wisp/",
proxy: "socks5h://localhost:1080"
});
// Error handling for invalid configuration
try {
const invalidClient = new LibcurlClient({
websocket: "wss://example.com/wisp" // Missing trailing slash
});
} catch (error) {
console.error("Configuration error:", error.message);
// "The Websocket URL must end with a trailing forward slash."
}
```
### Response
#### Success Response (Instance)
- **LibcurlClient** (object) - An instance of the LibcurlClient.
#### Response Example
```json
// No direct JSON response, returns a client instance.
// Example of successful instantiation:
// const client = new LibcurlClient({ websocket: "wss://proxy.example.com/wisp/" });
```
```
--------------------------------
### Configure Connection Limits for LibcurlClient (JavaScript)
Source: https://github.com/mercuryworkshop/libcurl-transport/blob/master/README.md
Demonstrates how to set the maximum number of open connections for libcurl.js using the 'connections' option. This option is passed directly to libcurl.js's HTTPSession.set_connections.
```javascript
let client = new LibcurlClient({ websocket: "wss://example.com/wsproxy/", connections: [30, 20, 1] })
```
--------------------------------
### connect Method - WebSocket Connection
Source: https://context7.com/mercuryworkshop/libcurl-transport/llms.txt
Establishes a WebSocket connection with specified protocols, custom headers, and event handlers for connection lifecycle events (open, message, close, error).
```APIDOC
## POST /mercuryworkshop/libcurl-transport/connect
### Description
Establishes a WebSocket connection through an encrypted proxy tunnel. Supports protocol negotiation, custom headers, and bidirectional message streaming. Returns functions to send messages and close the connection, along with callbacks for connection events.
### Method
POST
### Endpoint
`/mercuryworkshop/libcurl-transport/connect`
### Parameters
#### Query Parameters
- **websocket** (string) - Required - The WebSocket URL for the proxy.
#### Request Body
- **wsUrl** (URL) - Required - The target WebSocket endpoint.
- **protocols** (string[]) - Optional - An array of supported WebSocket sub-protocols.
- **headers** (string[][]) - Optional - An array of custom headers to send with the connection request.
- **onopen** (function) - Optional - Callback function executed when the connection opens. Receives selected protocol and extensions.
- **onmessage** (function) - Optional - Callback function executed when a message is received. Receives message data (string, ArrayBuffer, or Blob).
- **onclose** (function) - Optional - Callback function executed when the connection closes. Receives closure code and reason.
- **onerror** (function) - Optional - Callback function executed when an error occurs. Receives the error object.
### Request Example
```javascript
const client = new LibcurlClient({ websocket: "wss://proxy.example.com/wisp/" });
await client.init();
const wsUrl = new URL("wss://echo.example.com/socket");
const protocols = ["echo-protocol"];
const headers = [
["Origin", "https://myapp.example.com"],
["User-Agent", "LibcurlTransport/2.0"]
];
let sendMessage, closeConnection;
[sendMessage, closeConnection] = client.connect(
wsUrl,
protocols,
headers,
(protocol, extensions) => {
console.log("WebSocket opened");
sendMessage("Hello, WebSocket!");
},
(data) => {
console.log("Message received:", data);
},
(code, reason) => {
console.log("WebSocket closed");
},
(error) => {
console.error("WebSocket error:", error);
}
);
// To send a message:
sendMessage("My message");
// To close the connection:
// closeConnection(1000, "Normal closure");
```
### Response
#### Success Response (200)
- **sendMessage** (function) - A function to send messages over the WebSocket.
- **closeConnection** (function) - A function to close the WebSocket connection.
#### Response Example
```json
{
"sendMessage": "function",
"closeConnection": "function"
}
```
```
--------------------------------
### HTTP Request Method
Source: https://context7.com/mercuryworkshop/libcurl-transport/llms.txt
Executes HTTP requests through the encrypted proxy tunnel, supporting all standard HTTP methods with custom headers, request body, and abort signals. The method transforms proxy-transports format requests into libcurl.js fetch calls, handling redirect behavior and returning standardized response objects with raw headers, status codes, and response bodies.
```APIDOC
## POST /request
### Description
Executes HTTP requests through the encrypted proxy tunnel, supporting all standard HTTP methods with custom headers, request body, and abort signals. The method transforms proxy-transports format requests into libcurl.js fetch calls, handling redirect behavior and returning standardized response objects with raw headers, status codes, and response bodies.
### Method
POST
### Endpoint
/request
### Parameters
#### Request Body
- **url** (URL) - Required - The URL to make the request to.
- **method** (string) - Required - The HTTP method to use (e.g., 'GET', 'POST').
- **body** (string) - Optional - The request body, if any.
- **headers** (Array>) - Optional - An array of header key-value pairs.
- **signal** (AbortSignal) - Optional - An AbortSignal to cancel the request.
### Request Example
```json
{
"url": "https://api.example.com/data",
"method": "GET",
"headers": [
["User-Agent", "LibcurlTransport/2.0"],
["Accept", "application/json"]
]
}
```
### Response
#### Success Response (200)
- **status** (number) - The HTTP status code of the response.
- **headers** (Array>) - An array of raw header key-value pairs.
- **body** (ReadableStream) - The response body as a stream.
#### Response Example
```json
{
"status": 200,
"headers": [
["Content-Type", "application/json"]
],
"body": "{ \"message\": \"success\" }"
}
```
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.