### Install compare-versions with npm
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Install the compare-versions package using npm.
```bash
npm install compare-versions
```
--------------------------------
### Install compare-versions using npm
Source: https://github.com/omichelsen/compare-versions/blob/main/README.md
Install the compare-versions package using npm. Note that starting from v5, the main export is named.
```bash
$ npm install compare-versions
```
--------------------------------
### Pre-release Comparison Examples
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/specification.md
Illustrates the rules for comparing pre-release versions, showing that versions with pre-releases are considered less than the same version without, and how pre-release segments are compared.
```plaintext
1.0.0-alpha < 1.0.0
1.0.0-alpha < 1.0.0-beta
1.0.0-1 < 1.0.0-alpha
1.0.0-rc.1 < 1.0.0-rc.2
```
--------------------------------
### Browser Module Import
Source: https://github.com/omichelsen/compare-versions/blob/main/README.md
In modern browsers, functions can be imported directly as ES modules. This example shows how to import and use several functions.
```html
```
--------------------------------
### Wildcard Matching Examples
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/specification.md
Demonstrates how the compareVersions function handles wildcard characters ('x' or '*') in version strings. When wildcards are present in either version being compared, the function returns 0, indicating equality.
```typescript
compareVersions('1.0.x', '1.0.5'); // 0 (wildcards match)
compareVersions('1.x', '1.5.0'); // 0 (wildcards match)
compareVersions('1.0.*', '1.0.999'); // 0 (wildcards match)
```
--------------------------------
### Check if Version is Supported within a Range
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/compare.md
This example demonstrates how to check if a current version falls within a supported range (minimum and maximum) using the `compare` function for both lower and upper bounds. It's useful for validating compatibility.
```typescript
import { compare } from 'compare-versions';
const currentVersion = '2.5.3';
const minRequired = '2.0.0';
const maxSupported = '3.0.0';
if (compare(currentVersion, minRequired, '>=') &&
compare(currentVersion, maxSupported, '<')) {
console.log('Version is supported');
}
```
--------------------------------
### Complex Range Examples with satisfies()
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/quick-reference.md
Demonstrates how to use the `satisfies()` function with various logical operators (AND, OR) and range formats like caret and hyphenated ranges. Use for checking if a version meets multiple criteria.
```typescript
satisfies('1.8.0', '>=1.5.0 <2.0.0') // true
```
```typescript
satisfies('1.2.7', '1.2.7 || >=1.2.9') // true
satisfies('1.2.8', '1.2.7 || >=1.2.9') // false
```
```typescript
satisfies('1.8.0', '1.5.0 - 2.3.0') // true
```
```typescript
satisfies('1.8.0', '^1.0.0 <2.0.0 || >=3.0.0') // true
```
--------------------------------
### Check Package Dependencies Against Requirements
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Utilize `satisfies` and `validate` to check installed package versions against specified ranges. Handles missing, invalid, and incompatible dependencies.
```typescript
import { satisfies, validate } from 'compare-versions';
function checkDependencies(installedVersions, requirements) {
const results = {};
for (const [pkg, range] of Object.entries(requirements)) {
const installed = installedVersions[pkg];
if (!installed) {
results[pkg] = { status: 'missing' };
} else if (!validate(installed)) {
results[pkg] = { status: 'invalid', version: installed };
} else if (!satisfies(installed, range)) {
results[pkg] = {
status: 'incompatible',
installed,
required: range
};
} else {
results[pkg] = { status: 'ok', version: installed };
}
}
return results;
}
const deps = {
'react': '18.2.0',
'typescript': '5.0.0',
'lodash': 'invalid'
};
const requirements = {
'react': '>=17.0.0',
'typescript': '~5.0.0',
'lodash': '^4.0.0'
};
const check = checkDependencies(deps, requirements);
// { react: { status: 'ok', ... }, typescript: { status: 'ok', ... }, ... }
```
--------------------------------
### Usage of CompareOperator with compare function
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/types.md
Demonstrates how to use the CompareOperator type with the compare function for type-safe version comparisons. Shows correct usage and a type error example.
```typescript
import { compare, type CompareOperator } from 'compare-versions';
const operator: CompareOperator = '>=';
const result = compare('1.2.3', '1.0.0', operator); // Returns: true
// Type error: operator type is wrong
// const badOp: CompareOperator = '=='; // Error!
```
--------------------------------
### Project File Structure
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-index.md
Illustrates the directory layout of the compare-versions project, showing the organization of source code, build artifacts, and package metadata.
```tree
compare-versions/
├── src/
│ ├── index.ts (public exports)
│ ├── compareVersions.ts (core comparison)
│ ├── compare.ts (operator-based comparison)
│ ├── satisfies.ts (range matching)
│ ├── validate.ts (validation functions)
│ └── utils.ts (shared utilities)
├── lib/
│ ├── esm/ (ES module build)
│ │ ├── index.js
│ │ ├── index.d.ts (TypeScript declarations)
│ │ └── ...
│ └── umd/ (Universal module build)
│ ├── index.js
│ ├── index.js.map
│ └── ...
└── package.json
```
--------------------------------
### Hyphenated Range Matching (Inclusive)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/satisfies.md
Illustrates checking if a version falls within a hyphenated range, which is inclusive of both the start and end versions. Import 'satisfies' from 'compare-versions'.
```typescript
import { satisfies } from 'compare-versions';
satisfies('1.5.1', '1.2.3 - 2.3.4'); // Returns: true
satisfies('2.3.5', '1.2.3 - 2.3.4'); // Returns: false
satisfies('1.2.3', '1.2.3 - 2.3.4'); // Returns: true (inclusive)
satisfies('2.3.4', '1.2.3 - 2.3.4'); // Returns: true (inclusive)
```
--------------------------------
### Import Core Functions (Browser UMD)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-index.md
Access all public APIs via the global `window.compareVersions` object when using the Browser UMD build.
```html
```
--------------------------------
### Basic Caret and Tilde Range Matching
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/satisfies.md
Demonstrates basic version matching using caret (^) and tilde (~) range specifiers. Ensure the 'compare-versions' library is imported.
```typescript
import { satisfies } from 'compare-versions';
satisfies('1.1.0', '^1.0.0'); // Returns: true
satisfies('2.0.0', '^1.0.0'); // Returns: false
satisfies('1.5.0', '~1.0.0'); // Returns: false
satisfies('1.0.5', '~1.0.0'); // Returns: true
```
--------------------------------
### Validate a non-numeric invalid version string
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/validate.md
Tests an invalid version string that does not start with a digit or 'v' and contains non-numeric characters. The function returns false.
```typescript
import { validate } from 'compare-versions';
validate('foo');
```
--------------------------------
### Browser Legacy (UMD) Import
Source: https://github.com/omichelsen/compare-versions/blob/main/README.md
For older browser environments, the UMD build makes functions available on the global `window.compareVersions` object.
```html
```
--------------------------------
### Pre-release Version Matching
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/satisfies.md
Illustrates checking compatibility with pre-release versions using caret ranges. Note that pre-release versions are only considered if the range explicitly includes them. Import 'satisfies' from 'compare-versions'.
```typescript
import { satisfies } from 'compare-versions';
satisfies('1.0.0-rc.1', '^1.0.0-rc.0'); // Returns: true
satisfies('1.0.0', '^1.0.0-rc.0'); // Returns: true
satisfies('1.0.0-alpha', '^1.0.0-rc.0'); // Returns: false
```
--------------------------------
### Version Comparison Pipeline
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/architecture.md
Details the step-by-step process for comparing two version strings, from validation and parsing to segment-by-segment comparison.
```mermaid
graph TD
A[Input (string, string)] --> B(validateAndParse() [utils]);
B --> C(Parse into regex groups [1-5]);
C --> D(Extract pre-release segment);
D --> E(compareSegments() [utils]);
E --> F(Compare main version parts);
F --> G(Compare pre-release parts (if both exist));
G --> H(Return: 1 | 0 | -1);
```
--------------------------------
### Validate an invalid semantic version string (missing patch)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/validate.md
This snippet shows an example of an invalid version string where a pre-release identifier is present but the patch version is missing. The function correctly returns false.
```typescript
import { validate } from 'compare-versions';
validate('1.0-rc.1');
```
--------------------------------
### AND Range Matching (Space-Separated)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/satisfies.md
Shows how to specify an AND range by separating conditions with spaces, effectively checking if a version meets all criteria. Requires 'satisfies' from 'compare-versions'.
```typescript
import { satisfies } from 'compare-versions';
satisfies('1.5.0', '>=1.2.0 <2.0.0'); // Returns: true
satisfies('2.0.0', '>=1.2.0 <2.0.0'); // Returns: false
satisfies('1.1.0', '>=1.2.0 <2.0.0'); // Returns: false
```
--------------------------------
### Compare Pre-release Versions
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/compare.md
Use this snippet to compare pre-release versions. It correctly handles pre-release identifiers like '-beta' and '-rc.1'.
```typescript
import { compare } from 'compare-versions';
compare('1.0.0', '1.0.0-beta', '>'); // Returns: true
compare('1.0.0-rc.1', '1.0.0-rc.2', '<'); // Returns: true
```
--------------------------------
### Version Matching with Comparison Operators
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/satisfies.md
Shows how to use comparison operators (>, =, <, <=, >=) with the satisfies() function for version checking. Requires importing 'satisfies' from 'compare-versions'.
```typescript
import { satisfies } from 'compare-versions';
satisfies('10.1.8', '>10.0.4'); // Returns: true
satisfies('10.0.1', '=10.0.1'); // Returns: true
satisfies('10.1.1', '<10.2.2'); // Returns: true
satisfies('10.1.1', '<=10.2.2'); // Returns: true
satisfies('10.1.1', '>=10.2.2'); // Returns: false
```
--------------------------------
### Checking App Version Against Supported Ranges
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/satisfies.md
Demonstrates a common use case: iterating through a list of supported version ranges to check if an application's version is compatible. Requires importing 'satisfies' from 'compare-versions'.
```typescript
import { satisfies } from 'compare-versions';
const appVersion = '2.5.3';
const supportedRanges = ['^2.0.0', '^1.5.0'];
const isSupported = supportedRanges.some(range =>
satisfies(appVersion, range)
);
// Result: true (matches ^2.0.0)
```
--------------------------------
### Include compareVersions (Browser Global)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/quick-reference.md
Include this script tag in your HTML to make the compareVersions function available globally in the browser.
```html
```
--------------------------------
### Import Core Functions (CommonJS)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-index.md
Import all public APIs from the main entry point when using CommonJS.
```javascript
const {
compareVersions,
compare,
satisfies,
validate,
validateStrict,
CompareOperator
} = window.compareVersions;
```
--------------------------------
### Package.json Exports Configuration
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/specification.md
This JSON configuration specifies the entry points for different module systems (main for CommonJS, module for ESM) and the location of type definitions. It also indicates that the module has no side effects.
```json
{
"main": "./lib/umd/index.js",
"module": "./lib/esm/index.js",
"types": "./lib/esm/index.d.ts",
"sideEffects": false
}
```
--------------------------------
### UMD Build Command with Rollup
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/architecture.md
Command to bundle the ESM output using Rollup into a UMD format, naming the global variable 'compareVersions'. Includes source map generation.
```bash
rollup lib/esm/index.js --format umd --name compareVersions
```
--------------------------------
### Version Utilities Testing
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Demonstrates testing various version utility functions including sorting, comparison, satisfaction checks, and validation using Jest.
```typescript
import { describe, it, expect } from '@jest/globals';
import { compareVersions, compare, satisfies, validate } from 'compare-versions';
describe('Version utilities', () => {
describe('compareVersions', () => {
it('should sort versions correctly', () => {
const versions = ['2.0.0', '1.0.0', '1.5.0'];
expect(versions.sort(compareVersions)).toEqual(['1.0.0', '1.5.0', '2.0.0']);
});
});
describe('compare', () => {
it('should support all operators', () => {
expect(compare('2.0.0', '1.0.0', '>')).toBe(true);
expect(compare('1.0.0', '1.0.0', '=')).toBe(true);
expect(compare('1.0.0', '2.0.0', '<')).toBe(true);
});
});
describe('satisfies', () => {
it('should support npm version ranges', () => {
expect(satisfies('1.2.3', '^1.0.0')).toBe(true);
expect(satisfies('1.2.3', '~1.2.0')).toBe(true);
expect(satisfies('1.2.3', '1.0.0 - 2.0.0')).toBe(true);
});
});
describe('validate', () => {
it('should validate version format', () => {
expect(validate('1.0.0')).toBe(true);
expect(validate('invalid')).toBe(false);
});
});
});
```
--------------------------------
### Range Matching Pipeline
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/architecture.md
Explains the logic for determining if a version string satisfies a given range, including handling various range types and operators.
```mermaid
graph TD
A[Input (version: string, range: string)] --> B(Preprocess range (trim, normalize));
B --> C(Detect range type (||, -, space, operator));
C --> D{Branch on type:};
D -- OR (||) --> E(Recursively check each);
D -- Hyphen (-) --> F(Convert to >= and <=);
D -- Space --> G(Split and check all);
D -- Single --> H(Extract operator);
H --> I{Branch on operator:};
I -- ^, ~ --> J(Complex range logic);
I -- >, >=, =, <=, < --> K(Use compare());
E --> L(Return: boolean);
F --> L;
G --> L;
J --> L;
K --> L;
```
--------------------------------
### compareVersions
Source: https://github.com/omichelsen/compare-versions/blob/main/README.md
Compares two version strings. Returns 1 if the first version is greater, 0 if they are equal, and -1 if the second version is greater.
```APIDOC
## compareVersions
### Description
Compares two version strings and returns a numerical value indicating their relationship.
### Function Signature
`compareVersions(version1: string, version2: string): number`
### Parameters
#### Path Parameters
- **version1** (string) - The first version string to compare.
- **version2** (string) - The second version string to compare.
### Return Value
- **number**: `1` if `version1` > `version2`, `0` if `version1` == `version2`, `-1` if `version1` < `version2`.
### Usage Example
```js
import { compareVersions } from 'compare-versions';
compareVersions('11.1.1', '10.0.0'); // returns 1
compareVersions('10.0.0', '10.0.0'); // returns 0
compareVersions('10.0.0', '11.1.1'); // returns -1
```
### Sorting Example
```js
const versions = ['1.5.19', '1.2.3', '1.5.5'];
const sorted = versions.sort(compareVersions);
// sorted will be ['1.2.3', '1.5.5', '1.5.19']
```
```
--------------------------------
### Import Core Functions (ES Modules)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-index.md
Import all public APIs from the main entry point when using ES Modules.
```typescript
import {
compareVersions,
compare,
satisfies,
validate,
validateStrict,
CompareOperator
} from 'compare-versions';
```
--------------------------------
### Import compare-versions functions (ES Modules)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Import necessary functions from the compare-versions library when using ES Modules.
```typescript
import {
compareVersions,
compare,
satisfies,
validate,
validateStrict
} from 'compare-versions';
```
--------------------------------
### Module Organization
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/architecture.md
Illustrates the directory structure and the primary role of each module within the library.
```tree
src/
├── index.ts # Public API exports
├── compareVersions.ts # Core numeric comparison function
├── compare.ts # Operator-based comparison wrapper
├── satisfies.ts # Range matching logic
├── validate.ts # Validation functions (2)
└── utils.ts # Shared utilities and types
```
--------------------------------
### Compare Versions with Pre-release Tags
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/compareVersions.md
Compares versions including pre-release tags. Release versions are considered greater than pre-release versions.
```typescript
import { compareVersions } from 'compare-versions';
compareVersions('1.0.0', '1.0.0-alpha'); // Returns: 1 (release > pre-release)
compareVersions('1.0.0-beta', '1.0.0-alpha'); // Returns: 1
compareVersions('1.0.0-rc.1', '1.0.0-rc.2'); // Returns: -1
```
--------------------------------
### Negotiate API Version with Client and Server
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Use `satisfies` to determine the compatible API endpoint based on the client's version. `compareVersions` can warn if the server is significantly newer.
```typescript
import { compareVersions, satisfies } from 'compare-versions';
class APIClient {
constructor(serverVersion, clientVersion) {
this.serverVersion = serverVersion;
this.clientVersion = clientVersion;
}
getCompatibleEndpoint() {
// Use latest compatible API version
if (satisfies(this.clientVersion, '>=2.0.0')) {
return '/api/v3';
}
if (satisfies(this.clientVersion, '>=1.5.0')) {
return '/api/v2';
}
return '/api/v1';
}
requiresUpdate() {
// Warn if server is much newer
return compareVersions(this.serverVersion, this.clientVersion) > 1;
}
}
const client = new APIClient('3.0.0', '2.5.0');
console.log(client.getCompatibleEndpoint()); // '/api/v3'
console.log(client.requiresUpdate()); // false
```
--------------------------------
### Package Contents Configuration
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/architecture.md
Defines the files included in the package, the main entry points for CommonJS and ES Modules, and TypeScript declaration files.
```json
{
"files": ["lib", "src"],
"main": "./lib/umd/index.js",
"module": "./lib/esm/index.js",
"types": "./lib/esm/index.d.ts"
}
```
--------------------------------
### OR Range Matching
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/satisfies.md
Demonstrates how to use the OR operator (||) to check if a version satisfies any of the specified ranges. Ensure 'satisfies' is imported from 'compare-versions'.
```typescript
import { satisfies } from 'compare-versions';
satisfies('1.4.6', '1.2.7 || >=1.2.9 <2.0.0'); // Returns: true
satisfies('1.2.8', '1.2.7 || >=1.2.9 <2.0.0'); // Returns: false
satisfies('1.2.7', '1.2.7 || >=1.2.9 <2.0.0'); // Returns: true
```
--------------------------------
### compare
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-index.md
Compares two version strings using human-readable operators (e.g., '>', '<', '='). Returns a boolean indicating if the comparison is true.
```APIDOC
## compare
### Description
Compares two version strings using human-readable operators (e.g., '>', '<', '='). Returns a boolean indicating if the comparison is true.
### Signature
`(v1: string, v2: string, operator: CompareOperator) => boolean`
```
--------------------------------
### Migration to v6.x: npm Comparator Sets
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Illustrates the change in behavior for the `satisfies` function from v5.x to v6.x, where spaces now denote AND conditions for comparator sets.
```typescript
// v5.x behavior (spaces were mostly ignored)
satisfies('1.5.1', '>=1.2.0 <2.0.0'); // Treated as '>=1.2.0<2.0.0'
// v6.x behavior (spaces denote AND conditions)
satisfies('1.5.1', '>=1.2.0 <2.0.0'); // Correctly parsed as two conditions
```
--------------------------------
### Import compareVersions (CommonJS)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/quick-reference.md
Use this require statement for Node.js environments or build tools that use the CommonJS module system.
```javascript
const { compareVersions } = require('compare-versions');
```
--------------------------------
### Migration to v5.x: Named Exports
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Shows the change in import syntax from v4.x (default export) to v5.x and later (named exports) for the compare-versions library.
```typescript
// v4.x
import compareVersions from 'compare-versions';
// v5.x and later
import { compareVersions } from 'compare-versions';
```
--------------------------------
### Compare Versions
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/compareVersions.md
Compares two version strings. Returns 1 if v1 > v2, 0 if equal, -1 if v1 < v2.
```typescript
import { compareVersions } from 'compare-versions';
compareVersions('11.1.1', '10.0.0'); // Returns: 1
compareVersions('10.0.0', '10.0.0'); // Returns: 0
compareVersions('10.0.0', '11.1.1'); // Returns: -1
```
--------------------------------
### Compare Versions with Wildcards
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/compareVersions.md
Compares versions using wildcard characters ('x' or '*') for minor or patch segments. Wildcards match any value.
```typescript
import { compareVersions } from 'compare-versions';
compareVersions('1.0.x', '1.0.5'); // Returns: 0 (wildcard matches)
compareVersions('1.0.*', '1.0.99'); // Returns: 0
```
--------------------------------
### Compare Two Versions
Source: https://github.com/omichelsen/compare-versions/blob/main/README.md
Use `compareVersions` to determine the relationship between two version strings. It returns 1 if the first is greater, 0 if equal, and -1 if the second is greater.
```javascript
import { compareVersions } from 'compare-versions';
compareVersions('11.1.1', '10.0.0'); // 1
compareVersions('10.0.0', '10.0.0'); // 0
compareVersions('10.0.0', '11.1.1'); // -1
```
--------------------------------
### compareVersions Function
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/compareVersions.md
Compares two semantic version strings and returns a numeric value compatible with Array.sort().
```APIDOC
## compareVersions(v1: string, v2: string): number
### Description
Compares two semantic version strings and returns a numeric value compatible with `Array.sort()`.
### Parameters
#### Path Parameters
- **v1** (string) - Required - The first version to compare.
- **v2** (string) - Required - The second version to compare.
### Returns
- **number** - Returns `1` if v1 is greater than v2, `0` if equal, `-1` if v2 is greater than v1. Compatible with [Array.sort(fn) interface](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Parameters).
### Throws
- **TypeError** - If v1 or v2 is not a string.
- **Error** - If v1 or v2 does not match a valid semver pattern.
### Usage Examples
#### Basic comparison
```typescript
import { compareVersions } from 'compare-versions';
compareVersions('11.1.1', '10.0.0'); // Returns: 1
compareVersions('10.0.0', '10.0.0'); // Returns: 0
compareVersions('10.0.0', '11.1.1'); // Returns: -1
```
#### Sorting versions
```typescript
import { compareVersions } from 'compare-versions';
const versions = [
'1.5.19',
'1.2.3',
'1.5.5'
];
const sorted = versions.sort(compareVersions);
// Result: ['1.2.3', '1.5.5', '1.5.19']
```
#### With pre-release versions
```typescript
import { compareVersions } from 'compare-versions';
compareVersions('1.0.0', '1.0.0-alpha'); // Returns: 1 (release > pre-release)
compareVersions('1.0.0-beta', '1.0.0-alpha'); // Returns: 1
compareVersions('1.0.0-rc.1', '1.0.0-rc.2'); // Returns: -1
```
#### With wildcards
```typescript
import { compareVersions } from 'compare-versions';
compareVersions('1.0.x', '1.0.5'); // Returns: 0 (wildcard matches)
compareVersions('1.0.*', '1.0.99'); // Returns: 0
```
```
--------------------------------
### Validate Version Formats
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/README.md
Use `validate` for lenient checks accepting partial versions and leading 'v'. Use `validateStrict` for strict semver.org compliance requiring exactly three parts.
```typescript
import { validate, validateStrict } from 'compare-versions';
validate('1.0'); // true (lenient)
validateStrict('1.0'); // false (strict requires 3 parts)
validate('1.0.0'); // true
validateStrict('1.0.0'); // true
```
--------------------------------
### compare(v1, v2, op)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/quick-reference.md
Performs a human-readable comparison between two version strings based on a specified operator.
```APIDOC
## compare(v1, v2, op)
### Description
Compares two version strings `v1` and `v2` using a specified comparison operator `op`. Returns `true` if the comparison matches the operator, `false` otherwise.
### Purpose
To allow for flexible, human-readable version comparisons beyond simple equality or ordering.
### Input
- `v1` (string): The first version string.
- `v2` (string): The second version string.
- `op` (CompareOperator | string): The comparison operator. Supported operators include '>', '<', '>=', '<=', '=', '==', '!='.
### Output
- `true`: if the comparison between `v1` and `v2` matches the operator `op`.
- `false`: otherwise.
### Example Usage
```typescript
import { compare } from 'compare-versions';
console.log(compare('1.10.0', '1.2.0', '>')); // Output: true
console.log(compare('1.2.0', '1.10.0', '<=')); // Output: true
console.log(compare('1.2.0', '1.2.0', '==')); // Output: true
console.log(compare('1.2.0', '1.3.0', '!=')); // Output: true
```
```
--------------------------------
### Side Effects Configuration
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/architecture.md
Specifies that the library has no side effects, which is crucial for tree-shaking optimization in module bundlers.
```json
{
"sideEffects": false
}
```
--------------------------------
### validate
Source: https://github.com/omichelsen/compare-versions/blob/main/README.md
Validates a version string against common versioning rules. Returns a boolean.
```APIDOC
## validate
### Description
Validates a version string using general version comparison rules.
### Function Signature
`validate(version: string): boolean`
### Parameters
#### Path Parameters
- **version** (string) - The version string to validate.
### Return Value
- **boolean**: `true` if the version string is considered valid, `false` otherwise.
### Usage Example
```js
import { validate } from 'compare-versions';
validate('1.0.0-rc.1'); // returns true
validate('1.0-rc.1'); // returns false
validate('foo'); // returns false
```
```
--------------------------------
### Function Signatures for Version Comparison
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/architecture.md
Lists the explicit type signatures for key functions involved in version comparison, validation, and satisfaction checks.
```typescript
// compareVersions.ts
function compareVersions(v1: string, v2: string): number
```
```typescript
// compare.ts
function compare(v1: string, v2: string, operator: CompareOperator): boolean
```
```typescript
// satisfies.ts
function satisfies(version: string, range: string): boolean
```
```typescript
// validate.ts
function validate(version: string): boolean
function validateStrict(version: string): boolean
```
```typescript
// utils.ts
function validateAndParse(version: string): RegExpMatchArray
function compareSegments(
a: string | string[] | RegExpMatchArray,
b: string | string[] | RegExpMatchArray
): number
```
--------------------------------
### Import compareVersions (ESM)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/quick-reference.md
Use this import statement for modern JavaScript environments that support ES Modules.
```typescript
import { compareVersions } from 'compare-versions';
```
--------------------------------
### Compare Version Strings
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/README.md
Use `compareVersions` for direct comparison returning -1, 0, or 1. Use `compare` with an operator for boolean results.
```typescript
import { compareVersions, compare } from 'compare-versions';
compareVersions('2.0.0', '1.0.0'); // 1 (greater)
compare('2.0.0', '1.0.0', '>'); // true
```
--------------------------------
### Check version compatibility with tilde ranges
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Use the `satisfies` function with tilde ranges (`~`) to check if a version is compatible, allowing only patch-level changes.
```typescript
import { satisfies } from 'compare-versions';
const appVersion = '2.1.0';
// Tilde: patch-level changes allowed
if (satisfies(appVersion, '~2.1.0')) {
console.log('Version is compatible with ~2.1.0');
// Matches: 2.1.0 through 2.1.999, not 2.2.0
}
```
--------------------------------
### Compare Versions with Operators
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/compare.md
Use this snippet to compare two version strings using various operators like '>', '=', '<', '<=', '>=', and '!='. Ensure you import the `compare` function from 'compare-versions'.
```typescript
import { compare } from 'compare-versions';
compare('10.1.8', '10.0.4', '>'); // Returns: true
compare('10.0.1', '10.0.1', '='); // Returns: true
compare('10.1.1', '10.2.2', '<'); // Returns: true
compare('10.1.1', '10.2.2', '<='); // Returns: true
compare('10.1.1', '10.2.2', '>='); // Returns: false
compare('1.0.0', '1.0.0', '!='); // Returns: false
```
--------------------------------
### Compare versions for conditional logic
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Use the `compare` function for human-readable version comparisons in conditional statements. It accepts the current version, the version to compare against, and an operator.
```typescript
import { compare } from 'compare-versions';
const currentVersion = '1.5.2';
if (compare(currentVersion, '1.0.0', '>')) {
console.log('Current version is newer than 1.0.0');
}
if (compare(currentVersion, '2.0.0', '<')) {
console.log('Current version is older than 2.0.0');
}
```
--------------------------------
### Find the Newest Compatible Version from Available Versions
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Filter available versions using `satisfies` and then sort them with `compareVersions` to find the newest compatible version. Returns null if no versions satisfy the requirements.
```typescript
import { satisfies, compareVersions } from 'compare-versions';
function findBestVersion(availableVersions, requirements) {
// Filter versions that satisfy requirements
const compatible = availableVersions.filter(v =>
satisfies(v, requirements)
);
if (compatible.length === 0) {
return null;
}
// Return newest compatible version
return compatible.sort(compareVersions).pop();
}
const available = ['1.0.0', '1.5.0', '2.0.0', '2.5.0', '3.0.0'];
findBestVersion(available, '^2.0.0'); // '2.5.0'
findBestVersion(available, '~1.5.0'); // '1.5.0'
findBestVersion(available, '>2.0.0'); // '3.0.0'
findBestVersion(available, '1.0.0'); // '1.0.0'
findBestVersion(available, '^5.0.0'); // null
```
--------------------------------
### Validate a pre-release semantic version string
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/validate.md
Checks if a version string with pre-release identifiers (e.g., -alpha, -rc.1) is valid. This is useful for testing release candidates.
```typescript
import { validate } from 'compare-versions';
validate('1.0.0-rc.1');
```
--------------------------------
### Find Newest Compatible Version
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/README.md
Filters a list of versions to find the newest one that satisfies a specific range, then sorts them and retrieves the latest using `filter`, `sort`, and `pop`. Requires `satisfies` and `compareVersions`.
```typescript
const compatible = versions
.filter(v => satisfies(v, '^2.0.0'))
.sort(compareVersions)
.pop();
```
--------------------------------
### Check Version Satisfaction with Ranges
Source: https://github.com/omichelsen/compare-versions/blob/main/README.md
The `satisfies` function checks if a given version string falls within a specified range, supporting npm-style versioning syntax.
```javascript
import { satisfies } from 'compare-versions';
satisfies('10.0.1', '~10.0.0'); // true
satisfies('10.1.0', '~10.0.0'); // false
satisfies('10.1.2', '^10.0.0'); // true
satisfies('11.0.0', '^10.0.0'); // false
satisfies('10.1.8', '>10.0.4'); // true
satisfies('10.0.1', '=10.0.1'); // true
satisfies('10.1.1', '<10.2.2'); // true
satisfies('10.1.1', '<=10.2.2'); // true
satisfies('10.1.1', '>=10.2.2'); // false
satisfies('1.4.6', '1.2.7 || >=1.2.9 <2.0.0'); // true
satisfies('1.2.8', '1.2.7 || >=1.2.9 <2.0.0'); // false
satisfies('1.5.1', '1.2.3 - 2.3.4'); // true
satisfies('2.3.5', '1.2.3 - 2.3.4'); // false
```
--------------------------------
### Cache Version Comparison Results
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Implements a cache to store and retrieve version comparison results, improving performance for repeated comparisons of the same version pairs. Uses a Map for caching.
```typescript
import { compareVersions } from 'compare-versions';
class VersionCache {
constructor() {
this.cache = new Map();
}
compare(v1, v2) {
const key = `${v1}:${v2}`;
if (this.cache.has(key)) {
return this.cache.get(key);
}
const result = compareVersions(v1, v2);
this.cache.set(key, result);
return result;
}
}
const cache = new VersionCache();
cache.compare('1.0.0', '2.0.0'); // Computed
cache.compare('1.0.0', '2.0.0'); // Cached
```
--------------------------------
### Wildcard Matching in Ranges
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/specification.md
Wildcards (x, X, *) in version ranges match any segment. Use this for flexible version constraints.
```javascript
satisfies('1.5.3', '1.x'); // true (wildcard matches)
```
```javascript
satisfies('1.5.3', '1.0.x'); // true (wildcard matches)
```
```javascript
satisfies('1.5.3', '1.5.*'); // true (wildcard matches)
```
--------------------------------
### satisfies(v, range)
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/quick-reference.md
Checks if a given version string satisfies a specified version range.
```APIDOC
## satisfies(v, range)
### Description
Determines if a given version string `v` falls within the specified version `range`. Supports various range formats including caret (`^`), hyphen (`-`), and comparative operators (`>=`, `<`).
### Purpose
To check if a version is compatible with a given set of version constraints.
### Input
- `v` (string): The version string to check.
- `range` (string): The version range string.
### Output
- `true`: if the version `v` is within the specified `range`.
- `false`: otherwise.
### Example Usage
```typescript
import { satisfies } from 'compare-versions';
console.log(satisfies('1.5.0', '^1.0.0')); // Output: true (satisfies >=1.0.0 <2.0.0)
console.log(satisfies('1.5.0', '1.0.0 - 2.0.0')); // Output: true
console.log(satisfies('1.5.0', '>=1.0.0 <2.0.0')); // Output: true
console.log(satisfies('2.1.0', '^1.0.0')); // Output: false
```
```
--------------------------------
### Check Feature Compatibility with App Version
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/usage-guide.md
Use `satisfies` to determine if an application version meets the requirements for a specific feature. Ensure the feature has defined requirements.
```typescript
import { satisfies } from 'compare-versions';
class FeatureManager {
static isSupported(feature, appVersion) {
const requirements = {
'dark-mode': '>=1.5.0',
'multi-account': '>=2.0.0',
'api-v2': '>=1.8.0 <2.0.0 || >=2.5.0'
};
if (!requirements[feature]) {
return false;
}
return satisfies(appVersion, requirements[feature]);
}
}
FeatureManager.isSupported('dark-mode', '1.6.0'); // true
FeatureManager.isSupported('multi-account', '1.9.0'); // false
FeatureManager.isSupported('api-v2', '1.9.0'); // true
```
--------------------------------
### Version String Parsing Regex
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/specification.md
This comprehensive regex pattern is used to parse version strings, extracting major, minor, patch, fourth, and pre-release segments.
```regex
/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i
```
--------------------------------
### Validate a version string with a leading 'v'
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/validate.md
Tests version strings that begin with the character 'v', which is accepted by the validator. This is common in some versioning schemes.
```typescript
import { validate } from 'compare-versions';
validate('v1.0.0');
```
--------------------------------
### Import CommonJS Modules
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/README.md
Import the library's functions using CommonJS syntax, suitable for Node.js environments that do not support ES Modules directly.
```javascript
const {
compareVersions,
compare,
satisfies,
validate,
validateStrict
} = require('compare-versions');
```
--------------------------------
### compare Function
Source: https://github.com/omichelsen/compare-versions/blob/main/_autodocs/api-reference/compare.md
Compares two semantic version strings using a specified human-readable operator. It returns true if the comparison satisfies the operator, and false otherwise.
```APIDOC
## compare(v1: string, v2: string, operator: CompareOperator): boolean
### Description
Compares two semantic version strings using a human-readable operator. Returns `true` if the comparison between v1 and v2 satisfies the operator, `false` otherwise.
### Parameters
#### Path Parameters
- **v1** (string) - Required - The first version string to compare.
- **v2** (string) - Required - The second version string to compare.
- **operator** (CompareOperator) - Required - The operator to use for comparison. Allowed values are: `>`, `>=`, `=`, `<=`, `<`, `!=`.
### Returns
- **boolean** - `true` if the comparison satisfies the operator, `false` otherwise.
### Throws
- **TypeError** - If v1 or v2 is not a string, or if operator is not a string.
- **Error** - If v1 or v2 does not match a valid semver pattern.
- **Error** - If the operator is not one of the allowed values.
### Usage Examples
#### Comparison operators
```typescript
import { compare } from 'compare-versions';
compare('10.1.8', '10.0.4', '>'); // Returns: true
compare('10.0.1', '10.0.1', '='); // Returns: true
compare('10.1.1', '10.2.2', '<'); // Returns: true
compare('10.1.1', '10.2.2', '<='); // Returns: true
compare('10.1.1', '10.2.2', '>='); // Returns: false
compare('1.0.0', '1.0.0', '!='); // Returns: false
```
#### Version range checking
```typescript
import { compare } from 'compare-versions';
const currentVersion = '2.5.3';
const minRequired = '2.0.0';
const maxSupported = '3.0.0';
if (compare(currentVersion, minRequired, '>=') &&
compare(currentVersion, maxSupported, '<')) {
console.log('Version is supported');
}
```
#### Pre-release comparison
```typescript
import { compare } from 'compare-versions';
compare('1.0.0', '1.0.0-beta', '>'); // Returns: true
compare('1.0.0-rc.1', '1.0.0-rc.2', '<'); // Returns: true
```
```