### Verify wreq-js installation Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/installation.mdx Verify the wreq-js installation by importing functions and making a test request. This example uses TypeScript to check available browser profiles and perform an HTTP GET request. ```typescript import { fetch, getProfiles } from 'wreq-js'; // Check available browser profiles console.log('Available profiles:', getProfiles()); // Make a test request const response = await fetch('https://httpbin.org/get', { browser: 'chrome_142', }); console.log('Status:', response.status); ``` -------------------------------- ### Install Ubuntu/Debian build essentials Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/installation.mdx Install build-essential package on Ubuntu or Debian systems using apt-get. This provides the C compiler and related tools needed for building wreq-js from source. ```bash sudo apt-get install build-essential ``` -------------------------------- ### Manage Multiple Requests with wreq-js Sessions Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/quickstart.mdx Illustrates how to use sessions in wreq-js for making multiple requests. Sessions persist cookies and connection state, improving performance for subsequent requests. The example includes a login POST request and an authenticated GET request, followed by closing the session. ```typescript import { createSession } from 'wreq-js'; const session = await createSession({ browser: 'chrome_142' }); // Login await session.fetch('https://example.com/login', { method: 'POST', body: new URLSearchParams({ user: 'name', pass: 'secret' }), }); // Access authenticated endpoint (cookies are preserved) const account = await session.fetch('https://example.com/account'); console.log(await account.text()); // Clean up await session.close(); ``` -------------------------------- ### Make a Single Request with wreq-js Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/quickstart.mdx Demonstrates how to make a single HTTP GET request using the fetch function from wreq-js. It specifies a browser profile for the request and logs the JSON response. Note that one-off fetch calls are ephemeral by default. ```typescript import { fetch } from 'wreq-js'; const response = await fetch('https://httpbin.org/get', { browser: 'chrome_142', }); console.log(await response.json()); ``` -------------------------------- ### Install Rust toolchain from source Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/installation.mdx Install the Rust toolchain using the official rustup script. This is a prerequisite for building wreq-js from source on platforms without prebuilt binaries. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Quick Start Fetch Request Source: https://github.com/sqdshguy/wreq-js/blob/master/README.md A basic example demonstrating how to perform a fetch request using wreq-js. It shows how to import the fetch function and make a request with specified browser and OS fingerprints. ```typescript import { fetch } from 'wreq-js'; const res = await fetch('https://example.com/api', { browser: 'chrome_142', os: 'windows', }); console.log(await res.json()); ``` -------------------------------- ### Install wreq-js using npm, yarn, pnpm, and bun Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/installation.mdx Install the wreq-js package using your preferred package manager. Ensure you have Node.js v20.0.0 or higher installed. ```bash npm install wreq-js ``` ```bash yarn add wreq-js ``` ```bash pnpm add wreq-js ``` ```bash bun add wreq-js ``` -------------------------------- ### Install Build Tools (Linux Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/BUILD.md Installs essential build tools on Debian/Ubuntu or Fedora/RHEL based Linux distributions. ```bash # Ubuntu/Debian sudo apt-get install build-essential # Fedora/RHEL sudo dnf install gcc ``` -------------------------------- ### Make a Request with a Proxy using wreq-js Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/quickstart.mdx Shows how to configure a proxy for an HTTP request made with wreq-js. The proxy option allows requests to be routed through a specified proxy server, including authentication details if required. ```typescript import { fetch } from 'wreq-js'; const response = await fetch('https://example.com', { browser: 'chrome_142', proxy: 'http://user:pass@proxy.example.com:8080', }); ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/CONTRIBUTING.md Installs project dependencies using npm. This command reads the package.json file to download and set up the necessary libraries for development. ```bash npm install ``` -------------------------------- ### Install wreq-js Package Source: https://github.com/sqdshguy/wreq-js/blob/master/README.md Instructions for installing the wreq-js package using various Node.js package managers. This is the first step to use the library in your project. ```bash npm install wreq-js # or yarn add wreq-js pnpm add wreq-js bun add wreq-js ``` -------------------------------- ### Install Xcode Command Line Tools (macOS Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/BUILD.md Installs the necessary command-line developer tools on macOS, which may be required for building certain native modules. ```bash xcode-select --install ``` -------------------------------- ### Run Tests for wreq-js (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/BUILD.md Executes the test suite for wreq-js, which includes building the project, starting a test server, and running the tests. ```bash npm test ``` -------------------------------- ### Get Available Operating Systems with wreq-js Source: https://context7.com/sqdshguy/wreq-js/llms.txt Fetches a list of supported operating systems for browser emulation. The selected OS influences platform-specific headers and TLS fingerprints. The example shows how to use this with `fetch` and `createSession`. ```typescript import { getOperatingSystems, fetch, createSession } from 'wreq-js'; const operatingSystems = getOperatingSystems(); console.log(`Supported OS: ${operatingSystems.join(', ')}`); // ['windows', 'macos', 'linux', 'android', 'ios'] // Request with specific OS emulation const response = await fetch('https://api.example.com/detect', { browser: 'chrome_142', os: 'windows', timeout: 5000 }); const data = await response.json(); console.log('Detected platform:', data.platform); // Test different OS combinations for (const os of ['windows', 'macos', 'linux']) { const res = await fetch('https://api.example.com/fingerprint', { browser: 'chrome_142', os, timeout: 5000 }); const fingerprint = await res.json(); console.log(`${os}:`, fingerprint.platform); } // Session with OS binding const session = await createSession({ browser: 'chrome_142', os: 'macos' }); // All requests in this session use macOS fingerprint await session.fetch('https://example.com/page1'); await session.fetch('https://example.com/page2'); await session.close(); ``` -------------------------------- ### Build wreq-js from Source (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/BUILD.md Installs dependencies and builds both Rust and TypeScript components of wreq-js. This is the recommended command for a full build. ```bash npm install npm run build ``` -------------------------------- ### Troubleshooting: Clean Slate Build (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/BUILD.md Performs a comprehensive cleanup by removing build artifacts, node modules, and package lock files, followed by a fresh install and build. ```bash npm run clean rm -rf node_modules package-lock.json npm install npm run build ``` -------------------------------- ### Example Test Case (TypeScript) Source: https://github.com/sqdshguy/wreq-js/blob/master/CONTRIBUTING.md Demonstrates a well-written test case in TypeScript, emphasizing descriptive naming for clarity and maintainability within the testing framework. ```typescript // Good test('should load correct binary for macOS ARM64', () => { // ... }); // Bad test('test1', () => { // ... }); ``` -------------------------------- ### get() - Convenience GET Method Source: https://context7.com/sqdshguy/wreq-js/llms.txt A shorthand for making GET requests without explicitly specifying the method in the options. ```APIDOC ## get() - Convenience GET Method ### Description Provides a convenient shorthand for making HTTP GET requests, accepting all options compatible with the `fetch` function except for the `method` itself. ### Method `get(url, options)` ### Endpoint N/A (Function call within Node.js) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL to fetch. - **options** (object) - Optional - Configuration options for the request (same as `fetch` options, excluding `method`). - **browser** (string) - Required - The browser profile to emulate. - **os** (string) - Optional - The operating system to emulate. - **headers** (object) - Optional - Custom request headers. - **timeout** (number) - Optional - Request timeout in milliseconds. - **proxy** (string) - Optional - Proxy server URL. - **signal** (AbortSignal) - Optional - An AbortSignal to cancel the request. ### Request Example ```json { "url": "https://api.example.com/users/123", "options": { "browser": "chrome_142", "headers": { "Accept": "application/json" } } } ``` ### Response #### Success Response (200-level) - **response** (Response) - A Fetch API Response object, similar to the one returned by `fetch()`. #### Response Example ```json { "ok": true, "status": 200, "statusText": "OK", "headers": { "Content-Type": "application/json" } } ``` ``` -------------------------------- ### Example Commit Messages (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/CONTRIBUTING.md Illustrates various commit message types according to Conventional Commits, including features, bug fixes, documentation updates, and breaking changes. ```bash # Feature feat(request): add support for HTTP/3 # Bug fix fix(loader): resolve platform detection on Alpine Linux # Documentation docs(readme): add installation instructions for pnpm # Breaking change feat(api)!: change request signature to accept options object BREAKING CHANGE: request() now requires an options object instead of positional arguments ``` -------------------------------- ### Fix npm permissions on macOS Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/installation.mdx Resolve potential permission errors encountered during npm operations on macOS by changing the ownership of the .npm directory to the current user. This is a common troubleshooting step for installation issues. ```bash sudo chown -R $(whoami) ~/.npm ``` -------------------------------- ### Basic GET Request with fetch() Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/api-reference/fetch.mdx Demonstrates a basic GET request using the fetch() function. It specifies a browser profile for fingerprinting and then parses the JSON response. This is useful for fetching data from APIs. ```typescript import { fetch } from 'wreq-js'; const response = await fetch('https://api.example.com/data', { browser: 'chrome_142', }); const data = await response.json(); ``` -------------------------------- ### Emulate Windows Chrome Browser in TypeScript Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/concepts/browser-profiles.mdx Shows an example of configuring a fetch request to emulate a specific browser and operating system combination. This fetch call targets 'https://example.com' using the 'chrome_142' browser profile and the 'windows' operating system emulation. ```typescript const response = await fetch('https://example.com', { browser: 'chrome_142', os: 'windows', }); ``` -------------------------------- ### Perform GET Requests with get() in wreq-js Source: https://context7.com/sqdshguy/wreq-js/llms.txt A convenience method for making HTTP GET requests. It simplifies GET requests by not requiring the 'method' option. Accepts all standard fetch options like browser fingerprinting, headers, and timeouts. ```typescript import { get } from 'wreq-js'; // Simple GET with browser fingerprint const response = await get('https://api.example.com/users/123', { browser: 'chrome_142', headers: { 'Accept': 'application/json' } }); const user = await response.json(); console.log('User:', user.name, user.email); // GET with custom headers and timeout const apiResponse = await get('https://api.example.com/products?category=electronics', { browser: 'firefox_139', headers: { 'Authorization': 'Bearer token123', 'X-Request-Id': crypto.randomUUID() }, timeout: 8000 }); const products = await apiResponse.json(); console.log(`Found ${products.length} products`); ``` -------------------------------- ### Emulate iOS Safari Browser in TypeScript Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/concepts/browser-profiles.mdx Provides an example of emulating a browser and OS combination for an iOS Safari instance. This fetch request targets 'https://example.com' using the 'safari_18' browser profile and the 'ios' operating system. ```typescript const response = await fetch('https://example.com', { browser: 'safari_18', os: 'ios', }); ``` -------------------------------- ### Get Operating Systems (TypeScript) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/api-reference/utilities.mdx Retrieves a list of all supported operating systems for emulation. This allows users to specify the target OS when making requests, enhancing the simulation of different client environments. The function returns an array of strings, each representing an OS name. ```typescript import { getOperatingSystems } from 'wreq-js'; const systems = getOperatingSystems(); console.log(systems); // ['windows', 'macos', 'linux', 'android', 'ios'] ``` -------------------------------- ### Session Management with wreq-js Source: https://github.com/sqdshguy/wreq-js/blob/master/README.md Example of using sessions with wreq-js for managing cookies and TLS connections across multiple requests. This approach is recommended for most real-world workloads to improve performance by keeping connections warm. ```typescript import { createSession } from 'wreq-js'; const session = await createSession({ browser: 'chrome_142', os: 'windows' }); try { const a = await session.fetch('https://example.com/a'); const b = await session.fetch('https://example.com/b'); console.log(a.status, b.status); } finally { await session.close(); } ``` -------------------------------- ### Handle Incoming WebSocket Messages (String, Binary, JSON) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/guides/websockets.mdx Provides an example of how to process incoming messages from a WebSocket server using the `onMessage` callback in wreq-js. It handles both string and binary data, with specific logic for parsing JSON strings into JavaScript objects. Requires 'wreq-js' and assumes an active WebSocket connection. ```typescript const ws = await websocket({ url: 'wss://example.com/socket', browser: 'chrome_142', onMessage: (data) => { // data can be string or binary if (typeof data === 'string') { const message = JSON.parse(data); console.log('Received JSON:', message); } else { console.log('Received binary:', data.byteLength, 'bytes'); } }, }); ``` -------------------------------- ### Get Available Browser Profiles with wreq-js Source: https://context7.com/sqdshguy/wreq-js/llms.txt Retrieves an array of all supported browser profiles by the wreq-js library. These profile names can be used in the `browser` option for session creation and requests. The example also shows filtering and random selection. ```typescript import { getProfiles } from 'wreq-js'; const profiles = getProfiles(); console.log(`Total profiles: ${profiles.length}`); // Filter by browser type const chromeProfiles = profiles.filter(p => p.startsWith('chrome_')); const firefoxProfiles = profiles.filter(p => p.startsWith('firefox_')); const safariProfiles = profiles.filter(p => p.startsWith('safari_')); console.log('Chrome versions:', chromeProfiles); // ['chrome_100', 'chrome_101', ..., 'chrome_142'] console.log('Firefox versions:', firefoxProfiles); // ['firefox_109', 'firefox_110', ..., 'firefox_143'] console.log('Safari versions:', safariProfiles); // ['safari_15.3_ios_15.3', 'safari_17', 'safari_18', ..., 'safari_26'] // Test API with multiple browsers for (const browser of ['chrome_142', 'firefox_139', 'safari_18']) { const response = await fetch('https://api.example.com/detect', { browser, timeout: 5000 }); const data = await response.json(); console.log(`${browser} detected as:`, data.userAgent); } // Random browser selection const randomBrowser = profiles[Math.floor(Math.random() * profiles.length)]; console.log('Using random browser:', randomBrowser); ``` -------------------------------- ### Troubleshooting: Rebuild Rust Addon (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/BUILD.md Command to rebuild the Rust native addon for wreq-js, often necessary if the 'index.node' module cannot be found. ```bash npm run build:rust ``` -------------------------------- ### Individual Build Commands (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/BUILD.md Commands to build only the Rust components or only the TypeScript components of wreq-js separately. ```bash # Rust only npm run build:rust # TypeScript only npm run build:ts ``` -------------------------------- ### Operating System Emulation - getOperatingSystems() Source: https://context7.com/sqdshguy/wreq-js/llms.txt Retrieves a list of supported operating systems for browser emulation. Specifying an OS influences platform-specific headers and TLS fingerprints. ```APIDOC ## Operating System Emulation ### getOperatingSystems() - Available OS List ### Description Returns array of supported operating systems for browser emulation. The OS affects platform-specific headers and TLS fingerprints. ### Method `getOperatingSystems()` ### Endpoint Not applicable (function) ### Parameters None ### Request Example ```typescript import { getOperatingSystems, fetch, createSession } from 'wreq-js'; const operatingSystems = getOperatingSystems(); console.log(`Supported OS: ${operatingSystems.join(', ')}`); // ['windows', 'macos', 'linux', 'android', 'ios'] // Request with specific OS emulation const response = await fetch('https://api.example.com/detect', { browser: 'chrome_142', os: 'windows', timeout: 5000 }); const data = await response.json(); console.log('Detected platform:', data.platform); // Test different OS combinations for (const os of ['windows', 'macos', 'linux']) { const res = await fetch('https://api.example.com/fingerprint', { browser: 'chrome_142', os, timeout: 5000 }); const fingerprint = await res.json(); console.log(`${os}:`, fingerprint.platform); } // Session with OS binding const session = await createSession({ browser: 'chrome_142', os: 'macos' }); // All requests in this session use macOS fingerprint await session.fetch('https://example.com/page1'); await session.fetch('https://example.com/page2'); await session.close(); ``` ### Response - `Array` - An array of strings, where each string is a supported operating system name. ``` -------------------------------- ### Fetch API with Advanced Configurations Source: https://context7.com/sqdshguy/wreq-js/llms.txt Documentation for the `fetch` function in wreq-js, detailing configurations for request timeouts, proxy usage, and custom headers. ```APIDOC ## Advanced Request Options ### Request Timeout Configuration Control maximum request duration with timeout option. Defaults to 30 seconds. #### Parameters - **timeout** (number) - Optional - The maximum time in milliseconds to wait for a response. Defaults to 30000 (30 seconds). #### Request Example ```typescript import { fetch } from 'wreq-js'; // Short timeout const healthResponse = await fetch('https://api.example.com/health', { browser: 'chrome_142', timeout: 2000 // 2 seconds }); // Long timeout const exportResponse = await fetch('https://api.example.com/export/large-dataset', { browser: 'chrome_142', timeout: 120000 // 2 minutes }); // With abort signal const controller = new AbortController(); document.querySelector('#cancelBtn').onclick = () => controller.abort(); try { await fetch('https://api.example.com/slow-operation', { browser: 'chrome_142', timeout: 60000, signal: controller.signal }); } catch (error) { if (error.name === 'AbortError') { console.log('User cancelled request'); } else { console.log('Request timeout or network error'); } } ``` ### Proxy Configuration Route requests through HTTP or SOCKS5 proxies with optional authentication. #### Parameters - **proxy** (string) - Optional - The URL of the proxy server. Supports `http://` and `socks5://` schemes, with optional username and password (e.g., 'http://username:password@proxy.example.com:8080'). #### Request Example ```typescript import { fetch } from 'wreq-js'; // HTTP proxy without authentication const res1 = await fetch('https://api.example.com/data', { browser: 'chrome_142', proxy: 'http://proxy.example.com:8080' }); // SOCKS5 proxy with authentication const res4 = await fetch('https://api.example.com/data', { browser: 'chrome_142', proxy: 'socks5://user:pass@proxy.example.com:1080' }); // Using a session with proxy const session = await createSession({ browser: 'firefox_139', proxy: 'http://proxy.example.com:8080' }); await session.fetch('https://example.com/page1'); await session.close(); ``` ### Custom Headers Without Browser Emulation Disable automatic browser headers for complete control over request headers. #### Parameters - **disableDefaultHeaders** (boolean) - Optional - If true, automatically added browser headers (like User-Agent, Accept, etc.) are omitted, sending only the explicitly provided headers. #### Request Example ```typescript import { fetch } from 'wreq-js'; // Default behavior (browser headers added) const res1 = await fetch('https://api.example.com/data', { browser: 'chrome_142', headers: { 'X-Api-Key': 'abc123' } }); // Disable default headers const res2 = await fetch('https://api.example.com/data', { headers: { 'User-Agent': 'CustomBot/2.0', 'X-Bot-Id': '12345' }, disableDefaultHeaders: true }); // API client example const apiClient = async (endpoint, apiKey) => { return fetch(`https://api.example.com${endpoint}`, { headers: { 'Authorization': `Bearer ${apiKey}`, 'Content-Type': 'application/json' }, disableDefaultHeaders: true }); }; await apiClient('/users', 'token123'); ``` ``` -------------------------------- ### Build Project (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/CONTRIBUTING.md Builds the project using npm scripts. This typically involves transpiling code, bundling assets, or performing other build-time operations. ```bash npm run build ``` -------------------------------- ### Session Management - clearCookies() Source: https://context7.com/sqdshguy/wreq-js/llms.txt Removes all cookies from the current session while retaining the connection pool. This is useful for starting fresh requests without prior cookie data. ```APIDOC ## Session.clearCookies() ### Description Removes all cookies from session while keeping connection pool alive. ### Method Not applicable (method of a Session object) ### Endpoint Not applicable (method of a Session object) ### Parameters None ### Request Example ```typescript const session = await createSession({ browser: 'chrome_142' }); // Accumulate cookies await session.fetch('https://example.com/login', { method: 'POST', body: '...' }); await session.fetch('https://example.com/dashboard'); // Clear cookies for fresh start session.clearCookies(); console.log('Cookies cleared, connection pool retained'); // New requests have no cookies await session.fetch('https://example.com/public'); await session.close(); ``` ### Response None (modifies session state) ### Response Example None ``` -------------------------------- ### Clean Build wreq-js (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/BUILD.md Removes build artifacts and then performs a full build of wreq-js. Useful for ensuring a fresh build environment. ```bash npm run clean npm run build ``` -------------------------------- ### Clear Session Cookies with wreq-js Source: https://context7.com/sqdshguy/wreq-js/llms.txt Demonstrates how to clear all cookies from a wreq-js session while keeping the underlying connection pool alive. This is useful for starting fresh requests without any pre-existing cookies. ```typescript const session = await createSession({ browser: 'chrome_142' }); // Accumulate cookies await session.fetch('https://example.com/login', { method: 'POST', body: '...' }); await session.fetch('https://example.com/dashboard'); // Clear cookies for fresh start session.clearCookies(); console.log('Cookies cleared, connection pool retained'); // New requests have no cookies await session.fetch('https://example.com/public'); await session.close(); ``` -------------------------------- ### Troubleshooting: Update Rust Toolchain (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/BUILD.md Updates the stable Rust toolchain to the latest version, which can resolve compilation errors. ```bash rustup update stable ``` -------------------------------- ### Get Browser Profiles (TypeScript) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/api-reference/utilities.mdx Retrieves a list of all available browser fingerprint profiles supported by wreq-js. These profiles can be used to simulate specific browser environments for requests. The function returns an array of strings, where each string represents a browser profile name. ```typescript import { getProfiles } from 'wreq-js'; const profiles = getProfiles(); console.log(profiles); // ['chrome_142', 'chrome_141', 'firefox_139', 'safari_18', 'edge_120', ...] ``` -------------------------------- ### getOperatingSystems() - Operating Systems Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/api-reference/overview.mdx The `getOperatingSystems()` function provides a list of supported operating systems for emulation. This allows you to specify the target OS for browser fingerprinting. ```APIDOC ## GET /api/utilities/os ### Description List available operating systems. ### Method GET ### Endpoint N/A (This describes a function, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { getOperatingSystems } from 'wreq-js'; const operatingSystems = await getOperatingSystems(); console.log(operatingSystems); ``` ### Response #### Success Response (200) - **operatingSystems** (Array) - An array of supported operating system names. #### Response Example ```json [ "windows", "macos", "linux" ] ``` ``` -------------------------------- ### List Supported Operating Systems in TypeScript Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/concepts/browser-profiles.mdx Fetches a list of operating systems that wreq-js can emulate for browser fingerprinting. This function returns an array of strings, each representing a supported OS. This information is useful for selecting the appropriate `os` option in fetch requests. ```typescript import { getOperatingSystems } from 'wreq-js'; console.log(getOperatingSystems()); // ['windows', 'macos', 'linux', 'android', 'ios'] ``` -------------------------------- ### Session Isolation Example in TypeScript Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/concepts/sessions.mdx Highlights the isolation features of sessions, showing that separate sessions maintain their own independent cookie jars, TLS caches, and connection pools. Cookies set in one session do not affect another. ```typescript // These sessions are completely isolated const session1 = await createSession({ browser: 'chrome_142' }); const session2 = await createSession({ browser: 'firefox_139' }); // Cookies set in session1 do not affect session2 await session1.fetch('https://example.com/set-cookie'); await session2.fetch('https://example.com/check-cookie'); // No cookie present ``` -------------------------------- ### Operating System Utilities Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/api-reference/utilities.mdx Functions to retrieve available operating systems for emulation. ```APIDOC ## getOperatingSystems() ### Description Get a list of all available operating systems for emulation. ### Method GET (conceptual, as it's a utility function) ### Endpoint N/A ### Parameters None ### Request Example ```typescript import { getOperatingSystems } from 'wreq-js'; const systems = getOperatingSystems(); console.log(systems); // ['windows', 'macos', 'linux', 'android', 'ios'] ``` ### Response #### Success Response (200) - **systems** (EmulationOS[]) - An array of strings representing available operating system names. #### Response Example ```json ["windows", "macos", "linux", "android", "ios"] ``` ``` -------------------------------- ### Headers Class Usage (TypeScript) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/api-reference/utilities.mdx Demonstrates the usage of the `Headers` class in wreq-js for constructing and manipulating HTTP request headers. This class provides methods to append, delete, get, set, and iterate over header key-value pairs. It is essential for customizing request metadata. ```typescript import { fetch, Headers } from 'wreq-js'; const headers = new Headers(); headers.set('Authorization', 'Bearer token'); headers.set('Content-Type', 'application/json'); const response = await fetch('https://api.example.com', { browser: 'chrome_142', headers, }); ``` -------------------------------- ### Configure Session Options in TypeScript Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/concepts/sessions.mdx Illustrates how to pass configuration options when creating a session. These options, such as `browser`, `os`, and `proxy`, define the default behavior for all requests within that session. ```typescript const session = await createSession({ browser: 'chrome_142', os: 'windows', proxy: 'http://proxy.example.com:8080', insecure: false, }); ``` -------------------------------- ### fetch() API Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/api-reference/fetch.mdx The fetch() function is the primary method for making HTTP requests. It accepts a URL and an optional `RequestInit` object for configuration. ```APIDOC ## POST /api/fetch ### Description Makes an HTTP request to the specified URL with optional browser fingerprinting and request configurations. ### Method POST ### Endpoint /api/fetch ### Parameters #### Request Body - **url** (string | URL) - Required - The URL to fetch. Can be a string or URL object. - **init** (RequestInit) - Optional - Request configuration object. - **method** (string) - Optional - HTTP method (default: GET). - **headers** (HeadersInit) - Optional - Request headers. - **body** (BodyInit | null) - Optional - Request body. - **browser** (BrowserProfile) - Optional - Browser fingerprint profile to use. - **os** (EmulationOS) - Optional - Operating system to emulate. - **proxy** (string) - Optional - Proxy URL. - **timeout** (number) - Optional - Request timeout in milliseconds. - **signal** (AbortSignal) - Optional - AbortSignal for cancelling the request. - **redirect** (string) - Optional - Redirect handling mode (default: 'follow'). - **disableDefaultHeaders** (boolean) - Optional - Disable default browser emulation headers (default: false). - **insecure** (boolean) - Optional - Accept invalid/self-signed certificates (default: false). ### Request Example ```json { "url": "https://api.example.com/data", "init": { "method": "GET", "browser": "chrome_142", "headers": { "Content-Type": "application/json" } } } ``` ### Response #### Success Response (200) - **status** (number) - HTTP status code. - **statusText** (string) - HTTP status text. - **headers** (object) - Response headers. - **ok** (boolean) - True if status is 200-299. - **url** (string) - Final URL after redirects. - **body** (ReadableStream | null) - Response body. - **bodyUsed** (boolean) - True if body has been consumed. #### Response Example ```json { "status": 200, "statusText": "OK", "headers": { "Content-Type": "application/json" }, "ok": true, "url": "https://api.example.com/data", "body": null, "bodyUsed": false } ``` ``` -------------------------------- ### Import Core Functions and Utilities from wreq-js (TypeScript) Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/api-reference/overview.mdx Imports essential functions and classes from the wreq-js library, including those for making requests, managing sessions, and accessing utilities like profile and OS information. This is the primary way to start using the library's capabilities. ```typescript import { // Core functions fetch, createSession, withSession, websocket, // Utilities getProfiles, getOperatingSystems, // Classes Headers, Request, Response, } from 'wreq-js'; ``` -------------------------------- ### Basic Fetch Request with wreq-js Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/introduction.mdx Demonstrates how to perform a basic fetch request using wreq-js, specifying browser and operating system fingerprints for more authentic network behavior. This is useful for web scraping or interacting with APIs that might block generic HTTP clients. The function takes a URL and an options object, returning a Promise that resolves to a Response object. ```typescript import { fetch } from 'wreq-js'; const response = await fetch('https://example.com/api', { browser: 'chrome_142', os: 'windows', }); console.log(await response.json()); ``` -------------------------------- ### Parsing Server-Sent Events (SSE) with wreq-js Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/guides/streaming.mdx Provides a method to parse Server-Sent Events (SSE) from a response stream using wreq-js. It reads data chunks, decodes them, and buffers incomplete events. Complete events are processed by identifying lines starting with 'data:' and parsing the JSON payload. ```typescript const response = await fetch('https://example.com/events', { browser: 'chrome_142', headers: { Accept: 'text/event-stream' }, }); const reader = response.body?.getReader(); if (!reader) throw new Error('No response body'); const decoder = new TextDecoder(); let buffer = ''; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); // Process complete events const events = buffer.split(' '); buffer = events.pop() || ''; // Keep incomplete event in buffer for (const event of events) { if (event.startsWith('data: ')) { const data = event.slice(6); console.log('Event:', JSON.parse(data)); } } } ``` -------------------------------- ### Make HTTP Requests with fetch() in wreq-js Source: https://context7.com/sqdshguy/wreq-js/llms.txt The primary function for making HTTP requests with browser impersonation. It's compatible with the Fetch API and allows specifying browser/OS profiles, headers, timeouts, and bodies. Supports GET, POST, and other methods, with options for proxies and abort signals. ```typescript import { fetch } from 'wreq-js'; // Basic GET request with Chrome 142 fingerprint on Windows const response = await fetch('https://api.example.com/data', { browser: 'chrome_142', os: 'windows', headers: { 'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', 'X-Api-Key': 'abc123' }, timeout: 10000 }); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const data = await response.json(); console.log('Response data:', data); console.log('Response headers:', Object.fromEntries(response.headers)); console.log('Cookies received:', response.cookies); // POST request with JSON body const postResponse = await fetch('https://api.example.com/submit', { method: 'POST', browser: 'firefox_139', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ username: 'testuser', email: 'test@example.com', preferences: { theme: 'dark', notifications: true } }), timeout: 15000 }); const result = await postResponse.json(); console.log('Created resource:', result); // Request with proxy and abort signal const controller = new AbortController(); setTimeout(() => controller.abort(), 5000); try { const proxyResponse = await fetch('https://geo-restricted-api.example.com/data', { browser: 'safari_18', proxy: 'http://username:password@proxy.example.com:8080', signal: controller.signal, headers: { 'Accept-Language': 'en-US,en;q=0.9' } }); const geoData = await proxyResponse.text(); console.log('Geo-restricted data:', geoData); } catch (error) { if (error.name === 'AbortError') { console.log('Request aborted after timeout'); } else { console.error('Request failed:', error.message); } } ``` -------------------------------- ### Create and Use a Session in TypeScript Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/concepts/sessions.mdx Demonstrates how to create a session using `createSession`, perform authenticated requests, and automatically include cookies from previous requests. The session must be explicitly closed when done. ```typescript import { createSession } from 'wreq-js'; const session = await createSession({ browser: 'chrome_142' }); // All requests share the same cookie jar await session.fetch('https://example.com/login', { method: 'POST', body: new URLSearchParams({ user: 'name', pass: 'secret' }), }); // Cookies from login are automatically included const dashboard = await session.fetch('https://example.com/dashboard'); console.log(await dashboard.text()); // Always close when done await session.close(); ``` -------------------------------- ### Use Custom Headers with Disabled Defaults in TypeScript Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/concepts/browser-profiles.mdx Illustrates how to send a fetch request with completely custom headers by disabling the default browser emulation headers. This is achieved using the `disableDefaultHeaders: true` option along with providing a `headers` object. The example uses 'chrome_142' browser profile but overrides default headers like 'Accept' and 'User-Agent'. ```typescript const response = await fetch('https://api.example.com', { browser: 'chrome_142', headers: { 'Accept': '*/*', 'User-Agent': 'CustomBot/1.0', }, disableDefaultHeaders: true, }); ``` -------------------------------- ### Run Specific Test File (Bash) Source: https://github.com/sqdshguy/wreq-js/blob/master/CONTRIBUTING.md Runs a specific test file within the project's test suite using npm. This allows for focused testing during development. ```bash npm test -- path/to/test.spec.ts ``` -------------------------------- ### Convenience POST Method Source: https://context7.com/sqdshguy/wreq-js/llms.txt The `post()` method offers a simplified way to make POST requests, allowing various body types like strings, Buffers, URLSearchParams, and FormData for cleaner syntax. ```APIDOC ## POST /api ### Description Performs a POST request with a specified body. This method supports various body types for flexibility. ### Method POST ### Endpoint `https://api.example.com/*` (Example endpoints shown in usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (string) - Required - The URL to send the POST request to. - **body** (string | Buffer | URLSearchParams | FormData) - Required - The data to send in the request body. - **options** (object) - Optional - Configuration options for the request, such as headers, timeout, and browser fingerprint. - **browser** (string) - Optional - Specifies the browser fingerprint to use for the request. - **headers** (object) - Optional - Request headers. - **timeout** (number) - Optional - Request timeout in milliseconds. ### Request Example ```json // JSON POST request await post( 'https://api.example.com/auth/login', JSON.stringify({ username: 'admin', password: 'secret123' }), { browser: 'chrome_142', headers: { 'Content-Type': 'application/json' } } ); // Form data POST const formData = new URLSearchParams(); ormData.append('email', 'user@example.com'); formData.append('message', 'Hello from wreq-js'); await post( 'https://api.example.com/contact', formData.toString(), { browser: 'safari_18', headers: { 'Content-Type': 'application/x-www-form-urlencoded' } } ); // Binary POST with Buffer const imageBuffer = Buffer.from([0xFF, 0xD8, 0xFF, 0xE0]); // JPEG header await post( 'https://api.example.com/upload', imageBuffer, { browser: 'chrome_142', headers: { 'Content-Type': 'image/jpeg' }, timeout: 30000 } ); ``` ### Response #### Success Response (200) - **Response** (Response object) - The standard Response object from the Fetch API. #### Response Example ```json // For JSON response const jsonResponse = await post(...); const authResult = await jsonResponse.json(); console.log('Auth token:', authResult.token); // For text response const formResponse = await post(...); console.log('Form submitted:', await formResponse.text()); // For JSON response after upload const uploadResponse = await post(...); const uploadResult = await uploadResponse.json(); console.log('Uploaded to:', uploadResult.url); ``` ``` -------------------------------- ### Basic HTTP Proxy Configuration in TypeScript Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/guides/proxy-usage.mdx Configure a basic HTTP proxy by passing the `proxy` option to the `fetch` function. This routes requests through the specified proxy server. Ensure the proxy URL is correctly formatted. ```typescript import { fetch } from 'wreq-js'; const response = await fetch('https://example.com', { browser: 'chrome_142', proxy: 'http://proxy.example.com:8080', }); ``` -------------------------------- ### fetch() - Make HTTP requests Source: https://github.com/sqdshguy/wreq-js/blob/master/docs/api-reference/overview.mdx The `fetch()` function allows you to make HTTP requests with the ability to customize browser fingerprinting, operating system emulation, proxy settings, and more. It extends the standard Fetch API with additional options. ```APIDOC ## GET /api/fetch ### Description Make HTTP requests with browser fingerprinting. ### Method GET (or other HTTP methods supported by Fetch API) ### Endpoint N/A (This describes a function, not a REST endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (for GET requests) ### Request Example ```typescript import { fetch } from 'wreq-js'; const response = await fetch('https://example.com', { browser: { name: 'chrome', version: '100' }, os: 'windows', proxy: 'http://user:password@host:port', timeout: 5000, disableDefaultHeaders: false, insecure: false }); ``` ### Response #### Success Response (200) - **response** (Response) - The response object from the HTTP request. #### Response Example ```json { "status": 200, "ok": true, "headers": { "Content-Type": "application/json" }, "body": "..." } ``` ```