### Install build dependencies on Debian-based systems Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Command to install required build tools and libraries on Debian or Ubuntu. ```bash sudo apt install python3 make cmake emscripten autoconf automake libtool pkg-config wget xxd jq ``` -------------------------------- ### Import libcurl.js as ES6 Module Source: https://github.com/ading2210/libcurl.js/blob/main/website/index.html Use the library as an ES6 module when installed via NPM. ```javascript import { libcurl } from "libcurl.js/bundled"; ``` -------------------------------- ### Get Error String from Code Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Retrieves the human-readable error string corresponding to a given libcurl error code. ```javascript console.log(libcurl.get_error_string(56)); ``` -------------------------------- ### Configure libcurl.set_websocket Proxy URL Source: https://context7.com/ading2210/libcurl.js/llms.txt Set the WebSocket proxy URL for libcurl.js to tunnel TCP connections. This must be called before making requests. The URL must end with a trailing slash. Examples include Wisp protocol and local development servers. ```javascript // Set the Wisp protocol proxy URL libcurl.set_websocket("wss://your-server.com/ws/"); // Using a local development server libcurl.set_websocket("ws://localhost:6001/"); // Get current proxy URL console.log(libcurl.websocket_url); ``` ```javascript // Common pattern: set proxy based on current page location document.addEventListener("libcurl_load", () => { const proxyUrl = `wss://${location.hostname}/ws/`; libcurl.set_websocket(proxyUrl); }); // Now requests can be made const response = await libcurl.fetch("https://api.example.com/data"); ``` -------------------------------- ### Initialize libcurl.js Source: https://github.com/ading2210/libcurl.js/blob/main/client/use_bundled.html Asynchronously load the libcurl WebAssembly module and verify readiness. ```javascript async function main() { console.log("libcurl.js ready?", libcurl.ready); console.log("waiting for wasm load"); await libcurl.load_wasm(); console.log("libcurl.js ready?", libcurl.ready); console.log("loaded libcurl.js", libcurl.version.lib); } ``` -------------------------------- ### Build libcurl.js from source Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Commands to clone the repository and execute the build script. ```bash git clone https://github.com/ading2210/libcurl.js --recursive cd libcurl.js/client ./build.sh ``` -------------------------------- ### Use libcurl.onload callback Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Assign a callback function to handle library readiness, useful for web worker environments. ```javascript libcurl.onload = () => { console.log("libcurl.js ready!"); } ``` -------------------------------- ### Initialize WebSocket and Log libcurl.js Version Source: https://github.com/ading2210/libcurl.js/blob/main/client/index.html This snippet listens for the 'libcurl_load' event to set up a WebSocket connection using the current page's URL and logs the loaded libcurl.js version. Ensure libcurl.js is loaded before this script executes. ```javascript document.addEventListener("libcurl_load", ()=>{ libcurl.set_websocket(location.href.replace("http", "ws")); console.log(`loaded libcurl.js v${libcurl.version.lib}`); }); ``` -------------------------------- ### Initialize and execute libcurl.js unit tests Source: https://github.com/ading2210/libcurl.js/blob/main/client/tests/index.html Sets up the WebSocket connection and dynamically fetches and executes test scripts based on the URL hash. ```javascript function create_flag(result) { let element = document.createElement("div"); element.setAttribute("result", result); element.className = "flag"; document.body.append(element); } function assert(condition, message) { if (!condition) { throw new Error(message || "Assertion failed"); } } document.addEventListener("libcurl_load", async ()=>{ try { libcurl.set_websocket(`ws://localhost:6001/ws/`); let r = await fetch("/tests/scripts/" + location.hash.substring(1)); eval(await r.text()); await test(); create_flag("success"); } catch (e) { console.error(e.stack || e); create_flag("error"); } }); ``` -------------------------------- ### Initialize libcurl.js in HTML Source: https://context7.com/ading2210/libcurl.js/llms.txt Load the library via CDN and initialize the WASM module before configuring the WebSocket proxy. ```html ``` -------------------------------- ### Initialize libcurl.js via HTML script tag Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Load the library and initialize the WASM module using the onload attribute. ```html ``` -------------------------------- ### Initialize libcurl.js asynchronously Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Await the WASM loading process before executing library functions. ```javascript async function main() { await libcurl.load_wasm("/out/libcurl.wasm"); console.log(await libcurl.fetch("https://ading.dev/")); } main(); ``` -------------------------------- ### Initialize libcurl.js Worker and Fetch Data Source: https://github.com/ading2210/libcurl.js/blob/main/client/worker.html Sets up the libcurl.js worker, configures WebSocket, posts initial messages, and performs an HTTP fetch request. Ensure libcurl.js and its WASM file are loaded. ```javascript importScripts( `${location.origin}/out/libcurl.js` ); async function main() { libcurl.set_websocket( `${location.origin.replace("http", "ws")}/ `); self.postMessage("loaded libcurl.js v" + libcurl.version.lib); let r = await libcurl.fetch("https://ifconfig.me/all", { _libcurl_verbose: 1 }); self.postMessage(await r.text()); } libcurl.onload = main; libcurl.stdout = self.postMessage; libcurl.stderr = self.postMessage; libcurl.load_wasm( `${location.origin}/out/libcurl.wasm` ); ``` -------------------------------- ### Handle libcurl load events Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Listen for the libcurl_load event to perform initialization tasks once the library is ready. ```javascript document.addEventListener("libcurl_load", ()=>{ libcurl.set_websocket(`wss://${location.hostname}/ws/`); console.log("libcurl.js ready!"); }); ``` -------------------------------- ### Run libcurl.js Proxy Server Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Clone the repository, navigate to the directory, and run the server script with the static client path. Refer to the wisp-server-python documentation for additional arguments. ```bash git clone https://github.com/ading2210/libcurl.js --recursive cd libcurl.js server/run.sh --static=./client ``` -------------------------------- ### Create and Use a TLS Socket Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Demonstrates creating a TLS socket, connecting to a host, sending an HTTP request, and logging the response. Ensure the host and port are correct for your target server. ```javascript let socket = new libcurl.TLSSocket("ading.dev", 443, {verbose: 1}); socket.onopen = () => { console.log("socket connected!"); let str = "GET / HTTP/1.1\r\nHost: ading.dev\r\nConnection: close\r\n\r\n"; socket.send(new TextEncoder().encode(str)); }; socket.onmessage = (data) => { console.log(new TextDecoder().decode(data)); }; ``` -------------------------------- ### Include libcurl.js via Script Tag Source: https://github.com/ading2210/libcurl.js/blob/main/website/index.html Load the library directly into a webpage using a script tag. ```html ``` -------------------------------- ### Import libcurl.js as an ES6 Module Source: https://context7.com/ading2210/libcurl.js/llms.txt Use the regular version for manual WASM loading or the bundled version for an all-in-one approach. ```javascript // Regular version - requires separate WASM loading import { libcurl } from "libcurl.js"; await libcurl.load_wasm("/path/to/libcurl.wasm"); libcurl.set_websocket("wss://proxy.example.com/ws/"); // Bundled version - WASM included in JS (no separate load needed) import { libcurl } from "libcurl.js/bundled"; await libcurl.load_wasm(); // Still call this to wait for initialization libcurl.set_websocket("wss://proxy.example.com/ws/"); const response = await libcurl.fetch("https://api.example.com/data"); const data = await response.json(); console.log(data); ``` -------------------------------- ### Establish Basic WebSocket Connection Source: https://context7.com/ading2210/libcurl.js/llms.txt Create a WebSocket connection to a server and handle events like opening, receiving messages, closing, and errors. Supports sending text and binary data. ```javascript const ws = new libcurl.CurlWebSocket("wss://echo.websocket.org/"); ws.onopen = () => { console.log("Connected!"); ws.send("Hello, WebSocket!"); ws.send(new Uint8Array([1, 2, 3, 4])); // Binary data }; ws.onmessage = (data) => { if (typeof data === "string") { console.log("Text message:", data); } else { console.log("Binary message:", data); // Uint8Array } }; ws.onclose = () => { console.log("Connection closed cleanly"); }; ws.onerror = (errorCode) => { console.error("WebSocket error:", libcurl.get_error_string(errorCode)); }; // Close when done setTimeout(() => ws.close(), 10000); ``` -------------------------------- ### Handle Lifecycle Events Source: https://context7.com/ading2210/libcurl.js/llms.txt Listen for library initialization and error events using DOM listeners, EventTarget, or callbacks. ```javascript // DOM event listener (works in main thread) document.addEventListener("libcurl_load", () => { console.log("libcurl.js loaded successfully"); }); document.addEventListener("libcurl_abort", (event) => { console.error("libcurl.js crashed:", event.detail); }); // EventTarget-based events (works in Web Workers) libcurl.events.addEventListener("libcurl_load", () => { console.log("Ready in worker!"); }); libcurl.events.addEventListener("libcurl_abort", (event) => { console.error("Crash in worker:", event.detail); }); // Callback-based (simplest for Web Workers) libcurl.onload = () => { console.log("libcurl.js initialized"); postMessage({ type: "ready" }); }; // Promise-based loading async function init() { try { await libcurl.load_wasm("/libcurl.wasm"); console.log("WASM loaded"); } catch (error) { console.error("Failed to load WASM:", error); } } ``` -------------------------------- ### Create and Use an HTTP Session Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Instantiate an HTTPSession, set a base URL, perform a fetch request, and close the session. Ensure session.close() is called to prevent memory leaks. ```javascript let session = new libcurl.HTTPSession(); session.base_url = "https://ading.dev"; let r = await session.fetch("/projects/"); console.log(await r.text()); session.close(); ``` -------------------------------- ### Enable Verbose Output and Logging Source: https://context7.com/ading2210/libcurl.js/llms.txt Configure request-level verbosity and global logging handlers for debugging TLS and connection issues. ```javascript // Enable verbose mode for individual requests const response = await libcurl.fetch("https://example.com", { _libcurl_verbose: 1 }); // Custom stdout/stderr handlers libcurl.stderr = (text) => { console.debug("[libcurl]", text); }; libcurl.stdout = (text) => { console.log("[output]", text); }; // Custom logger for all libcurl.js messages libcurl.logger = (type, text) => { // type is "log", "warn", or "error" switch (type) { case "error": console.error("[libcurl error]", text); break; case "warn": console.warn("[libcurl warn]", text); break; default: console.log("[libcurl]", text); } }; // Useful in Web Workers where console may not be available libcurl.logger = (type, text) => { postMessage({ type: "log", level: type, message: text }); }; ``` -------------------------------- ### Create and Use Basic HTTP Session Source: https://context7.com/ading2210/libcurl.js/llms.txt Instantiate an isolated HTTP session for managing connections, cookies, and settings. Always ensure to call `close()` on the session when it's no longer needed. ```javascript const session = new libcurl.HTTPSession(); const response = await session.fetch("https://example.com"); console.log(await response.text()); session.close(); // Important: always close sessions ``` -------------------------------- ### WebSocket with Subprotocols and Options Source: https://context7.com/ading2210/libcurl.js/llms.txt Configure a WebSocket connection with specific subprotocols, custom headers, verbose logging, and proxy settings for advanced use cases. ```javascript const wsWithOptions = new libcurl.CurlWebSocket( "wss://api.example.com/socket", ["graphql-ws", "subscriptions-transport-ws"], // Subprotocols { headers: { "Authorization": "Bearer token123", "X-Client-Version": "1.0.0" }, verbose: true, // Enable libcurl debug output proxy: "socks5h://127.0.0.1:1080" } ); wsWithOptions.onopen = () => { wsWithOptions.send(JSON.stringify({ type: "connection_init", payload: {} })); }; wsWithOptions.onmessage = (data) => { const msg = JSON.parse(data); console.log("GraphQL message:", msg); }; ``` -------------------------------- ### Access Utility Functions Source: https://context7.com/ading2210/libcurl.js/llms.txt Retrieve library version information, resolve error codes, and access CA certificate bundles. ```javascript // Get version information console.log(libcurl.version); // { // lib: "0.7.4", // libcurl.js version // wisp: "1.0.0", // Wisp client version // curl: "8.10.1", // curl version // mbedtls: "3.6.0", // Mbed TLS version // nghttp2: "1.62.0", // nghttp2 version // brotli: "1.1.0" // Brotli version // } // Check if WASM is loaded if (libcurl.ready) { console.log("libcurl.js is ready"); } // Get error string from error code const errorMessage = libcurl.get_error_string(56); console.log(errorMessage); // "Failure when receiving data from the peer" // Common error codes: // 6 = Couldn't resolve host // 7 = Failed to connect // 28 = Operation timeout // 35 = SSL connect error // 56 = Failure when receiving data // Get CA certificate bundle (PEM format) const caCerts = libcurl.get_cacert(); console.log(caCerts.substring(0, 100)); // -----BEGIN CERTIFICATE-----... // Access copyright notice console.log(libcurl.copyright); ``` -------------------------------- ### Establish libcurl.TLSSocket Connection Source: https://context7.com/ading2210/libcurl.js/llms.txt Create raw TLS socket connections for custom protocols. Handles connection events like open, message, close, and error. Data is received as Uint8Array. Supports verbose output and proxy configuration. ```javascript // Basic TLS socket connection const socket = new libcurl.TLSSocket("example.com", 443); socket.onopen = () => { console.log("TLS connection established"); // Send raw HTTP request const request = "GET / HTTP/1.1\r\n" + "Host: example.com\r\n" + "Connection: close\r\n\r\n"; socket.send(new TextEncoder().encode(request)); }; socket.onmessage = (data) => { // data is always Uint8Array const text = new TextDecoder().decode(data); console.log("Received:", text); }; socket.onclose = () => { console.log("Socket closed"); }; socket.onerror = (errorCode) => { console.error("Socket error:", libcurl.get_error_string(errorCode)); }; ``` ```javascript // TLS socket with verbose output and proxy const secureSocket = new libcurl.TLSSocket("cloudflare.com", 443, { verbose: true, proxy: "socks5h://127.0.0.1:9050" }); secureSocket.onopen = () => { // Verify TLS version const request = "GET /cdn-cgi/trace HTTP/1.1\r\n" + "Host: cloudflare.com\r\n" + "Connection: close\r\n\r\n"; secureSocket.send(new TextEncoder().encode(request)); }; secureSocket.onmessage = (data) => { const response = new TextDecoder().decode(data); if (response.includes("tls=TLSv1.3")) { console.log("TLS 1.3 connection confirmed!"); } }; ``` ```javascript // Custom protocol implementation example class CustomProtocol { constructor(host, port) { this.socket = new libcurl.TLSSocket(host, port); this.messageQueue = []; this.socket.onopen = () => this.onConnected(); this.socket.onmessage = (data) => this.handleData(data); this.socket.onerror = (err) => this.handleError(err); } onConnected() { // Send protocol handshake const handshake = new Uint8Array([0x01, 0x00, 0x00, 0x00]); this.socket.send(handshake); } handleData(data) { this.messageQueue.push(data); } handleError(errorCode) { console.error("Protocol error:", libcurl.get_error_string(errorCode)); } close() { this.socket.close(); } } ``` -------------------------------- ### Create a WebSocket Connection with CurlWebSocket Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Establish a WebSocket connection using CurlWebSocket, setting up event handlers for open, message, and error events. Send data after connection is open. The verbose option logs libcurl output. ```javascript let ws = new libcurl.CurlWebSocket("wss://echo.websocket.org/", [], {verbose: 1}); ws.onopen = () => { console.log("ws connected!"); ws.send("hello".repeat(100)); }; ws.onmessage = (data) => { console.log(data); }; ``` -------------------------------- ### Perform HTTP requests with libcurl.fetch Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Execute HTTP requests using the fetch-compatible API and process the response. ```javascript let r = await libcurl.fetch("https://ading.dev"); console.log(await r.text()); ``` -------------------------------- ### Create a WebSocket Connection with libcurl.WebSocket Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Utilize the libcurl.WebSocket object, which mirrors the standard WebSocket API. Add event listeners for 'open' and 'message' events to handle connection and data reception. ```javascript let ws = new libcurl.WebSocket("wss://echo.websocket.org/"); ws.addEventListener("open", () => { console.log("ws connected!"); ws.send("hello".repeat(128)); }); ws.addEventListener("message", (event) => { console.log(event.data); }); ``` -------------------------------- ### libcurl.fetch Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Performs an HTTP request with optional configuration for verbosity and HTTP version. ```APIDOC ## libcurl.fetch ### Description Performs a fetch request. Supports additional libcurl-specific options. ### Parameters - **url** (string) - Required - The URL to fetch. - **options** (object) - Optional - Includes '_libcurl_verbose' (number) and '_libcurl_http_version' (number: 1.0, 1.1, or 2.0). ``` -------------------------------- ### HTTP Session with Proxy Configuration Source: https://context7.com/ading2210/libcurl.js/llms.txt Set up an HTTP session to route traffic through a specified proxy server, such as a SOCKS5 proxy for anonymity. ```javascript const proxiedSession = new libcurl.HTTPSession({ proxy: "socks5h://127.0.0.1:9050" }); await proxiedSession.fetch("https://check.torproject.org"); proxiedSession.close(); ``` -------------------------------- ### Fetch with Verbose Output Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Fetches a URL and enables verbose libcurl output, similar to `curl -v`. By default, output is printed to the browser console. ```javascript await libcurl.fetch("https://example.com", {_libcurl_verbose: 1}); ``` -------------------------------- ### CDN resource URLs Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Direct URLs for loading the library and WASM files from a third-party CDN. ```text https://cdn.jsdelivr.net/npm/libcurl.js@0.7.1/libcurl.js https://cdn.jsdelivr.net/npm/libcurl.js@0.7.1/libcurl.wasm ``` -------------------------------- ### Perform HTTP Requests with libcurl.fetch Source: https://context7.com/ading2210/libcurl.js/llms.txt Execute various types of HTTP requests using the Fetch API-compatible interface, including support for custom headers, bodies, and abort signals. ```javascript // Basic GET request const response = await libcurl.fetch("https://example.com"); console.log("Status:", response.status); // 200 console.log("OK:", response.ok); // true console.log(await response.text()); // GET request with custom headers const r = await libcurl.fetch("https://httpbin.org/get", { headers: { "Authorization": "Bearer token123", "X-Custom-Header": "value" } }); const json = await r.json(); console.log(json.headers); // POST request with JSON body const postResponse = await libcurl.fetch("https://httpbin.org/post", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: "test", value: 42 }) }); console.log(await postResponse.json()); // POST with Blob body const blobResponse = await libcurl.fetch("https://httpbin.org/anything", { method: "POST", body: new Blob(["hello world"], { type: "text/plain" }) }); // Using Request object const request = new Request("https://httpbin.org/get", { headers: new Headers({ "X-Test-Header": "1" }) }); const r2 = await libcurl.fetch(request); // Abort request with AbortController const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); try { await libcurl.fetch("https://slow-api.example.com/data", { signal: controller.signal }); } catch (e) { if (e.name === "AbortError") { console.log("Request was aborted"); } } // Access raw headers (for duplicate headers) const resp = await libcurl.fetch("https://example.com"); console.log(resp.raw_headers); // [["header-name", "value"], ...] // Using proxy server (SOCKS5, SOCKS4, HTTP) const proxiedResponse = await libcurl.fetch("https://example.com", { proxy: "socks5h://127.0.0.1:1080" }); ``` -------------------------------- ### Implement libcurl.js in a Web Worker Source: https://context7.com/ading2210/libcurl.js/llms.txt Configures a Web Worker to handle network requests using libcurl.js and provides a main thread interface for communication. ```javascript // worker.js importScripts("https://cdn.jsdelivr.net/npm/libcurl.js@0.7.4/libcurl.js"); libcurl.onload = () => { libcurl.set_websocket("wss://proxy.example.com/ws/"); postMessage({ type: "ready" }); }; libcurl.load_wasm("https://cdn.jsdelivr.net/npm/libcurl.js@0.7.4/libcurl.wasm"); self.onmessage = async (event) => { if (event.data.type === "fetch") { try { const response = await libcurl.fetch(event.data.url, event.data.options); const data = await response.json(); postMessage({ type: "response", data, id: event.data.id }); } catch (error) { postMessage({ type: "error", error: error.message, id: event.data.id }); } } }; // main.js const worker = new Worker("worker.js"); const pendingRequests = new Map(); let requestId = 0; worker.onmessage = (event) => { if (event.data.type === "ready") { console.log("Worker ready"); } else if (event.data.type === "response") { const resolve = pendingRequests.get(event.data.id); if (resolve) { resolve(event.data.data); pendingRequests.delete(event.data.id); } } }; function fetchViaWorker(url, options = {}) { return new Promise((resolve) => { const id = requestId++; pendingRequests.set(id, resolve); worker.postMessage({ type: "fetch", url, options, id }); }); } // Usage const data = await fetchViaWorker("https://api.example.com/users"); ``` -------------------------------- ### HTTP Session with Base URL Source: https://context7.com/ading2210/libcurl.js/llms.txt Configure a session with a base URL to simplify making requests to a specific API endpoint using relative paths. ```javascript const apiSession = new libcurl.HTTPSession(); apiSession.base_url = "https://api.example.com"; const users = await apiSession.fetch("/users"); const posts = await apiSession.fetch("/posts"); const comments = await apiSession.fetch("/posts/1/comments"); console.log(await users.json()); apiSession.close(); ``` -------------------------------- ### Use libcurl.WebSocket API Source: https://context7.com/ading2210/libcurl.js/llms.txt Connect to a WebSocket server using the standard WebSocket API. Listen for open, message, close, and error events. Supports sending text, ArrayBuffer, and Blob data. Binary type can be set to 'arraybuffer' or 'blob'. ```javascript // Standard WebSocket API compatible usage const ws = new libcurl.WebSocket("wss://echo.websocket.org/"); ws.addEventListener("open", () => { console.log("Connection opened"); ws.send("Hello from polyfill!"); }); ws.addEventListener("message", (event) => { console.log("Received:", event.data); }); ws.addEventListener("close", (event) => { console.log("Connection closed:", event.code, event.reason); }); ws.addEventListener("error", (event) => { console.error("WebSocket error occurred"); }); // Check connection state console.log(ws.readyState); // 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED // Set binary type for received data ws.binaryType = "arraybuffer"; // or "blob" (default) ws.addEventListener("message", (event) => { if (event.data instanceof ArrayBuffer) { console.log("Binary data:", new Uint8Array(event.data)); } }); // Send different data types ws.send("text message"); ws.send(new Blob(["blob data"])); ws.send(new Uint8Array([0x01, 0x02, 0x03]).buffer); // Close connection ws.close(); ``` ```javascript // WebSocket with options (extended API) const wsWithAuth = new libcurl.WebSocket( "wss://secure.example.com/ws", ["protocol-v1"], { headers: { "Authorization": "Bearer token" } } ); ``` -------------------------------- ### libcurl.WebSocket - WebSocket Polyfill Source: https://context7.com/ading2210/libcurl.js/llms.txt Provides a standard WebSocket API interface compatible with browser's native WebSocket, including EventTarget support and standard events. ```APIDOC ## libcurl.WebSocket - WebSocket Polyfill Use the standard WebSocket API interface through libcurl.js. This polyfill provides the same interface as the browser's native WebSocket, with EventTarget support and standard events. ### Usage ```javascript // Standard WebSocket API compatible usage const ws = new libcurl.WebSocket("wss://echo.websocket.org/"); ws.addEventListener("open", () => { console.log("Connection opened"); ws.send("Hello from polyfill!"); }); ws.addEventListener("message", (event) => { console.log("Received:", event.data); }); ws.addEventListener("close", (event) => { console.log("Connection closed:", event.code, event.reason); }); ws.addEventListener("error", (event) => { console.error("WebSocket error occurred"); }); // Check connection state console.log(ws.readyState); // 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED // Set binary type for received data ws.binaryType = "arraybuffer"; // or "blob" (default) ws.addEventListener("message", (event) => { if (event.data instanceof ArrayBuffer) { console.log("Binary data:", new Uint8Array(event.data)); } }); // Send different data types ws.send("text message"); ws.send(new Blob(["blob data"])); ws.send(new Uint8Array([0x01, 0x02, 0x03]).buffer); // Close connection ws.close(); // WebSocket with options (extended API) const wsWithAuth = new libcurl.WebSocket( "wss://secure.example.com/ws", ["protocol-v1"], { headers: { "Authorization": "Bearer token" } } ); ``` ### Properties - **readyState** (number) - The current state of the WebSocket connection (0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED). - **binaryType** (string) - Specifies the type of binary data to be received. Can be "blob" or "arraybuffer". ### Methods - **send(data)**: Sends data to the server. `data` can be a string, Blob, or ArrayBuffer. - **close()**: Closes the WebSocket connection. ### Events - **open**: Fired when the connection is established. - **message**: Fired when a message is received from the server. - **close**: Fired when the connection is closed. - **error**: Fired when an error occurs. ``` -------------------------------- ### libcurl.TLSSocket Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Creates a raw TLS socket connection to a specified host and port. ```APIDOC ## libcurl.TLSSocket ### Description Creates a raw TLS socket connection. The socket supports sending data as Uint8Array and provides callbacks for connection status and incoming messages. ### Parameters - **host** (string) - Required - The hostname to connect to. - **port** (number) - Required - The TCP port to connect to. - **options** (object) - Optional - Extra settings including 'verbose' (boolean) and 'proxy' (string). ### Methods - **send(data)**: Sends data (Uint8Array) to the socket. - **close()**: Closes the socket connection. ### Request Example let socket = new libcurl.TLSSocket("ading.dev", 443, {verbose: 1}); ``` -------------------------------- ### Session Management API Source: https://github.com/ading2210/libcurl.js/blob/main/client/exported_funcs.txt Functions for initializing, configuring, and managing libcurl sessions. ```APIDOC ## Session Management Functions ### Description Functions to manage the lifecycle of a libcurl session. ### Methods - **init_curl**: Initializes the libcurl environment. - **session_create**: Creates a new session instance. - **session_perform**: Executes the session operations. - **session_set_options**: Configures session-specific options. - **session_add_request**: Adds a request to the session queue. - **session_get_active**: Retrieves the status of active requests. - **session_remove_request**: Removes a request from the session. - **session_cleanup**: Cleans up session resources. ``` -------------------------------- ### Fetch with Specific HTTP Version Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Fetches a URL and forces the usage of a specific HTTP version (1.0, 1.1, or 2.0). Defaults to HTTP/2 if not specified. ```javascript await libcurl.fetch("https://example.com", {_libcurl_http_version: 1.1}); ``` -------------------------------- ### libcurl.set_websocket Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Configures the URL for the websocket proxy used by the library. ```APIDOC ## libcurl.set_websocket ### Description Sets the URL of the websocket proxy. This must be called before other API functions if a proxy is required. ### Parameters - **url** (string) - Required - The proxy URL, must end with a trailing slash. ``` -------------------------------- ### Create and Communicate with a Web Worker Source: https://github.com/ading2210/libcurl.js/blob/main/client/worker.html Creates a new Web Worker from a Blob containing JavaScript code and sets up a message handler to receive data from it. This is useful for offloading tasks. ```javascript var blob = new Blob([ document.querySelector('#worker1').textContent ], { type: "text/javascript" }); var worker = new Worker(window.URL.createObjectURL(blob)); worker.onmessage = function(e) { console.log("Received: " + e.data); } ``` -------------------------------- ### Perform HTTPS Request Source: https://github.com/ading2210/libcurl.js/blob/main/website/index.html Execute an HTTPS request using the fetch-compatible API. ```javascript var r = await libcurl.fetch("https://ading.dev"); console.log(await r.text()); ``` -------------------------------- ### libcurl.HTTPSession Class Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Methods and configuration for managing persistent HTTP sessions. ```APIDOC ## libcurl.HTTPSession ### Description Creates a new session for HTTP requests with support for cookies and proxy settings. ### Constructor `new libcurl.HTTPSession(options)` ### Options - **enable_cookies** (boolean) - Optional - Whether cookies should be persisted. - **cookie_jar** (string) - Optional - Data from a cookie jar file. - **proxy** (string) - Optional - URL for socks5h, socks4a, or http proxy. ### Methods - **fetch(url)** - Performs a request within the session. - **set_connections(active, cache, per_host)** - Sets connection limits. - **export_cookies()** - Returns recorded cookies as a string. - **close()** - Closes all connections and cleans up memory. ### Attributes - **base_url** (string) - Base URL for resolving relative paths. ``` -------------------------------- ### HTTP and Request API Source: https://github.com/ading2210/libcurl.js/blob/main/client/exported_funcs.txt Functions for handling HTTP requests and request-specific configurations. ```APIDOC ## HTTP and Request Functions ### Description Functions for creating, configuring, and retrieving information about HTTP requests. ### Methods - **create_request**: Creates a new request object. - **request_set_proxy**: Sets proxy settings for a request. - **http_set_options**: Configures global HTTP options. - **http_get_info**: Retrieves information about the HTTP state. - **http_set_cookie_jar**: Sets the cookie jar file path. - **request_cleanup**: Cleans up request resources. ``` -------------------------------- ### libcurl.TLSSocket - Raw TLS Connections Source: https://context7.com/ading2210/libcurl.js/llms.txt Enables the creation of raw TLS socket connections for custom protocols over encrypted channels, suitable for low-level network communication. ```APIDOC ## libcurl.TLSSocket - Raw TLS Connections Create raw TLS socket connections for custom protocols over encrypted channels. Useful for implementing custom protocols or low-level network communication. ### Basic Usage ```javascript // Basic TLS socket connection const socket = new libcurl.TLSSocket("example.com", 443); socket.onopen = () => { console.log("TLS connection established"); // Send raw HTTP request const request = "GET / HTTP/1.1\r\n" + "Host: example.com\r\n" + "Connection: close\r\n\r\n"; socket.send(new TextEncoder().encode(request)); }; socket.onmessage = (data) => { // data is always Uint8Array const text = new TextDecoder().decode(data); console.log("Received:", text); }; socket.onclose = () => { console.log("Socket closed"); }; socket.onerror = (errorCode) => { console.error("Socket error:", libcurl.get_error_string(errorCode)); }; ``` ### Advanced Usage with Options ```javascript // TLS socket with verbose output and proxy const secureSocket = new libcurl.TLSSocket("cloudflare.com", 443, { verbose: true, proxy: "socks5h://127.0.0.1:9050" }); secureSocket.onopen = () => { // Verify TLS version const request = "GET /cdn-cgi/trace HTTP/1.1\r\n" + "Host: cloudflare.com\r\n" + "Connection: close\r\n\r\n"; secureSocket.send(new TextEncoder().encode(request)); }; secureSocket.onmessage = (data) => { const response = new TextDecoder().decode(data); if (response.includes("tls=TLSv1.3")) { console.log("TLS 1.3 connection confirmed!"); } }; ``` ### Custom Protocol Example ```javascript // Custom protocol implementation example class CustomProtocol { constructor(host, port) { this.socket = new libcurl.TLSSocket(host, port); this.messageQueue = []; this.socket.onopen = () => this.onConnected(); this.socket.onmessage = (data) => this.handleData(data); this.socket.onerror = (err) => this.handleError(err); } onConnected() { // Send protocol handshake const handshake = new Uint8Array([0x01, 0x00, 0x00, 0x00]); this.socket.send(handshake); } handleData(data) { this.messageQueue.push(data); } handleError(errorCode) { console.error("Protocol error:", libcurl.get_error_string(errorCode)); } close() { this.socket.close(); } } ``` ### Constructor `new libcurl.TLSSocket(host: string, port: number, options?: TLSSocketOptions)` ### Options (`TLSSocketOptions`) - **verbose** (boolean) - Enables verbose logging for the TLS connection. - **proxy** (string) - Specifies a proxy URL for the connection (e.g., "socks5h://127.0.0.1:9050"). ### Event Handlers - **onopen**: Callback function executed when the TLS connection is established. - **onmessage**: Callback function executed when data is received. The `data` argument is always a `Uint8Array`. - **onclose**: Callback function executed when the connection is closed. - **onerror**: Callback function executed when an error occurs. The `errorCode` argument is a numerical error code. ``` -------------------------------- ### Configure Network Transport Source: https://context7.com/ading2210/libcurl.js/llms.txt Set the underlying network protocol or implement a custom transport class that adheres to the WebSocket-like interface. ```javascript // Use Wisp protocol (default - best performance via multiplexing) libcurl.transport = "wisp"; // Use wsproxy protocol (one WebSocket per TCP connection) libcurl.transport = "wsproxy"; // Custom transport implementation class CustomTransport { constructor(url) { // url format: "wss://proxy.example.com/ws/target.com:443" this.url = url; this.onopen = null; this.onclose = null; this.onmessage = null; this.onerror = null; // Connect using your custom protocol this.connect(); } connect() { // Implementation details... // Must implement WebSocket-like interface } send(data) { // Send data through your transport } close() { // Clean up connection } } libcurl.transport = CustomTransport; // All subsequent requests will use the custom transport await libcurl.fetch("https://example.com"); ``` -------------------------------- ### Configure HTTP Session Connection Limits Source: https://context7.com/ading2210/libcurl.js/llms.txt Control the connection pooling behavior of an HTTP session by setting limits on total connections, cache size, and connections per host. ```javascript const highPerfSession = new libcurl.HTTPSession(); // Args: max total connections, connection cache size, max per host highPerfSession.set_connections(100, 80, 10); // Make parallel requests const promises = []; for (let i = 0; i < 5; i++) { promises.push(highPerfSession.fetch(`https://api.example.com/item/${i}`)); } const responses = await Promise.all(promises); highPerfSession.close(); ``` -------------------------------- ### libcurl.CurlWebSocket Class Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Methods and events for managing WebSocket connections. ```APIDOC ## libcurl.CurlWebSocket ### Description Handles WebSocket communication with support for custom headers and proxy settings. ### Constructor `new libcurl.CurlWebSocket(url, protocols, options)` ### Options - **headers** (object) - Optional - HTTP request headers. - **verbose** (boolean) - Optional - Toggles verbose libcurl output. - **proxy** (string) - Optional - URL for proxy server. ### Callbacks - **onopen** - Triggered on successful connection. - **onmessage(data)** - Triggered when a message is received. - **onclose** - Triggered on clean closure. - **onerror(code)** - Triggered on error. ### Methods - **send(data)** - Sends string or Uint8Array data. - **close()** - Closes the connection. ``` -------------------------------- ### Configure Wisp Proxy URL Source: https://github.com/ading2210/libcurl.js/blob/main/website/index.html Set the WebSocket URL for the Wisp proxy server before making requests. ```javascript libcurl.set_websocket(`wss://wisp.mercurywork.shop/`); ``` -------------------------------- ### WebSocket and Socket API Source: https://github.com/ading2210/libcurl.js/blob/main/client/exported_funcs.txt Functions for managing WebSocket connections and raw socket communication. ```APIDOC ## WebSocket and Socket Functions ### Description Functions for managing WebSocket and raw socket data transmission and configuration. ### Methods - **websocket_set_options**: Configures WebSocket options. - **recv_from_websocket**: Receives data from a WebSocket. - **send_to_websocket**: Sends data to a WebSocket. - **close_websocket**: Closes a WebSocket connection. - **tls_socket_set_options**: Configures TLS socket options. - **recv_from_socket**: Receives data from a raw socket. - **send_to_socket**: Sends data to a raw socket. ``` -------------------------------- ### HTTP Session with Cookie Support Source: https://context7.com/ading2210/libcurl.js/llms.txt Enable cookie management within a session to automatically handle cookies across requests. Cookies can be exported and restored for persistence. ```javascript const cookieSession = new libcurl.HTTPSession({ enable_cookies: true }); // Login - cookies will be stored automatically await cookieSession.fetch("https://example.com/login", { method: "POST", body: JSON.stringify({ user: "admin", pass: "secret" }), headers: { "Content-Type": "application/json" } }); // Subsequent requests include cookies automatically const dashboard = await cookieSession.fetch("https://example.com/dashboard"); // Export cookies for persistence const cookieJar = cookieSession.export_cookies(); localStorage.setItem("cookies", cookieJar); cookieSession.close(); ``` ```javascript const restoredSession = new libcurl.HTTPSession({ enable_cookies: true, cookie_jar: localStorage.getItem("cookies") }); ``` -------------------------------- ### libcurl.get_error_string Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Retrieves a human-readable error string from a libcurl error code. ```APIDOC ## libcurl.get_error_string ### Description Converts a numeric libcurl error code into a descriptive string. ### Parameters - **code** (number) - Required - The error code defined by the libcurl C library. ``` -------------------------------- ### libcurl.set_websocket - Configure Proxy URL Source: https://context7.com/ading2210/libcurl.js/llms.txt Configures the WebSocket proxy URL that libcurl.js uses to tunnel TCP connections. This must be called before making any requests. ```APIDOC ## libcurl.set_websocket - Configure Proxy URL Set the WebSocket proxy URL that libcurl.js uses to tunnel TCP connections. This must be called before making any requests. The URL must end with a trailing slash. ### Setting the Proxy URL ```javascript // Set the Wisp protocol proxy URL libcurl.set_websocket("wss://your-server.com/ws/"); // Using a local development server libcurl.set_websocket("ws://localhost:6001/"); // Get current proxy URL console.log(libcurl.websocket_url); // Common pattern: set proxy based on current page location document.addEventListener("libcurl_load", () => { const proxyUrl = `wss://${location.hostname}/ws/`; libcurl.set_websocket(proxyUrl); }); // Now requests can be made const response = await libcurl.fetch("https://api.example.com/data"); ``` ### Method `libcurl.set_websocket(url: string)` ### Parameters - **url** (string) - The WebSocket proxy URL. Must end with a trailing slash. ### Properties - **libcurl.websocket_url** (string) - Returns the currently configured WebSocket proxy URL. ``` -------------------------------- ### Set Websocket Proxy URL Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Sets the URL for the websocket proxy. This URL must end with a trailing slash. Existing connections are not affected by this change. ```javascript libcurl.set_websocket("ws://localhost:6001/"); ``` -------------------------------- ### Intercept Standard Error Output Source: https://github.com/ading2210/libcurl.js/blob/main/README.md Sets a callback function to intercept standard error messages from libcurl. The provided text is appended to the document's body. ```javascript libcurl.stderr = (text) => {document.body.innerHTML += text}; ``` -------------------------------- ### Control HTTP Versions Source: https://context7.com/ading2210/libcurl.js/llms.txt Force specific HTTP protocol versions for individual requests to aid in debugging or server compatibility. ```javascript // Force HTTP/1.0 const r1 = await libcurl.fetch("https://example.com", { _libcurl_http_version: 1.0 }); // Force HTTP/1.1 const r2 = await libcurl.fetch("https://example.com", { _libcurl_http_version: 1.1 }); // Force HTTP/2 (default) const r3 = await libcurl.fetch("https://example.com", { _libcurl_http_version: 2.0 }); // Check which version was actually used console.log("HTTP version:", r3.url); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.