|
| 1 | +import * as semver from 'semver'; |
| 2 | + |
| 3 | +export interface SemverVersionConstraint { |
| 4 | + readonly range: string; |
| 5 | + readonly options?: Parameters<typeof semver.satisfies>[2]; |
| 6 | +} |
| 7 | +export type AtLeastVersionConstraint = |
| 8 | + | `${number}` |
| 9 | + | `${number}.${number}` |
| 10 | + | `${number}.${number}.${number}` |
| 11 | + | `${number}.${number}.${number}-${string}`; |
| 12 | +export type VersionConstraint = |
| 13 | + | SemverVersionConstraint |
| 14 | + | AtLeastVersionConstraint; |
| 15 | +export interface DependencyConstraint { |
| 16 | + readonly typescript: VersionConstraint; |
| 17 | + readonly eslint: VersionConstraint; |
| 18 | + /** |
| 19 | + * Passing a string for the value is shorthand for a '>=' constraint |
| 20 | + */ |
| 21 | + readonly [packageName: string]: VersionConstraint; |
| 22 | +} |
| 23 | + |
| 24 | +const BASE_SATISFIES_OPTIONS: semver.RangeOptions = { |
| 25 | + includePrerelease: true, |
| 26 | +}; |
| 27 | + |
| 28 | +function satisfiesDependencyConstraint( |
| 29 | + packageName: string, |
| 30 | + constraintIn: DependencyConstraint[string], |
| 31 | +): boolean { |
| 32 | + const constraint: SemverVersionConstraint = |
| 33 | + typeof constraintIn === 'string' |
| 34 | + ? { |
| 35 | + range: `>=${constraintIn}`, |
| 36 | + } |
| 37 | + : constraintIn; |
| 38 | + |
| 39 | + return semver.satisfies( |
| 40 | + (require(`${packageName}/package.json`) as { version: string }).version, |
| 41 | + constraint.range, |
| 42 | + typeof constraint.options === 'object' |
| 43 | + ? { ...BASE_SATISFIES_OPTIONS, ...constraint.options } |
| 44 | + : constraint.options, |
| 45 | + ); |
| 46 | +} |
| 47 | + |
| 48 | +export function satisfiesAllDependencyConstraints( |
| 49 | + dependencyConstraints: DependencyConstraint | undefined, |
| 50 | +): boolean { |
| 51 | + if (dependencyConstraints == null) { |
| 52 | + return true; |
| 53 | + } |
| 54 | + |
| 55 | + for (const [packageName, constraint] of Object.entries( |
| 56 | + dependencyConstraints, |
| 57 | + )) { |
| 58 | + if (!satisfiesDependencyConstraint(packageName, constraint)) { |
| 59 | + return false; |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + return true; |
| 64 | +} |
0 commit comments