|
| 1 | +import { arch, platform, release, version } from 'os'; |
| 2 | +import { FeatureFlag } from './FeatureFlagI'; |
| 3 | + |
| 4 | +type HardwareMatch = { |
| 5 | + arch?: string | string[]; |
| 6 | + platform?: string | string[]; |
| 7 | + release?: string | string[]; |
| 8 | + version?: string | string[]; |
| 9 | + nodeVersion?: string | string[]; |
| 10 | + processArch?: string | string[]; |
| 11 | + processPlatform?: string | string[]; |
| 12 | +}; |
| 13 | + |
| 14 | +export class HardwareFeatureFlag implements FeatureFlag { |
| 15 | + private readonly enabled: boolean; |
| 16 | + |
| 17 | + constructor( |
| 18 | + private readonly featureName: string, |
| 19 | + private readonly match: HardwareMatch, |
| 20 | + private readonly partial: boolean = false, |
| 21 | + ) { |
| 22 | + const checks = [ |
| 23 | + this.matchProperty(arch(), this.match.arch), |
| 24 | + this.matchProperty(platform(), this.match.platform), |
| 25 | + this.matchProperty(release(), this.match.release), |
| 26 | + this.matchProperty(version(), this.match.version), |
| 27 | + this.matchProperty(process.version, this.match.nodeVersion), |
| 28 | + this.matchProperty(process.arch, this.match.processArch), |
| 29 | + this.matchProperty(process.platform, this.match.processPlatform), |
| 30 | + ]; |
| 31 | + |
| 32 | + this.enabled = checks.every(Boolean); |
| 33 | + } |
| 34 | + |
| 35 | + private matchProperty(actual: string, expected?: string | string[]): boolean { |
| 36 | + if (expected === undefined) { |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + const patterns = Array.isArray(expected) ? expected : [expected]; |
| 41 | + |
| 42 | + return patterns.some((pattern) => { |
| 43 | + return this.partial ? actual.includes(pattern) : actual === pattern; |
| 44 | + }); |
| 45 | + } |
| 46 | + |
| 47 | + isEnabled(): boolean { |
| 48 | + return this.enabled; |
| 49 | + } |
| 50 | + |
| 51 | + describe(): string { |
| 52 | + const matchStr = JSON.stringify(this.match); |
| 53 | + return `HardwareFeatureFlag(feature=${this.featureName}, match=${matchStr}, partial=${this.partial}, enabled=${this.enabled})`; |
| 54 | + } |
| 55 | +} |
0 commit comments