Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ulixee
GitHub Repository: ulixee/secret-agent
Path: blob/main/plugins/default-browser-emulator/lib/VersionUtils.ts
1029 views
1
import * as macOsVersionAliasMap from '../data/macOsVersionAliasMap.json';
2
3
export function convertMacOsVersionString(versionString: string) {
4
let newVersionString = macOsVersionAliasMap[versionString];
5
if (!newVersionString) {
6
const [majorVersion] = versionString.split('.');
7
newVersionString = macOsVersionAliasMap[`${majorVersion}.*`];
8
}
9
return newVersionString || versionString;
10
}
11
12
export function findClosestVersionMatch(versionToMatch: string, versions: string[]) {
13
if (versions.length === 1 && versions[0] === 'ALL') return 'ALL';
14
if (!versions.length) return null;
15
16
// there is no guarantee we have an exact match, so let's get the closest
17
const versionTree = convertVersionsToTree(versions);
18
const [major, minor] = versionToMatch.split('-').map(x => Number(x));
19
20
const majors = Object.keys(versionTree).map(x => Number(x));
21
const majorMatch = getClosestNumberMatch(major, majors);
22
let versionMatch = `${majorMatch}`;
23
24
if (minor) {
25
const minors = Object.keys(versionTree[majorMatch]).map(x => Number(x));
26
const minorMatch = getClosestNumberMatch(minor, minors);
27
if (minorMatch !== undefined) versionMatch += `-${minorMatch}`;
28
} else if (!versions.includes(versionMatch)) {
29
const minors = Object.keys(versionTree[majorMatch]).map(x => Number(x));
30
if (minors.length) {
31
const minorMatch = major > majorMatch ? Math.max(...minors) : Math.min(...minors);
32
versionMatch += `-${minorMatch}`;
33
}
34
}
35
36
return versions.includes(versionMatch) ? versionMatch : null;
37
}
38
39
export function getClosestNumberMatch(numToMatch: number, nums: number[]) {
40
const sortedNums = nums.sort((a, b) => a - b);
41
let closest = sortedNums[0];
42
for (const num of sortedNums) {
43
if (num === numToMatch) {
44
return num;
45
}
46
if (num < numToMatch) {
47
closest = num;
48
} else if (num > numToMatch) {
49
break;
50
}
51
}
52
return closest;
53
}
54
55
export function convertVersionsToTree(versions: string[]): IVersionTree {
56
return versions.reduce((tree: any, version: string) => {
57
const [major, minor, build] = version.split(/\.|-/);
58
tree[major] = tree[major] || {};
59
if (minor === undefined) return tree;
60
tree[major][minor] = tree[major][minor] || [];
61
if (build) tree[major][minor].push(build);
62
return tree;
63
}, {});
64
}
65
66
export interface IVersionTree {
67
[major: number]: {
68
[minor: number]: number[];
69
};
70
}
71
72