### PNPM Installation Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Install the library using PNPM. A fast, disk-space-efficient package manager. ```bash pnpm add user-agents ``` -------------------------------- ### Dataset Configuration Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Example of configuring the dataset used by the library. Allows specifying a custom dataset file. ```javascript const UserAgent = require('user-agents'); // Load a custom dataset const ua = new UserAgent({ datasetPath: '/path/to/your/custom-user-agents.json' }); console.log(ua.toString()); ``` -------------------------------- ### Performance Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Demonstrates generating a User-Agent string efficiently. While the library is generally fast, this highlights basic usage. ```javascript const UserAgent = require('user-agents'); console.time('generateUA'); const ua = new UserAgent(); console.timeEnd('generateUA'); console.log(ua.toString()); ``` -------------------------------- ### Install Dependencies Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Installs project dependencies using npm. ```bash # Install dependencies npm install ``` -------------------------------- ### Device Category Example (Desktop) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for a desktop device. This is the default if no category is specified. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ deviceCategory: 'desktop' }); console.log(ua.toString()); ``` -------------------------------- ### Platform-Specific Example (iPhone) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for an iPhone. Useful for simulating iPhone browser environments. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ platform: 'iphone' }); console.log(ua.toString()); ``` -------------------------------- ### Install user-agents with NPM Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Install the user-agents library using NPM. This is the standard package manager for Node.js. ```bash npm install user-agents ``` -------------------------------- ### Platform-Specific Example (iPad) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for an iPad. Useful for simulating iPad browser environments. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ platform: 'ipad' }); console.log(ua.toString()); ``` -------------------------------- ### Install user-agents with Yarn Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Install the user-agents library using Yarn. Yarn is an alternative package manager for Node.js. ```bash yarn add user-agents ``` -------------------------------- ### Install user-agents with PNPM Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Install the user-agents library using PNPM. PNPM is a fast, disk-space-efficient package manager for Node.js. ```bash pnpm install user-agents ``` -------------------------------- ### Example: Accessing App Name Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Demonstrates how to access the appName property from a UserAgent instance and compare it with navigator.appName. ```javascript const userAgent = new UserAgent(); console.log(userAgent.data.appName); // 'Netscape' console.log(navigator.appName); // 'Netscape' ``` -------------------------------- ### Install User Agents with npm, pnpm, or yarn Source: https://github.com/intoli/user-agents/blob/main/README.md Install the User Agents package using your preferred JavaScript package manager. ```bash # With npm: npm install user-agents # With pnpm: pnpm install user-agents # With yarn: yarn add user-agents ``` -------------------------------- ### Testing Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a specific User-Agent for testing purposes. Allows for precise control over the environment being simulated. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ platform: 'linux', browserName: 'firefox' }); console.log(ua.toString()); ``` -------------------------------- ### Environment Variable Configuration Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Configuration using environment variables. Allows dynamic setting of options without code changes. ```bash # Example: Set dataset path via environment variable export USER_AGENTS_DATASET_PATH=/path/to/custom/user-agents.json # Example: Set cache directory export USER_AGENTS_CACHE_DIR=/tmp/user-agents-cache ``` -------------------------------- ### Platform-Specific Example (Linux) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for a Linux operating system. Useful for testing Linux-specific web content. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ platform: 'linux' }); console.log(ua.toString()); ``` -------------------------------- ### Generate a Random User Agent Source: https://github.com/intoli/user-agents/blob/main/_autodocs/OVERVIEW.md Import the UserAgent class and create a new instance to generate a random user agent string. This is the most basic way to get started. ```javascript import UserAgent from 'user-agents'; const userAgent = new UserAgent(); console.log(userAgent.toString()); // Output: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... ``` -------------------------------- ### Filter Usage Guide Source: https://github.com/intoli/user-agents/blob/main/_autodocs/README.md A comprehensive guide to using filters for selecting user agents. ```APIDOC ## Filter Usage Guide ### Description This guide covers all filter format types with examples, enabling users to precisely select user agents based on various criteria. ### Filter Types and Examples - **Object Filters**: Supports simple and nested object structures. - **RegExp Filters**: Allows for basic and complex regular expression matching. - **String Filters**: Enables filtering based on exact string matches. - **Function Filters**: Provides the ability to use custom logic for filtering. - **Array Filters**: Facilitates combining multiple filters. ### Real-world Examples Demonstrates practical applications of filters in various scenarios. ### Error Handling for Filters Details how errors related to filters are handled. ### Performance Considerations Discusses performance implications of different filtering strategies. ### Debugging Techniques Offers methods for debugging filter logic. ``` -------------------------------- ### UserAgentData Interface Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Demonstrates the structure of the UserAgentData interface, showing all available fields for a User-Agent object. ```typescript interface UserAgentData { appName: string; browserName: string; browserVersion: string; deviceCategory: 'desktop' | 'mobile' | 'tablet'; platform: string; platformVersion: string; osName: string; osVersion: string; vendor: string; vendorVersion: string; architecture: string; model: string; brand: string; engineName: string; engineVersion: string; cpuClass: string; platformClass: string; mobile: boolean; tablet: boolean; smarttv: boolean; wearable: boolean; embedded: boolean; console: boolean; tv: boolean; bot: boolean; layoutEngine: string; layoutEngineVersion: string; layoutEngineName: string; layoutEngineVendor: string; layoutEngineVendorVersion: string; layoutEngineArchitecture: string; layoutEngineModel: string; layoutEngineBrand: string; layoutEngineCPUClass: string; layoutEnginePlatformVersion: string; layoutEngineOSName: string; layoutEngineOSVersion: string; layoutEngineMobile: boolean; layoutEngineTablet: boolean; layoutEngineSmartTV: boolean; layoutEngineWearable: boolean; layoutEngineEmbedded: boolean; layoutEngineConsole: boolean; layoutEngineTV: boolean; layoutEngineBot: boolean; connection: { downlink: number; effectiveType: 'slow-2g' | '2g' | '3g' | '4g'; rtt: number; type: 'bluetooth' | 'cellular' | 'ethernet' | 'none' | 'wifi' | 'wimax' | 'other' | 'vpn'; }; screen: { height: number; width: number; colorDepth: number; pixelDepth: number; }; pluginsLength: number; plugins: string[]; languages: string[]; language: string; oscpu: string; vendor: string; weight: number; ua: string; toString: () => string; toJSON: () => UserAgentData; } ``` -------------------------------- ### Screen Size Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string with specific screen dimensions. Useful for testing responsive design elements. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ screen: { height: 1080, width: 1920, }, }); console.log(ua.toString()); ``` -------------------------------- ### Platform-Specific Example (Windows) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for a Windows operating system. Useful for testing Windows-specific web content. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ platform: 'win' }); console.log(ua.toString()); ``` -------------------------------- ### Platform-Specific Example (macOS) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for a macOS operating system. Useful for testing macOS-specific web content. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ platform: 'macos' }); console.log(ua.toString()); ``` -------------------------------- ### Install Latest TypeScript Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Ensure you have TypeScript 4.0 or later installed to avoid potential type errors when using the user-agents library with TypeScript. ```bash npm install --save-dev typescript@latest ``` -------------------------------- ### Device Category Example (Tablet) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for a tablet device. Useful for simulating tablet browser environments. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ deviceCategory: 'tablet' }); console.log(ua.toString()); ``` -------------------------------- ### Example: Accessing OS/CPU Info Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Shows how to access the oscpu property, which typically returns a string like 'Windows NT 10.0; Win64; x64' on Windows or null on other systems. ```javascript const userAgent = new UserAgent(); console.log(userAgent.data.oscpu); // 'Windows NT 10.0; Win64; x64' or null ``` -------------------------------- ### Batch Generation Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate multiple User-Agent strings at once. Useful for performance testing or creating diverse datasets. ```javascript const UserAgent = require('user-agents'); const uas = UserAgent.parse('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'); console.log(uas.random(10)); ``` -------------------------------- ### Browser-Specific Example (Safari) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for the Safari browser. Useful for testing Safari-specific web features. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ browserName: 'safari' }); console.log(ua.toString()); ``` -------------------------------- ### TypeScript Configuration Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Configuration for TypeScript projects using the user-agents library. Ensures proper type checking and module resolution. ```json { "compilerOptions": { "target": "es2018", "module": "commonjs", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "outDir": "./dist", "rootDir": "./src" }, "include": [ "src/**/*.ts" ], "exclude": [ "node_modules" ] } ``` -------------------------------- ### Filter by Platform Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Matches a single property with an exact value. This example filters for the 'Win32' platform. ```javascript // Filter by platform const windows = new UserAgent({ platform: 'Win32' }); console.log(windows().platform); // Always 'Win32' ``` -------------------------------- ### Generate Desktop User Agents Source: https://github.com/intoli/user-agents/blob/main/_autodocs/examples.md Provides an example for generating user agents that simulate desktop environments. It shows how to access platform and screen width, which are typical for desktops. ```javascript import UserAgent from 'user-agents'; const desktop = new UserAgent({ deviceCategory: 'desktop' }); console.log(desktop.data.platform); // Win32 or MacIntel or Linux console.log(desktop.data.screenWidth); // Usually >= 1024px ``` -------------------------------- ### Example: Accessing Platform and Filtering Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Demonstrates accessing the platform property and filtering UserAgent instances by specific platforms like 'Win32', 'MacIntel', 'iPhone', 'iPad', or using a regex for any Linux platform. ```javascript const userAgent = new UserAgent(); console.log(userAgent.data.platform); // 'Win32' // Filter by platform const windows = new UserAgent({ platform: 'Win32' }); const mac = new UserAgent({ platform: 'MacIntel' }); const iphone = new UserAgent({ platform: 'iPhone' }); const ipad = new UserAgent({ platform: 'iPad' }); // Filter by any Linux platform const linux = new UserAgent({ platform: /Linux/ }); ``` -------------------------------- ### Browser-Specific Example (Edge) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for the Edge browser. Useful for testing Edge-specific web features. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ browserName: 'edge' }); console.log(ua.toString()); ``` -------------------------------- ### Filter Type Example (String) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Use a string as a filter to match a User-Agent. This is the simplest form of filtering. ```javascript const UserAgent = require('user-agents'); const ua = UserAgent.parse('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'); console.log(ua.toString()); ``` -------------------------------- ### Network Condition Example (WiFi) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string simulating a WiFi network connection. Useful for testing performance on stable, high-speed networks. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ connection: 'wifi' }); console.log(ua.toString()); ``` -------------------------------- ### Browser-Specific Example (Firefox) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for the Firefox browser. Useful for testing Firefox-specific web features. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ browserName: 'firefox' }); console.log(ua.toString()); ``` -------------------------------- ### Browser-Specific Example (Chrome) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string for the Chrome browser. Useful for testing Chrome-specific web features. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ browserName: 'chrome' }); console.log(ua.toString()); ``` -------------------------------- ### Device Category Example (Mobile) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string specifically for a mobile device. Useful for simulating mobile browser environments. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ deviceCategory: 'mobile' }); console.log(ua.toString()); ``` -------------------------------- ### Error Handling Example (UserAgent.random()) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Use UserAgent.random() to handle cases where no matching user agents are found, preventing errors. ```javascript const UserAgent = require('user-agents'); // This will return a random UserAgent instance or null if no matches are found const ua = UserAgent.random(); if (ua) { console.log(ua.toString()); } else { console.log('No user agents matched the criteria.'); } ``` -------------------------------- ### Example: Accessing Connection Properties Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Shows how to access and log various network connection properties like downlink, effectiveType, rtt, and type. Also demonstrates filtering UserAgent instances by connection type. ```javascript const userAgent = new UserAgent(); console.log(userAgent.data.connection.downlink); // 10 console.log(userAgent.data.connection.effectiveType); // '4g' console.log(userAgent.data.connection.rtt); // 50 console.log(userAgent.data.connection.type); // 'wifi' // Filter for specific connection types const fourG = new UserAgent({ connection: { effectiveType: '4g' } }); const wifi = new UserAgent({ connection: { type: 'wifi' } }); ``` -------------------------------- ### Example: Accessing Language Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Demonstrates how to access the language property from a UserAgent instance. The output can be a language string like 'en-US' or null. ```javascript const userAgent = new UserAgent(); console.log(userAgent.data.language); // 'en-US' or null ``` -------------------------------- ### Network Condition Example (3G) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string simulating a 3G network connection. Useful for testing performance on slower networks. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ connection: '3g' }); console.log(ua.toString()); ``` -------------------------------- ### Network Condition Example (4G) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string simulating a 4G network connection. Useful for testing performance on typical mobile networks. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ connection: '4g' }); console.log(ua.toString()); ``` -------------------------------- ### RegExp Filter Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/OVERVIEW.md Employ RegExp filters to match patterns within the user agent string. ```javascript const userAgent = new UserAgent(/Chrome/); ``` -------------------------------- ### String Filter Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/OVERVIEW.md Utilize string filters for exact value matching on specific properties like the platform. ```javascript const userAgent = new UserAgent({ platform: 'Win32' }); ``` -------------------------------- ### Generate Mobile User Agents Source: https://github.com/intoli/user-agents/blob/main/_autodocs/examples.md Illustrates how to generate user agents specifically for mobile devices. Includes examples for single and multiple generations, and verification of the device category. ```javascript import UserAgent from 'user-agents'; const mobile = new UserAgent({ deviceCategory: 'mobile' }); // Single generation console.log(mobile()); // Multiple generations for (let i = 0; i < 5; i++) { console.log(mobile().toString()); } // Verify all match filter console.log(mobile().deviceCategory); // Always 'mobile' ``` -------------------------------- ### Error Handling Example (try-catch) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Handle potential errors when generating User-Agent strings using a try-catch block. This is crucial for robust applications. ```javascript const UserAgent = require('user-agents'); try { const ua = new UserAgent({ invalidOption: 'someValue' }); console.log(ua.toString()); } catch (error) { console.error('Error generating user agent:', error.message); } ``` -------------------------------- ### Network Condition Example (Cellular) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string simulating a cellular network connection. Useful for testing performance on mobile carrier networks. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ connection: 'cellular' }); console.log(ua.toString()); ``` -------------------------------- ### Get All UserAgentData Properties Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Instantiate a UserAgent and access its data property to retrieve all available information. Use JSON.stringify for easy viewing. ```javascript import UserAgent from 'user-agents'; const userAgent = new UserAgent(); const fingerprint = userAgent.data; console.log(JSON.stringify(fingerprint, null, 2)); ``` -------------------------------- ### ESM Import Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Import the UserAgent class using ECMAScript Modules (ESM) syntax. This is standard for modern JavaScript environments. ```javascript import UserAgent from 'user-agents'; const ua = new UserAgent(); console.log(ua.toString()); ``` -------------------------------- ### Filter Type Example (Object) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Use an object as a filter to match a User-Agent based on specific properties. This allows for more complex filtering criteria. ```javascript const UserAgent = require('user-agents'); const ua = UserAgent.parse('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'); const filteredUa = ua.filter({ platform: 'win', browserName: 'chrome', deviceCategory: 'desktop' }); console.log(filteredUa.toString()); ``` -------------------------------- ### Example: Triggering No Matches Error Source: https://github.com/intoli/user-agents/blob/main/_autodocs/errors.md Illustrates how to intentionally trigger the 'No user agents matched your filters.' error using an invalid device category in the UserAgent constructor and how to catch it. ```javascript import UserAgent from 'user-agents'; // This throws because no user agent matches this device category try { const userAgent = new UserAgent({ deviceCategory: 'impossible-device' }); } catch (error) { console.error(error.message); // 'No user agents matched your filters.' } ``` -------------------------------- ### Array Filter Example (AND Logic) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/OVERVIEW.md Combine multiple filters using an array to enforce AND logic, ensuring all specified conditions are met. ```javascript const userAgent = new UserAgent([/Chrome/, { deviceCategory: 'desktop' }]); ``` -------------------------------- ### Filter by Multiple Properties (AND Logic) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Ensures all specified filters match using logical AND. This example filters for tablet devices with no plugins and a specific vendor. ```javascript import UserAgent from 'user-agents'; const userAgent = new UserAgent({ deviceCategory: 'tablet', pluginsLength: 0, vendor: 'Apple Computer, Inc.' }); // Will only generate iPad/iOS user agents with no plugins console.log(userAgent().deviceCategory); // 'tablet' console.log(userAgent().pluginsLength); // 0 console.log(userAgent().vendor); // 'Apple Computer, Inc.' ``` -------------------------------- ### Get Operating System and CPU Info Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Retrieves operating system and CPU information, primarily available on Windows. Corresponds to navigator.oscpu and may be null or undefined on other platforms. ```typescript oscpu?: string | null ``` -------------------------------- ### CJS Import Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Import the UserAgent class using CommonJS (CJS) syntax. This is common in older Node.js projects or specific build configurations. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent(); console.log(ua.toString()); ``` -------------------------------- ### Complex Filtering Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Generate a User-Agent string matching multiple criteria, such as a specific browser, OS, and device category. Demonstrates advanced filtering capabilities. ```javascript const UserAgent = require('user-agents'); const ua = new UserAgent({ platform: 'win', browserName: 'chrome', deviceCategory: 'desktop', }); console.log(ua.toString()); ``` -------------------------------- ### Validating Filters Before Instantiation Source: https://github.com/intoli/user-agents/blob/main/_autodocs/errors.md Provides an example of validating filters by checking available user agents or specific categories before attempting to create a UserAgent instance, thus preventing the 'No Matches Error'. ```javascript import UserAgent from 'user-agents'; // Check what device categories are available const allDevices = new UserAgent(); // Create with no filters console.log(allDevices.cumulativeWeightIndexPairs.length); // Total available // Check mobile availability const mobile = UserAgent.random({ deviceCategory: 'mobile' }); if (mobile) { console.log('Mobile user agents available'); } else { console.log('No mobile user agents in dataset'); } ``` -------------------------------- ### Build Library Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Builds the library for distribution. ```bash # Build the library npm run build ``` -------------------------------- ### Filter Type Example (Array of Strings) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Use an array of strings as a filter to match a User-Agent against multiple possible values for a single property. Useful for matching any of a set of browsers, for example. ```javascript const UserAgent = require('user-agents'); const ua = UserAgent.parse('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'); const filteredUa = ua.filter({ browserName: ['chrome', 'firefox', 'edge'] }); console.log(filteredUa.toString()); ``` -------------------------------- ### Filter Type Example (Array of Objects) Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Use an array of objects as a filter to match a User-Agent against multiple complex filter conditions. Each object in the array represents an alternative set of criteria. ```javascript const UserAgent = require('user-agents'); const ua = UserAgent.parse('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'); const filteredUa = ua.filter([ { platform: 'win', browserName: 'chrome' }, { platform: 'macos', browserName: 'safari' } ]); console.log(filteredUa.toString()); ``` -------------------------------- ### Get Top 5 Mobile User Agents Source: https://github.com/intoli/user-agents/blob/main/_autodocs/examples.md Fetches and displays the top 5 most common mobile user agents. The output includes the percentage weight for each user agent. ```javascript import UserAgent from 'user-agents'; const mobile = new UserAgent({ deviceCategory: 'mobile' }); const topMobile = mobile.top(5); console.log('Top 5 mobile user agents:'); topMobile.forEach(ua => { console.log(`${(ua.weight * 100).toFixed(3)}% - ${ua.userAgent}`); }); ``` -------------------------------- ### Filter by Vendor Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Matches a single property with an exact value. This example filters for 'Google Inc.' as the vendor. ```javascript // Filter by vendor const google = new UserAgent({ vendor: 'Google Inc.' }); ``` -------------------------------- ### Fast UserAgent Filtering with Simple Properties Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Illustrates creating a UserAgent instance with a simple filter based on a device property, which is processed quickly. ```javascript import UserAgent from 'user-agents'; // Fast: Simple property match const fast = new UserAgent({ deviceCategory: 'desktop' }); ``` -------------------------------- ### Generate Tablet User Agents Source: https://github.com/intoli/user-agents/blob/main/_autodocs/examples.md Demonstrates generating user agents for tablet devices. Shows how to access platform, screen width, and confirm the device category is 'tablet'. ```javascript import UserAgent from 'user-agents'; const tablet = new UserAgent({ deviceCategory: 'tablet' }); console.log(tablet.data.platform); // iPhone or iPad console.log(tablet.data.screenWidth); // Typical tablet size console.log(tablet.data.deviceCategory); // 'tablet' ``` -------------------------------- ### Import UserAgent Class Source: https://github.com/intoli/user-agents/blob/main/_autodocs/OVERVIEW.md Demonstrates how to import the UserAgent class from the 'user-agents' package. ```javascript import UserAgent from 'user-agents'; // or import { UserAgent } from 'user-agents'; ``` -------------------------------- ### Filter by Device Category Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Matches a single property with an exact value. This example filters for 'mobile' device categories. ```javascript import UserAgent from 'user-agents'; // Filter by device category const mobile = new UserAgent({ deviceCategory: 'mobile' }); console.log(mobile().deviceCategory); // Always 'mobile' ``` -------------------------------- ### Run Tests Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Executes the project's test suite. ```bash # Run tests npm test ``` -------------------------------- ### Combine RegExp and Function Filters Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Combine RegExp and function filters for AND logic. This example targets Chrome versions 90 and above. ```javascript import UserAgent from 'user-agents'; // RegExp AND function filter const modernChrome = new UserAgent([ /Chrome/, (data) => { const match = data.userAgent.match(/Chrome\/(\d+)/); const version = match ? parseInt(match[1], 10) : 0; return version >= 90; } ]); ``` -------------------------------- ### Object Filter Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/OVERVIEW.md Use object filters to match specific properties of the user agent data, such as the device category. ```javascript const userAgent = new UserAgent({ deviceCategory: 'mobile' }); ``` -------------------------------- ### Generating and Using UserAgentData Source: https://github.com/intoli/user-agents/blob/main/_autodocs/types.md Demonstrates how to create a UserAgent instance, access its data, and use it to create custom filters based on specific criteria. Requires the 'user-agents' package. ```javascript import UserAgent from 'user-agents'; const userAgent = new UserAgent({ deviceCategory: 'mobile' }); const data = userAgent.data; console.log(data.userAgent); console.log(data.platform); console.log(data.connection.effectiveType); console.log(data.screenWidth); console.log(data.weight); // Use in custom filter const customFilter = new UserAgent((data) => { return data.screenWidth >= 768 && data.connection.effectiveType === '4g'; }); ``` -------------------------------- ### Get Browser App Name Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Retrieves the browser application name. This property always returns 'Netscape' and corresponds to navigator.appName. ```typescript appName: 'Netscape' ``` -------------------------------- ### Instance Methods: random(), top(), randomize() Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt These instance methods allow for generating random user agents, retrieving top user agents, and randomizing existing instances. ```APIDOC ## Instance Methods ### random() #### Description Generates and returns a random UserAgent instance. #### Method Instance Method #### Endpoint N/A (Method call) ### top() #### Description Retrieves a list of the top (most common) UserAgent instances. #### Method Instance Method #### Endpoint N/A (Method call) ### randomize() #### Description Randomizes the properties of the current UserAgent instance. #### Method Instance Method #### Endpoint N/A (Method call) ### Request Example ```javascript const ua = new UserAgent(); const randomUa = ua.random(); const topUas = ua.top(); ua.randomize(); ``` ### Response #### Success Response - **random()**: Returns a UserAgent instance. - **top()**: Returns an array of UserAgent instances. - **randomize()**: Modifies the current UserAgent instance in place. ``` -------------------------------- ### NestedValueOf Helper Type Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/GENERATED.txt Illustrates the NestedValueOf helper type, which is used for accessing nested properties within the UserAgentData structure. ```typescript type NestedValueOf = P extends `${infer K}.${infer Rest}` ? K extends keyof T ? NestedValueOf : never : P extends keyof T ? T[P] : never; // Example Usage: // type ConnectionType = NestedValueOf; // type ScreenWidth = NestedValueOf; ``` -------------------------------- ### UserAgent Class Source: https://github.com/intoli/user-agents/blob/main/_autodocs/README.md Documentation for the main UserAgent class, including its constructor, instance methods, and static methods. ```APIDOC ## Class: UserAgent ### Description Provides functionality for generating and manipulating user agent strings. ### Constructor - **new UserAgent(options?: ConstructorOptions)**: Initializes a new UserAgent instance. ### Instance Methods - **random(options?: RandomOptions): UserAgent**: Returns a random UserAgent instance. - **top(options?: TopOptions): UserAgent**: Returns the top UserAgent instance. - **randomize(): UserAgent**: Returns a randomized UserAgent instance. - **toString(): string**: Returns the string representation of the UserAgent. ### Static Methods - **random(options?: RandomOptions): UserAgent**: Returns a random UserAgent instance. - **top(options?: TopOptions): UserAgent**: Returns the top UserAgent instance. ### Properties - **data**: UserAgentData - The data associated with the UserAgent. - **cumulativeWeightIndexPairs**: CumulativeWeightIndexPair[] - Pairs of cumulative weight and index. ### Type Casting and Coercion Supports type casting and coercion for UserAgentData. ### Callable Instance Behavior Instances can be called like functions. ### instanceof Support Supports `instanceof` checks. ### Error Handling Includes error handling mechanisms. ``` -------------------------------- ### Constructor Source: https://github.com/intoli/user-agents/blob/main/_autodocs/INDEX.md Initializes a new UserAgent instance. Optionally accepts a Filter object to pre-configure the user agent. ```APIDOC ## new UserAgent(filters?: Filter): UserAgent ### Description Initializes a new UserAgent instance. Optionally accepts a Filter object to pre-configure the user agent. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **filters** (Filter) - Optional - An object used to filter and configure the user agent. ### Response #### Success Response (200) * **UserAgent** - A new instance of the UserAgent class. ``` -------------------------------- ### Find Most Common User Agents for a Platform Source: https://github.com/intoli/user-agents/blob/main/_autodocs/OVERVIEW.md Use the `top()` method to retrieve an array of the most common user agents for a specified platform. This is helpful for simulating realistic traffic from a particular operating system. ```javascript const userAgent = new UserAgent({ platform: 'MacIntel' }); const topMac = userAgent.top(10); // Array of the 10 most common Mac user agents ``` -------------------------------- ### Combine Multiple RegExp Filters Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Combine multiple RegExp filters using an array for AND logic. This example targets Safari on Macintosh systems. ```javascript import UserAgent from 'user-agents'; // Multiple RegExp filters const safariMac = new UserAgent([ /Safari/, /Macintosh/ ]); ``` -------------------------------- ### Combine RegExp and Object Filters Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Use an array to combine RegExp and object filters for AND logic. This example targets Chrome on desktop devices. ```javascript import UserAgent from 'user-agents'; // RegExp AND object filters const chromeDesktop = new UserAgent([ /Chrome/, { deviceCategory: 'desktop' } ]); ``` -------------------------------- ### Get Browser Language Preference Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Retrieves the user's language preference or locale. This property may be null or undefined and corresponds to navigator.language. ```typescript language?: string | null ``` -------------------------------- ### Generate a Random User Agent Source: https://github.com/intoli/user-agents/blob/main/_autodocs/examples.md Demonstrates the simplest way to generate a random user agent string. Repeat calls to generate different user agents. ```javascript import UserAgent from 'user-agents'; const userAgent = new UserAgent(); console.log(userAgent.toString()); // Output: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... // Repeat to get different user agents console.log(userAgent()); // Shorthand for userAgent.random() console.log(userAgent()); // Different user agent ``` -------------------------------- ### Access pluginsLength Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Access the count of installed browser plugins. Modern browsers typically have 0 plugins. Use this to filter for modern or older browsers. ```javascript const userAgent = new UserAgent(); console.log(userAgent.data.pluginsLength); // 0 ``` ```javascript // Filter for browsers with no plugins (modern) const noPlugins = new UserAgent({ pluginsLength: 0 }); ``` ```javascript // Filter for browsers with plugins const hasPlugins = new UserAgent((data) => data.pluginsLength > 0); ``` -------------------------------- ### Generate User Agents for Responsive Design Testing Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Create distinct user agents for desktop, tablet, and mobile devices. This allows for testing responsive design across different form factors. ```javascript import UserAgent from 'user-agents'; const desktopUA = new UserAgent({ deviceCategory: 'desktop' }); const tabletUA = new UserAgent({ deviceCategory: 'tablet' }); const mobileUA = new UserAgent({ deviceCategory: 'mobile' }); // Generate test user agents const testSuite = [ desktopUA(), tabletUA(), mobileUA() ]; ``` -------------------------------- ### Rotating User Agents for Sequential Requests Source: https://github.com/intoli/user-agents/blob/main/_autodocs/examples.md Demonstrates rotating through different device categories (desktop, mobile, tablet) for sequential requests. A counter ensures each request uses the next user agent in the predefined list. ```javascript import UserAgent from 'user-agents'; const users = [ new UserAgent({ deviceCategory: 'desktop' }), new UserAgent({ deviceCategory: 'mobile' }), new UserAgent({ deviceCategory: 'tablet' }) ]; let requestCount = 0; function getNextUserAgent() { const ua = users[requestCount % users.length]; requestCount++; return ua().toString(); } // Each request gets a different device category for (let i = 0; i < 9; i++) { console.log(getNextUserAgent()); } ``` -------------------------------- ### Package.json Entry Points Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Defines the main and module entry points for the user-agents library in package.json. It specifies both CommonJS (CJS) and ECMAScript Module (ESM) formats for compatibility. ```json { "main": "./dist/index.cjs", "module": "./dist/index.js", "exports": { "import": "./dist/index.js", "require": "./dist/index.cjs" } } ``` -------------------------------- ### Implement OR Logic with Custom Function Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Use a custom filter function to implement OR logic for device categories. This example targets mobile or tablet devices. ```javascript import UserAgent from 'user-agents'; // Note: This example shows common intent but requires // a custom filter function to implement true OR logic const mobileOrTablet = new UserAgent((data) => { return data.deviceCategory === 'mobile' || data.deviceCategory === 'tablet'; }); ``` -------------------------------- ### Generate Linux User Agents Source: https://github.com/intoli/user-agents/blob/main/_autodocs/examples.md Create Linux user agents using a regular expression for any Linux platform or a specific string for a particular architecture like 'Linux x86_64' or 'Linux aarch64'. ```javascript import UserAgent from 'user-agents'; // Any Linux platform const linux = new UserAgent({ platform: /Linux/ }); // Specific architecture const linuxX64 = new UserAgent({ platform: 'Linux x86_64' }); const linuxARM = new UserAgent({ platform: 'Linux aarch64' }); ``` -------------------------------- ### Function Filter Example Source: https://github.com/intoli/user-agents/blob/main/_autodocs/OVERVIEW.md Implement custom logic for filtering using function filters, allowing complex conditions based on the user agent data. ```javascript const userAgent = new UserAgent((data) => data.screenWidth >= 1920); ``` -------------------------------- ### Instantiate UserAgent with Filters Source: https://github.com/intoli/user-agents/blob/main/_autodocs/README.md Create an instance of the UserAgent class to generate random user agents. Filters can be applied to restrict the generated agents, such as specifying the device category. ```javascript import UserAgent from 'user-agents'; const ua = new UserAgent({ deviceCategory: 'mobile' }); console.log(ua()); // Random mobile user agent ``` -------------------------------- ### Instance Methods Source: https://github.com/intoli/user-agents/blob/main/_autodocs/INDEX.md Methods available on a UserAgent instance to interact with and retrieve information. ```APIDOC ## Instance Methods ### `random()` #### Description Returns a new UserAgent instance with randomly selected properties. #### Method Instance Method #### Endpoint N/A (Instance Method) ### `top(count?: number): UserAgentData[]` #### Description Returns an array of the top `count` most common UserAgentData objects, optionally filtered. #### Parameters * **count** (number) - Optional - The number of top user agents to retrieve. #### Response * **UserAgentData[]** - An array of UserAgentData objects. ### `randomize()` #### Description Randomizes the properties of the current UserAgent instance in place. #### Method Instance Method #### Endpoint N/A (Instance Method) ### `toString(): string` #### Description Returns the string representation of the UserAgent instance. #### Method Instance Method #### Endpoint N/A (Instance Method) ### `userAgent(): UserAgent` #### Description Allows the UserAgent instance to be called directly as a function, returning itself. #### Method Instance Method #### Endpoint N/A (Instance Method) ``` -------------------------------- ### Call UserAgent Instance as Function Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgent.md Call a UserAgent instance directly as a function to get a random user agent string. This is a shorthand for the .random() method. ```javascript const userAgent = new UserAgent({ platform: 'MacIntel' }); const newUA = userAgent(); // Equivalent to userAgent.random() ``` -------------------------------- ### pluginsLength Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgentData-Properties.md Represents the count of installed browser plugins, corresponding to `navigator.plugins.length`. Modern browsers typically report 0 plugins as Flash and similar plugins are deprecated. ```APIDOC ## pluginsLength ### Description Number of installed browser plugins. Corresponds to `navigator.plugins.length`. ### Type `number` ### Example Values `0`, `1`, `3`, `5` ### Note Modern browsers typically have `0` plugins (Flash and similar plugins are deprecated). ### Example Usage ```javascript const userAgent = new UserAgent(); console.log(userAgent.data.pluginsLength); // 0 // Filter for browsers with no plugins (modern) const noPlugins = new UserAgent({ pluginsLength: 0 }); // Filter for browsers with plugins const hasPlugins = new UserAgent((data) => data.pluginsLength > 0); ``` ``` -------------------------------- ### Generate Multiple User Agents Source: https://github.com/intoli/user-agents/blob/main/README.md Demonstrates using a UserAgent instance as a generator to create an array of user agents. This leverages the instance's pre-configured filters. ```javascript const generateUserAgent = new UserAgent(filters); const userAgents = Array(100).fill().map(() => generateUserAgent()); ``` -------------------------------- ### Get Top User Agents Source: https://github.com/intoli/user-agents/blob/main/README.md Retrieves the most common user agents from the filtered dataset, ordered by descending frequency. This method is available both as an instance and static method. ```javascript // Use the instance method with pre-configured filters. const mobileAgents = new UserAgent({ deviceCategory: 'mobile' }); const topMobile = mobileAgents.top(5); // Or use the static method directly. const topDesktop = UserAgent.top(5, { deviceCategory: 'desktop' }); ``` -------------------------------- ### Efficient vs. Inefficient Batch Generation Source: https://github.com/intoli/user-agents/blob/main/_autodocs/examples.md Compares the performance of creating a single UserAgent instance and reusing it for batch generation versus creating a new instance for each item. Reuse is significantly faster for large batches. ```javascript import UserAgent from 'user-agents'; // EFFICIENT: Create instance once, reuse const start1 = Date.now(); const generator = new UserAgent({ deviceCategory: 'mobile' }); const batch1 = Array(10000).fill().map(() => generator().toString()); const time1 = Date.now() - start1; // INEFFICIENT: Create new instance each time const start2 = Date.now(); const batch2 = Array(10000).fill() .map(() => new UserAgent({ deviceCategory: 'mobile' }).toString()); const time2 = Date.now() - start2; console.log(`Efficient: ${time1}ms for 10,000`); console.log(`Inefficient: ${time2}ms for 10,000`); console.log(`Speedup: ${(time2 / time1).toFixed(1)}x`); ``` -------------------------------- ### Generate Random User Agent Source: https://github.com/intoli/user-agents/blob/main/README.md Instantiate UserAgent to get a random user agent and browser fingerprint. Log the stringified user agent and its data object. ```javascript import UserAgent from 'user-agents'; const userAgent = new UserAgent(); console.log(userAgent.toString()); console.log(JSON.stringify(userAgent.data, null, 2)); ``` ```literal Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36 ``` ```json { "appName": "Netscape", "connection": { "downlink": 10, "effectiveType": "4g", "rtt": 0 }, "platform": "Win32", "pluginsLength": 3, "vendor": "Google Inc.", "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36", "viewportHeight": 660, "viewportWidth": 1260, "deviceCategory": "desktop", "screenHeight": 800, "screenWidth": 1280 } ``` -------------------------------- ### Avoid Creating New UserAgent Instances Repeatedly Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md Demonstrates the inefficient approach of creating a new UserAgent instance within a loop, which incurs significant construction overhead on each iteration. ```javascript import UserAgent from 'user-agents'; // Avoid: Creating new instance each time const userAgents = []; for (let i = 0; i < 10000; i++) { // Construction overhead on each iteration userAgents.push(new UserAgent({ deviceCategory: 'mobile' }).toString()); } ``` -------------------------------- ### Filter by Nested Connection Effective Type Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/Filter-Usage-Guide.md Accesses nested properties using object notation. This example filters by the '4g' effective type within the connection object. ```javascript import UserAgent from 'user-agents'; // Filter by connection effective type const fourG = new UserAgent({ connection: { effectiveType: '4g' } }); ``` -------------------------------- ### Reuse UserAgent Instance for Performance Source: https://github.com/intoli/user-agents/blob/main/_autodocs/configuration.md For optimal performance, create a single UserAgent instance and reuse it for generating multiple user agents. This is significantly faster than creating new instances repeatedly. ```javascript import UserAgent from 'user-agents'; // Good: Create once const generator = new UserAgent({ deviceCategory: 'mobile' }); // Reuse many times (100x+ faster than creating new instances) const userAgents = []; for (let i = 0; i < 10000; i++) { userAgents.push(generator().toString()); } ``` -------------------------------- ### Generate Random User Agent Source: https://github.com/intoli/user-agents/blob/main/_autodocs/api-reference/UserAgent.md Use `UserAgent.random` to get a random user agent matching specific filters. It returns null if no matches are found, unlike the constructor. ```typescript static random(filters: Filter): UserAgent | null ``` ```javascript const userAgent = UserAgent.random({ userAgent: /Safari/ }); if (userAgent) { console.log(userAgent.toString()); } else { console.log('No matching user agents'); } ``` -------------------------------- ### Handle Constructor Errors with No Matches Source: https://github.com/intoli/user-agents/blob/main/_autodocs/OVERVIEW.md Demonstrates how the UserAgent constructor throws an error when no user agents match the provided filters. Use a try-catch block to gracefully handle these exceptions. ```javascript try { new UserAgent({ deviceCategory: 'impossible' }); } catch (error) { console.error(error.message); // 'No user agents matched your filters.' } ```