### Install axios-cookiejar-support Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/README.md Install the necessary packages for axios-cookiejar-support, including axios, tough-cookie, and the support library itself. ```bash npm install axios tough-cookie axios-cookiejar-support ``` -------------------------------- ### Complete Axios CookieJar Configuration Example Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/configuration.md A comprehensive example demonstrating how to wrap Axios with axios-cookiejar-support, configure a CookieJar for session management, set base URLs, timeouts, and default headers. It also shows how cookies are automatically managed for subsequent requests and how to override the jar per request. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; // Create a jar for session management const sessionJar = new CookieJar(); // Create client with jar and default headers const client = wrapper(axios.create({ jar: sessionJar, baseURL: 'https://api.example.com', timeout: 10000, headers: { 'User-Agent': 'MyApp/1.0' } })); // Make authenticated requests - cookies automatically managed const loginResponse = await client.post('/auth/login', { username: 'user@example.com', password: 'password' }); // Subsequent requests automatically include login cookies const profileResponse = await client.get('/user/profile'); // Override jar per request if needed const otherSiteJar = new CookieJar(); const response = await client.get('https://other-site.com/data', { jar: otherSiteJar }); ``` -------------------------------- ### Basic Usage Example Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INDEX.md Demonstrates how to initialize a cookie jar and create an Axios client with cookie support. This client can then be used for making requests that persist cookies. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); await client.get('https://example.com'); ``` -------------------------------- ### Install Wrapper on Axios Instance Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/api-reference/wrapper.md Installs the cookie jar support wrapper on a specific Axios instance. Calling this multiple times on the same instance is safe as the interceptor is only installed once. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; const client = axios.create(); wrapper(client); wrapper(client); // Safe: interceptor only installed once ``` -------------------------------- ### Usage Example for Managed Axios Client Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTEGRATION-GUIDE.md Demonstrates how to instantiate and use the `ManagedClient`, ensuring that the `shutdown` method is called, typically in a `finally` block to guarantee cleanup. ```typescript async function main() { const client = new ManagedClient('https://api.example.com'); try { await client.request({ method: 'GET', url: '/data' }); } finally { await client.shutdown(); } } ``` -------------------------------- ### Login and Subsequent Requests with Session Management Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Maintain authentication across multiple requests by using session cookies. This example shows a login POST request followed by authenticated GET requests. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); // Step 1: Login (sets session cookie in jar) const loginResponse = await client.post('https://api.example.com/auth/login', { username: 'user@example.com', password: 'secure-password' }); console.log('Logged in:', loginResponse.status === 200); // Step 2: Subsequent requests automatically include session cookie const profileResponse = await client.get('https://api.example.com/user/profile'); console.log('Profile:', profileResponse.data); // Step 3: Another request in same session const settingsResponse = await client.get('https://api.example.com/user/settings'); console.log('Settings:', settingsResponse.data); ``` -------------------------------- ### Minimal Reproduction Example Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md This TypeScript code snippet demonstrates how to create a minimal reproduction case for issues with axios-cookiejar-support. It initializes a CookieJar and an Axios client wrapped with cookie support, then makes a GET request. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; // Minimal code that reproduces the issue const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); (async () => { try { await client.get('https://httpbin.org/cookies/set/test/value'); } catch (error) { console.error('Error:', error); } })(); ``` -------------------------------- ### Solution: Using http-cookie-agent with createCookieAgent Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md This example demonstrates how to integrate axios-cookiejar-support with custom HTTP/HTTPS agents, such as proxies, using the `http-cookie-agent` library. It shows how to create compatible agents that handle both proxying and cookie persistence. ```typescript import axios from 'axios'; import { CookieJar } from 'tough-cookie'; import { createCookieAgent } from 'http-cookie-agent'; import HttpProxyAgent from 'http-proxy-agent'; import HttpsProxyAgent from 'https-proxy-agent'; const HttpProxyCookieAgent = createCookieAgent(HttpProxyAgent.HttpProxyAgent); const HttpsProxyCookieAgent = createCookieAgent(HttpsProxyAgent.HttpsProxyAgent); const jar = new CookieJar(); const client = axios.create({ httpAgent: new HttpProxyCookieAgent({ jar: jar, hostname: 'proxy.example.com', port: 8080 }), httpsAgent: new HttpsProxyCookieAgent({ jar: jar, hostname: 'proxy.example.com', port: 8080 }) }); await client.get('https://example.com'); // Uses proxy and handles cookies ``` -------------------------------- ### Project File Structure Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/README.md Illustrates the organization of markdown files within the project repository, including the main README, API documentation, usage examples, and internal details. ```markdown output/ ├── README.md # This file ├── INDEX.md # Document index and navigation ├── API.md # API overview ├── PROJECT.md # Project information ├── types.md # Type definitions ├── configuration.md # Configuration reference ├── errors.md # Error reference ├── USAGE-EXAMPLES.md # Code examples ├── INTEGRATION-GUIDE.md # Integration patterns ├── INTERNALS-AND-TROUBLESHOOTING.md # Deep dive and troubleshooting └── api-reference/ └── wrapper.md # wrapper() function reference ``` -------------------------------- ### Module Augmentation Example Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/types.md Shows how to use TypeScript module augmentation to extend Axios types and enable the 'jar' property after importing and wrapping the library. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; wrapper(axios); // TypeScript now recognizes 'jar' in config const response = await axios.get('https://example.com', { jar: new CookieJar() // No type error }); ``` -------------------------------- ### Using http-cookie-agent with Proxies and Cookie Jars Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/errors.md Provides a resolution for using custom agents (like proxy agents) with cookie jar support by leveraging the 'http-cookie-agent' library. This example shows how to create compatible agents for both HTTP and HTTPS. ```typescript import axios from 'axios'; import { CookieJar } from 'tough-cookie'; import { createCookieAgent } from 'http-cookie-agent'; import HttpProxyAgent from 'http-proxy-agent'; import HttpsProxyAgent from 'https-proxy-agent'; const HttpProxyCookieAgent = createCookieAgent(HttpProxyAgent.HttpProxyAgent); const HttpsProxyCookieAgent = createCookieAgent(HttpsProxyAgent.HttpsProxyAgent); const jar = new CookieJar(); const client = axios.create({ httpAgent: new HttpProxyCookieAgent({ jar, hostname: '127.0.0.1', port: 8080 }), httpsAgent: new HttpsProxyCookieAgent({ jar, hostname: '127.0.0.1', port: 8080 }) }); await client.get('https://example.com'); ``` -------------------------------- ### wrapper(axios) Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/API.md Installs cookie jar support interceptor on an Axios instance or static export. This function modifies the provided Axios object to automatically handle cookies using a `tough-cookie` jar. ```APIDOC ## wrapper(axios) ### Description Installs cookie jar support interceptor on Axios instance or static export. ### Method Function Call ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `axios: T` - Axios static export or instance to wrap ### Returns - `T` - The same Axios object with cookie jar interceptor installed ### Effects - Installs request interceptor for cookie handling - For static export: wraps `axios.create()` to auto-apply interceptor to new instances - Idempotent: safe to call multiple times ### Errors - `Error` - If `config.jar` is invalid or custom agents are used with `jar` ### Request Example ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; // Wrap static wrapper(axios); const jar = new CookieJar(); await axios.get('https://example.com', { jar }); // Wrap instance const client = wrapper(axios.create()); await client.get('https://example.com', { jar: new CookieJar() }); ``` ### Response #### Success Response - `T` - The same Axios object with cookie jar interceptor installed #### Response Example ```typescript // The returned object is the same as the input 'axios' object, but with added functionality. // Example: axios or axios.create() ``` ``` -------------------------------- ### Axios Wrapper for Idempotent Interceptor Installation Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md This wrapper function ensures the request interceptor is installed only once per Axios instance, making multiple calls to the wrapper safe and ensuring new instances also receive the interceptor. ```typescript export function wrapper(axios: T): T { // Check if already wrapped const isWrapped = axios.interceptors.request.handlers?.find( ({ fulfilled }) => fulfilled === requestInterceptor ); if (isWrapped) { return axios; // Already wrapped, return as-is } // Install interceptor axios.interceptors.request.use(requestInterceptor); // For static export, wrap create() method if ('create' in axios) { const create = axios.create.bind(axios); axios.create = (...args) => { const instance = create.apply(axios, args); instance.interceptors.request.use(requestInterceptor); return instance; }; } return axios; } ``` -------------------------------- ### Catching Request-Level Errors Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/errors.md Errors during request setup, such as invalid jar configurations, are thrown synchronously by the wrapper function and can be caught using a standard try/catch block. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; wrapper(axios); try { await axios.get('https://example.com', { jar: true }); // Throws synchronously } catch (error) { console.error('Request setup failed:', error.message); } ``` -------------------------------- ### TypeScript Type Checking with Axios CookieJar Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Demonstrates type-safe configuration for Axios requests when using cookie jar support. Ensure you have axios, axios-cookiejar-support, and tough-cookie installed. ```typescript import axios, { AxiosRequestConfig } from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); // Type-safe configuration const config: AxiosRequestConfig = { jar: new CookieJar(), // ✓ jar is recognized headers: { 'User-Agent': 'MyApp' }, timeout: 5000 }; const response = await client.get('https://example.com', config); ``` -------------------------------- ### Basic Usage of axios-cookiejar-support Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/README.md Demonstrates how to initialize axios with cookie jar support. Import necessary modules, create a CookieJar instance, and wrap the axios client with the provided utility. ```javascript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); await client.get('https://example.com'); ``` -------------------------------- ### Basic Session Management with CookieJar Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/README.md Demonstrates how to set up a client with a CookieJar for session persistence. Use this for managing user sessions after login. ```typescript const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); await client.post('/login', credentials); const profile = await client.get('/profile'); // Session persists ``` -------------------------------- ### Basic Usage with CookieJar Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/API.md Demonstrates how to initialize a CookieJar and pass it to an Axios request configuration. ```typescript import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); await axios.get('https://example.com', { jar }); ``` -------------------------------- ### Instance-level Configuration Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/types.md Demonstrates how to configure a persistent CookieJar for an Axios instance using axios.create. ```typescript const client = axios.create({ jar: new CookieJar() }); ``` -------------------------------- ### Handling Axios Request Errors Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Demonstrates how to handle standard Axios request errors, distinguishing between server responses, network issues, and request setup problems. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); try { const response = await client.get('https://api.example.com/data'); } catch (error) { if (axios.isAxiosError(error)) { if (error.response) { console.error('Server error:', error.response.status, error.response.data); } else if (error.request) { console.error('Request made but no response:', error.request); } else { console.error('Error setting up request:', error.message); } } else { console.error('Unexpected error:', error); } } ``` -------------------------------- ### Build Project Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/PROJECT.md Compiles TypeScript code to the dist/ directory. Use this command to prepare the project for distribution or testing. ```bash pnpm build # Compiles TypeScript to dist/ ``` -------------------------------- ### wrapper Function Signature Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/api-reference/wrapper.md The wrapper function takes an Axios static export or an Axios instance and returns the same type, but with an installed request interceptor for cookie jar support. ```APIDOC ## wrapper Function ### Description The `wrapper` function enables cookie jar support for Axios by installing a request interceptor that automatically manages HTTP cookies using `tough-cookie` and `http-cookie-agent`. It can wrap both the static Axios export and individual Axios instances. ### Signature ```typescript function wrapper(axios: T): T ``` ### Parameters #### Parameters - **axios** (`AxiosStatic | AxiosInstance`) - Required - The Axios static export or an Axios instance to wrap with cookie jar support. ### Return Type `T` (same type as input) — Returns the wrapped Axios object or instance with the request interceptor installed. The return value is type-safe: if you pass an `AxiosStatic`, you get back an `AxiosStatic`; if you pass an `AxiosInstance`, you get back an `AxiosInstance`. ### Behavior The wrapper function: 1. Installs a request interceptor on the provided Axios instance/export 2. For each request with a `jar` option in the config, automatically creates `HttpCookieAgent` and `HttpsCookieAgent` instances 3. Does nothing if the interceptor is already installed (idempotent) 4. If wrapping the static Axios export, also wraps the `create()` method so all new instances get the interceptor automatically 5. Throws an error if custom `httpAgent` or `httpsAgent` are provided alongside a `jar` option ### Throws - **Error: `config.jar` does not accept boolean since `axios-cookiejar-support@2.0.0`.** - Condition: When `config.jar` is set to `true` (legacy boolean behavior) - **Error: `axios-cookiejar-support` does not support for use with other `http(s).Agent`.** - Condition: When `config.httpAgent` or `config.httpsAgent` are provided in the config alongside a `jar` option ``` -------------------------------- ### Initialize Axios with CookieJar Support Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/README.md Use the wrapper function to create an Axios client with built-in cookie jar support. This client automatically handles cookies using the provided CookieJar instance. ```typescript import { wrapper } from 'axios-cookiejar-support'; import axios from 'axios'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); await client.get('https://example.com'); ``` -------------------------------- ### Run Tests Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/PROJECT.md Executes the Vitest test suite. This command ensures the project's functionality meets expectations. ```bash pnpm test # Runs Vitest suite ``` -------------------------------- ### Save and Load Cookie Jars to Database Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTEGRATION-GUIDE.md Functions to persist and retrieve cookie jars using a database for session management. Assumes a database setup with a 'sessions' table. ```typescript // db/cookieStore.ts import { CookieJar } from 'tough-cookie'; import * as db from './database'; interface StoredSession { userId: string; cookies: any; createdAt: Date; updatedAt: Date; } export async function saveCookies(userId: string, jar: CookieJar) { const cookieData = jar.toJSON(); await db.sessions.upsert({ where: { userId }, create: { userId, cookies: cookieData, createdAt: new Date(), updatedAt: new Date() }, update: { cookies: cookieData, updatedAt: new Date() } }); } export async function loadCookies(userId: string): Promise { const session = await db.sessions.findUnique({ where: { userId } }); if (!session) { return null; } return CookieJar.fromJSON(session.cookies); } export async function deleteCookies(userId: string) { await db.sessions.delete({ where: { userId } }); } ``` -------------------------------- ### Agent Creation Overhead in Loops Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md Demonstrates the overhead of creating new agents for each request when using a cookie jar. Consider reusing the client for multiple requests to improve performance. ```typescript for (let i = 0; i < 100; i++) { await client.get('https://example.com'); // 2 agents created and discarded per request } // Consider reusing client if making many requests const results = await Promise.all([ ...Array(100).fill(0).map(() => client.get('https://example.com')) ]); ``` -------------------------------- ### Wrap Axios Static Export and Instance Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/API.md Demonstrates how to wrap both the static Axios export and a created Axios instance to enable cookie jar support. The `jar` option must be provided in the request config. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; // Wrap static wrapper(axios); const jar = new CookieJar(); await axios.get('https://example.com', { jar }); // Wrap instance const client = wrapper(axios.create()); await client.get('https://example.com', { jar: new CookieJar() }); ``` -------------------------------- ### Wrap Axios with Cookie Jar Support Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INDEX.md Use the wrapper function to enable cookie jar support for static Axios or Axios instances. This function installs a request interceptor to handle cookies automatically. ```typescript import { wrapper } from 'axios-cookiejar-support'; import axios from 'axios'; import { CookieJar } from 'tough-cookie'; // Wrap static Axios wrapper(axios); // Or wrap an instance const client = wrapper(axios.create({ jar: new CookieJar() })); ``` -------------------------------- ### Use Async Cookie Store with Axios Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/MIGRATION.md Demonstrates how to configure Axios to use an asynchronous cookie store like RedisCookieStore with http-cookie-agent. Ensure Node.js version compatibility. ```javascript import axios from 'axios'; import { CookieJar } from 'tough-cookie'; import redis from 'redis'; import RedisCookieStore from 'redis-cookie-store'; import { HttpCookieAgent, HttpsCookieAgent } from 'http-cookie-agent/node:http'; const redisClient = redis.createClient(); const store = new RedisCookieStore(redisClient); const jar = new CookieJar(store); const client = axios.create({ httpAgent: new HttpCookieAgent({ cookies: { async_UNSTABLE: true, jar } }), httpsAgent: new HttpsCookieAgent({ cookies: { async_UNSTABLE: true, jar } }), }); await client.get('https://example.com'); ``` -------------------------------- ### Diagnosing Cookies Not Sent: Jar Not Passed in Request Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md This example highlights the importance of explicitly passing the cookie jar in the request configuration. If the jar is only set in the Axios instance configuration but not in individual requests, cookies will not be sent. ```typescript // Wrong: jar in instance config but not in request const client = axios.create({ jar }); await client.get('https://example.com'); // No jar passed to this request // Right: jar passed in request config await client.get('https://example.com', { jar }); ``` -------------------------------- ### Create Multi-Tenant HTTP Client Factory Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTEGRATION-GUIDE.md Implement a factory pattern to create isolated HTTP clients for different tenants. Each client has its own cookie jar. ```typescript // http/clientFactory.ts import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; class ClientFactory { private clients: Map = new Map(); getClient(tenantId: string, apiKey: string) { if (!this.clients.has(tenantId)) { const jar = new CookieJar(); const client = wrapper(axios.create({ jar: jar, baseURL: `https://api.example.com/tenants/${tenantId}`, headers: { 'Authorization': `Bearer ${apiKey}`, 'X-Tenant-ID': tenantId } })); this.clients.set(tenantId, client); } return this.clients.get(tenantId); } clearClient(tenantId: string) { this.clients.delete(tenantId); } } export default new ClientFactory(); ``` -------------------------------- ### Instantiate CookieJar Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/configuration.md Instantiate a CookieJar from the 'tough-cookie' package. This is required to enable automatic cookie handling. ```typescript import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); ``` -------------------------------- ### Create Single Global HTTP Client Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTEGRATION-GUIDE.md Set up a reusable HTTP client with cookie jar support. This is useful for applications with a single API endpoint. ```typescript // http/client.ts import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const httpClient = wrapper(axios.create({ jar: jar, baseURL: process.env.API_BASE_URL || 'https://api.example.com', timeout: 30000, headers: { 'User-Agent': 'MyApp/1.0', 'Accept': 'application/json' } })); export default httpClient; ``` -------------------------------- ### Import Wrapper Function (ESM) Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/API.md This snippet demonstrates how to import the `wrapper` function using ES modules (ESM), which is the recommended way to use the library. ```typescript // ESM - always use this import { wrapper } from 'axios-cookiejar-support'; ``` -------------------------------- ### Instance Configuration with CookieJar Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/API.md Configure an Axios instance with a CookieJar for all subsequent requests made by that instance. ```typescript const client = wrapper(axios.create({ jar: new CookieJar(), baseURL: 'https://api.example.com' })); ``` -------------------------------- ### Initialize CookieJar with Custom Store (Synchronous) Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/configuration.md Initialize a CookieJar with a custom synchronous store for persistent or asynchronous cookie storage. Note: As of v4.0.0, only synchronous stores are supported directly. For asynchronous stores, consider using http-cookie-agent directly. ```typescript import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(asyncStore); ``` -------------------------------- ### Wrapping Axios Early in Application Entry Point Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md Apply the `wrapper()` function to the static `axios` instance in your application's entry point to ensure all subsequent imports use the wrapped version. This prevents issues with unwrapped instances. ```typescript // index.ts or main.ts - first file executed import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; wrapper(axios); // Now import other modules import './services'; import './api-clients'; ``` -------------------------------- ### Use Multi-Tenant HTTP Client Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTEGRATION-GUIDE.md Obtain a tenant-specific client from the factory and make requests. This ensures requests for different tenants do not share cookies. ```typescript import clientFactory from '../http/clientFactory'; export async function getOrganizationData(tenantId: string, apiKey: string) { const client = clientFactory.getClient(tenantId, apiKey); const response = await client.get('/organization'); return response.data; } ``` -------------------------------- ### Format Code Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/PROJECT.md Applies code formatting using ESLint and Prettier. This command ensures code style consistency across the project. ```bash pnpm format # Runs ESLint and Prettier ``` -------------------------------- ### Axios Client with Proxy Support and CookieJar Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/README.md Illustrates how to configure an Axios client to use a proxy agent that also supports cookie management. This is essential when requests must go through a proxy server. ```typescript import { createCookieAgent } from 'http-cookie-agent'; import ProxyAgent from 'http-proxy-agent'; const ProxyCookieAgent = createCookieAgent(ProxyAgent); const client = axios.create({ httpAgent: new ProxyCookieAgent({ jar, hostname: 'proxy' }), httpsAgent: new ProxyCookieAgent({ jar, hostname: 'proxy' }) }); ``` -------------------------------- ### Universal Code for Browser and Node.js Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md Shows how to write code that works in both browser and Node.js environments using axios-cookiejar-support. The wrapper handles environment-specific imports. ```typescript import { wrapper } from 'axios-cookiejar-support'; // Browser: imports noop.js (does nothing) // Node.js: imports dist/index.js (adds cookie support) ``` ```typescript import { wrapper } from 'axios-cookiejar-support'; // Safe in both browsers and Node.js const client = wrapper(axios.create()); ``` -------------------------------- ### CommonJS Usage in Node.js Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Demonstrates how to use axios-cookiejar-support with CommonJS modules in compatible Node.js versions. ```javascript const axios = require('axios'); const { wrapper } = require('axios-cookiejar-support'); const { CookieJar } = require('tough-cookie'); const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); client.get('https://example.com').then(response => { console.log(response.status); }).catch(error => { console.error('Error:', error.message); }); ``` -------------------------------- ### Implementing a Persistent CookieJar with a Database Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md Create a custom CookieJar that extends `tough-cookie`'s `CookieJar` and integrates with a database (e.g., `better-sqlite3`) for persistent cookie storage. This provides robust cookie management across restarts. ```typescript import { CookieJar } from 'tough-cookie'; import { Database } from 'better-sqlite3'; const db = new Database('cookies.db'); class PersistentCookieJar extends CookieJar { private db: Database; constructor(db: Database) { super(); this.db = db; this.loadFromDb(); } async setCookie(cookieString: string, url: string) { const cookie = await super.setCookie(cookieString, url); this.saveToDb(); return cookie; } private loadFromDb() { // Load cookies from database } private saveToDb() { // Save cookies to database } } ``` -------------------------------- ### Reuse Axios Client Instance Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Demonstrates creating a single Axios client instance with cookie support and reusing it across multiple function calls for efficiency. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; // Create once const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); // Reuse across multiple function calls async function fetchData(id) { return client.get(`https://api.example.com/data/${id}`); } async function main() { const item1 = await fetchData(1); const item2 = await fetchData(2); const item3 = await fetchData(3); } ``` -------------------------------- ### Solution: Using CookieJar Instance Instead of Boolean Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md Demonstrates the correct way to enable cookie support in axios-cookiejar-support v2.0.0 and later. Replace boolean `true` with an actual `CookieJar` instance in the request configuration. ```typescript import { CookieJar } from 'tough-cookie'; // Before (v1.x) const response = await axios.get('https://example.com', { jar: true }); // After (v2.x+) const jar = new CookieJar(); const response = await axios.get('https://example.com', { jar }); ``` -------------------------------- ### Cross-Domain Cookie Handling with Axios Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Demonstrates how the cookie jar respects domain and path rules, preventing cookies from being sent to mismatched domains. Cookies are automatically sent back to the originating domain. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); // Request to domain 1 const response1 = await client.get('https://api1.example.com'); // Response sets: Set-Cookie: api1_cookie=value1 // Request to domain 2 (different domain) const response2 = await client.get('https://api2.example.com'); // Cookie from api1.example.com is NOT sent (domain mismatch) // Request back to domain 1 const response3 = await client.get('https://api1.example.com/data'); // Cookie api1_cookie=value1 IS sent automatically ``` -------------------------------- ### Multiple Independent Sessions with CookieJar Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/README.md Shows how to create and manage multiple independent sessions using separate CookieJar instances for different clients. Useful when interacting with multiple distinct services. ```typescript const jar1 = new CookieJar(); const jar2 = new CookieJar(); const client1 = wrapper(axios.create({ jar: jar1 })); const client2 = wrapper(axios.create({ jar: jar2 })); ``` -------------------------------- ### Save and Restore Cookie Jars Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Demonstrates how to save a cookie jar to a file and restore it later. This is useful for persisting session cookies between application runs. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; import fs from 'node:fs'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); // Make requests (cookies stored) await client.get('https://example.com'); // Save jar to file const jarData = jar.toJSON(); fs.writeFileSync('cookies.json', JSON.stringify(jarData, null, 2)); // Later: restore from file const savedData = JSON.parse(fs.readFileSync('cookies.json', 'utf-8')); const restoredJar = CookieJar.fromJSON(savedData); const restoredClient = wrapper(axios.create({ jar: restoredJar })); // Continue with restored cookies const response = await restoredClient.get('https://example.com'); ``` -------------------------------- ### Lazy CookieJar Creation Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Shows how to create a CookieJar only when it's first needed to improve performance for applications that might not always require cookie support. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; let jar = null; function getClient() { if (!jar) { jar = new CookieJar(); return wrapper(axios.create({ jar })); } return wrapper(axios.create({ jar })); } // First call creates jar const client1 = getClient(); await client1.get('https://example.com'); // Subsequent calls reuse jar const client2 = getClient(); ``` -------------------------------- ### Use Single Global HTTP Client Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTEGRATION-GUIDE.md Import and use the pre-configured global HTTP client in your services. Ensures consistent cookie handling across requests. ```typescript // services/user.ts import httpClient from '../http/client'; export async function getProfile() { const response = await httpClient.get('/user/profile'); return response.data; } // services/data.ts import httpClient from '../http/client'; export async function fetchData() { const response = await httpClient.get('/data'); return response.data; } ``` -------------------------------- ### Enable Cookie Support on Axios Instance Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INDEX.md Wrap an Axios instance to enable cookie support. Ensure you have a CookieJar instance available. ```typescript const client = wrapper(axios.create({ jar: new CookieJar() })); ``` -------------------------------- ### Use CookieJar Instance Instead of Boolean Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/MIGRATION.md Illustrates the change in `config.jar` usage from v2.0.0 onwards, requiring an instance of `CookieJar` instead of a boolean value. ```diff // Cannot use boolean as config.jar since v2.x + const cookieJar = new CookieJar(); axios.get('https://example.com', { - jar: true, + jar: cookieJar, }); ``` -------------------------------- ### Combined Configuration Options Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/types.md Illustrates passing the 'jar' option along with other standard Axios request configurations like headers, timeout, and responseType. ```typescript await axios.get('https://example.com', { jar: new CookieJar(), headers: { 'User-Agent': 'MyApp/1.0' }, timeout: 5000, responseType: 'json' }); ``` -------------------------------- ### Cookie Jar Size Performance Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTERNALS-AND-TROUBLESHOOTING.md Illustrates the performance impact of adding and retrieving cookies from a large cookie jar. Performance degrades as the jar size increases. ```typescript const jar = new CookieJar(); // Adding many cookies for (let i = 0; i < 10000; i++) { await jar.setCookie(`cookie${i}=value`, `https://example.com/path/${i}`); } // Retrieving from large jar const cookies = await jar.getCookies('https://example.com'); // Getting slower as jar size increases ``` -------------------------------- ### Handling Library Configuration Errors Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Shows how to catch configuration-related errors thrown by the axios-cookiejar-support library, such as invalid jar values or incompatible agent usage. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; import http from 'node:http'; wrapper(axios); // Error 1: Invalid jar value (boolean) try { await axios.get('https://example.com', { jar: true // Invalid: must be CookieJar instance }); } catch (error) { if (error instanceof Error && error.message.includes('does not accept boolean')) { console.error('Configuration error: jar must be a CookieJar instance'); } } // Error 2: Custom agent with jar try { await axios.get('https://example.com', { jar: new CookieJar(), httpAgent: new http.Agent() // Incompatible with jar }); } catch (error) { if (error instanceof Error && error.message.includes('does not support for use with other')) { console.error('Cannot use custom agent with jar option'); } } ``` -------------------------------- ### Timeout and Retry Patterns with Axios CookieJar Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Shows how to integrate axios-cookiejar-support with custom timeout and retry logic, including exponential backoff for failed requests. Ensures requests are retried with increasing delays up to a maximum number of attempts. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar: jar, timeout: 5000 })); async function requestWithRetry(url, maxRetries = 3) { let attempt = 0; while (attempt < maxRetries) { try { return await client.get(url); } catch (error) { attempt++; if (attempt >= maxRetries) throw error; // Exponential backoff const delay = Math.pow(2, attempt) * 1000; await new Promise(resolve => setTimeout(resolve, delay)); } } } const response = await requestWithRetry('https://api.example.com/data'); ``` -------------------------------- ### Request-level Configuration Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/types.md Shows how to apply a CookieJar to a single Axios request. ```typescript await axios.get('https://example.com', { jar: new CookieJar() }); ``` -------------------------------- ### Wrap Axios Instance for Specific Context Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/api-reference/wrapper.md Create an Axios instance and wrap it with cookie jar support for use in a specific context. This allows for isolated cookie management. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); const response = await client.get('https://example.com'); ``` -------------------------------- ### wrapper() function Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/COMPLETION-SUMMARY.txt The primary exported function `wrapper()` is the main entry point for using the axios-cookiejar-support library. It allows for enhanced Axios request configuration, particularly for managing cookies via a jar. ```APIDOC ## wrapper() ### Description This function enhances Axios requests with cookie jar support, allowing for persistent cookie management across requests. ### Method N/A (Function Call) ### Parameters #### Function Parameters - **axiosInstance** (AxiosInstance) - Required - An instance of Axios to enhance. - **options** (object) - Optional - Configuration options for the cookie jar and request. - **jar** (tough.CookieJar) - Optional - A pre-configured cookie jar instance. - **cookiePath** (string) - Optional - Path to a file where the cookie jar will be stored/loaded from. - **removeEmptyCookies** (boolean) - Optional - If true, empty cookies will be removed. - ** αυτόματη αποθήκευση** (boolean) - Optional - If true, the cookie jar will be automatically saved. - **...other AxiosRequestConfig** - Any valid Axios request configuration options. ### Request Example ```javascript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create(), { jar: jar, // or cookiePath: './cookies.json' }); client.get('https://example.com/login').then(response => { console.log('Cookies after login:', jar.getCookiesSync('https://example.com')); }); ``` ### Response #### Return Value - **AxiosInstance** - An enhanced Axios instance with cookie jar support enabled. #### Error Conditions - **Boolean jar rejection error**: Occurs when a boolean value is provided for the `jar` option instead of a `tough.CookieJar` instance. - **Custom agent conflict error**: May occur if custom agents are used in a way that conflicts with cookie jar management. - **File system errors**: If `cookiePath` is provided and there are issues reading from or writing to the specified file. ``` -------------------------------- ### Import Wrapper Function (CommonJS) Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/API.md Import the `wrapper` function using `require` for CommonJS environments, compatible with Node.js versions 20.19.0+ or 22.12.0+. ```javascript const { wrapper } = require('axios-cookiejar-support'); ``` -------------------------------- ### Data Flow Diagram Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/PROJECT.md Illustrates the data flow within the axios-cookiejar-support library, from request interception to cookie storage and transmission. ```text wrapper(axios) ↓ Installs request interceptor ↓ Request made with jar option ↓ Interceptor creates cookie agents ↓ Agents handle cookie storage/transmission ↓ Response includes Set-Cookie headers ↓ Cookies stored in jar ↓ Next request to same origin ↓ Agents retrieve cookies from jar ↓ Cookies sent in Cookie header ``` -------------------------------- ### Request with Custom Axios Config Options Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/USAGE-EXAMPLES.md Demonstrates combining a CookieJar with other Axios configuration options such as headers, timeouts, POST data, and response types. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); // GET with headers and timeout const response1 = await client.get('https://api.example.com/data', { headers: { 'Authorization': 'Bearer token123', 'Accept': 'application/json' }, timeout: 5000 }); // POST with data and validation const response2 = await client.post('https://api.example.com/data', { name: 'John', age: 30 }, { headers: { 'Content-Type': 'application/json' }, validateStatus: (status) => status < 500 } ); // Request with custom response type const response3 = await client.get('https://api.example.com/file', { responseType: 'blob' }); ``` -------------------------------- ### Create Environment-Specific Axios Clients Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTEGRATION-GUIDE.md Factory function to create Axios clients with different configurations for development and production environments. It utilizes tough-cookie for cookie management. ```typescript // http/clientFactory.ts import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; function createClient(environment: 'development' | 'production') { const jar = new CookieJar(); const baseConfig = { jar: jar, timeout: 30000 }; const envConfig = environment === 'production' ? { baseURL: 'https://api.example.com', headers: { 'User-Agent': 'MyApp/1.0 (production)' } } : { baseURL: 'http://localhost:3000', headers: { 'User-Agent': 'MyApp/1.0 (development)' } }; return wrapper(axios.create({ ...baseConfig, ...envConfig })); } const client = createClient(process.env.NODE_ENV as any || 'development'); export default client; ``` -------------------------------- ### Managed Axios Client with Lifecycle Management Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTEGRATION-GUIDE.md Implement a managed client that wraps Axios and provides a clean shutdown mechanism. This ensures resources, like the cookie jar, are properly handled. ```typescript // http/ManagedClient.ts import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; export class ManagedClient { private jar: CookieJar; private client: any; private isActive = true; constructor(baseURL?: string) { this.jar = new CookieJar(); this.client = wrapper(axios.create({ jar: this.jar, baseURL: baseURL })); } async request(config: any) { if (!this.isActive) { throw new Error('Client is shut down'); } return this.client(config); } async shutdown() { this.isActive = false; // Optional: save cookies or clean up const cookies = await this.jar.getCookies(''); console.log(`Shutdown with ${cookies.length} cookies`); } getJar() { return this.jar; } } ``` -------------------------------- ### Wrap Axios Instance or Static Export Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/configuration.md Use the wrapper function to integrate cookie support with either the static Axios export or a created Axios instance. No configuration options are passed to the wrapper function itself. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; // Wrap static export wrapper(axios); // Or wrap instance const client = axios.create(); wrapper(client); ``` -------------------------------- ### Combine Cookie Jar with Proxy Agents Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/INTEGRATION-GUIDE.md Use http-cookie-agent to create custom agents that support both cookie jars and proxy configurations. This approach requires manual agent management. ```typescript // http/proxyClient.ts import axios from 'axios'; import { CookieJar } from 'tough-cookie'; import { createCookieAgent } from 'http-cookie-agent'; import HttpProxyAgent from 'http-proxy-agent'; import HttpsProxyAgent from 'https-proxy-agent'; const HttpProxyCookieAgent = createCookieAgent(HttpProxyAgent.HttpProxyAgent); const HttpsProxyCookieAgent = createCookieAgent(HttpsProxyAgent.HttpsProxyAgent); const jar = new CookieJar(); const proxyClient = axios.create({ httpAgent: new HttpProxyCookieAgent({ jar: jar, hostname: process.env.PROXY_HOST, port: parseInt(process.env.PROXY_PORT || '8080'), auth: process.env.PROXY_AUTH }), httpsAgent: new HttpsProxyCookieAgent({ jar: jar, hostname: process.env.PROXY_HOST, port: parseInt(process.env.PROXY_PORT || '8080'), auth: process.env.PROXY_AUTH }) }); export default proxyClient; ``` -------------------------------- ### Instance-Level Cookie Jar Configuration Source: https://github.com/3846masa/axios-cookiejar-support/blob/main/_autodocs/configuration.md Set the `jar` option when creating an Axios instance to apply a cookie jar to all requests made with that instance. Ensure `axios-cookiejar-support` and `tough-cookie` are imported. ```typescript import axios from 'axios'; import { wrapper } from 'axios-cookiejar-support'; import { CookieJar } from 'tough-cookie'; const jar = new CookieJar(); const client = wrapper(axios.create({ jar })); // Both requests use the same jar await client.get('https://example.com/login'); await client.get('https://example.com/profile'); ```