summaryrefslogtreecommitdiff
path: root/node_modules/@11ty/eleventy/src/Util/Compatibility.js
blob: c90a9b331adc0c9d1489b26ca5d954e1cb783224 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import semver from "semver";

import { getEleventyPackageJson, getWorkingProjectPackageJson } from "./ImportJsonSync.js";

const pkg = getEleventyPackageJson();

// Used in user config versionCheck method.
class Compatibility {
	static NORMALIZE_PRERELEASE_REGEX = /-canary\b/g;

	static #projectPackageJson;

	constructor(compatibleRange) {
		this.compatibleRange = Compatibility.getCompatibilityValue(compatibleRange);
	}

	static get projectPackageJson() {
		if (!this.#projectPackageJson) {
			this.#projectPackageJson = getWorkingProjectPackageJson();
		}

		return this.#projectPackageJson;
	}

	static normalizeIdentifier(identifier) {
		return identifier.replace(Compatibility.NORMALIZE_PRERELEASE_REGEX, "-alpha");
	}

	static getCompatibilityValue(compatibleRange) {
		if (compatibleRange) {
			return compatibleRange;
		}

		// fetch from project’s package.json
		if (this.projectPackageJson?.["11ty"]?.compatibility) {
			return this.projectPackageJson["11ty"].compatibility;
		}
	}

	isCompatible() {
		return Compatibility.satisfies(pkg.version, this.compatibleRange);
	}

	static satisfies(version, compatibleRange) {
		return semver.satisfies(
			Compatibility.normalizeIdentifier(version),
			Compatibility.normalizeIdentifier(compatibleRange),
			{
				includePrerelease: true,
			},
		);
	}

	getErrorMessage() {
		return `We found Eleventy version '${pkg.version}' which does not meet the required version range: '${this.compatibleRange}'. Use \`npm install @11ty/eleventy\` to upgrade your local project to the latest Eleventy version (or \`npm install @11ty/eleventy -g\` to upgrade the globally installed version).`;
	}
}

export default Compatibility;