|
| 1 | +import valid from "semver/functions/valid"; |
| 2 | +import satisfies from "semver/functions/satisfies"; |
| 3 | +import lt from "semver/functions/lt"; |
| 4 | + |
| 5 | +export { default as bundledBunModules } from "@assets/bun-modules.json"; |
| 6 | +export { default as implementedNodeModules } from "@assets/implemented-node-modules.json"; |
| 7 | + |
| 8 | +type SemVerBaseStringified = `${bigint}.${bigint}.${bigint}`; |
| 9 | +type SemVerStringifiedWithReleaseName = `${SemVerBaseStringified}-${string}`; |
| 10 | +type SemVerStringified = SemVerBaseStringified | SemVerStringifiedWithReleaseName; |
| 11 | +export type BunVersion = SemVerStringified | "latest"; |
| 12 | + |
| 13 | +export type Modules = Record<string, string | boolean>; |
| 14 | + |
| 15 | +export const MINIMUM_BUN_VERSION = "1.0.0" satisfies SemVerBaseStringified; |
| 16 | + |
| 17 | +export function checkModule(moduleName: string, modules: Modules, bunVersion: BunVersion): boolean { |
| 18 | + if (typeof moduleName !== "string") throw new TypeError("Module name must be a string"); |
| 19 | + if (!(moduleName in modules)) return false; |
| 20 | + |
| 21 | + const targetBunVersion = toSemVerStringified(bunVersion); |
| 22 | + if (lt(targetBunVersion, MINIMUM_BUN_VERSION)) { |
| 23 | + throw new RangeError(`Bun version must be at least ${MINIMUM_BUN_VERSION}`); |
| 24 | + } |
| 25 | + |
| 26 | + return satisfiesVersionRange(targetBunVersion, modules[moduleName]!); |
| 27 | +} |
| 28 | + |
| 29 | +export function getModules(modules: Modules, bunVersion?: BunVersion): string[] { |
| 30 | + const targetBunVersion = toSemVerStringified(bunVersion); |
| 31 | + if (lt(targetBunVersion, MINIMUM_BUN_VERSION)) { |
| 32 | + throw new RangeError(`Bun version must be at least ${MINIMUM_BUN_VERSION}`); |
| 33 | + } |
| 34 | + |
| 35 | + return Object.keys(modules).filter((moduleName) => { |
| 36 | + return satisfiesVersionRange(targetBunVersion, modules[moduleName]!); |
| 37 | + }); |
| 38 | +} |
| 39 | + |
| 40 | +function satisfiesVersionRange( |
| 41 | + version: SemVerStringified, |
| 42 | + versionRange: string | boolean, |
| 43 | +): boolean { |
| 44 | + if (typeof versionRange === "boolean") return versionRange; |
| 45 | + return satisfies(version, versionRange); |
| 46 | +} |
| 47 | + |
| 48 | +function toSemVerStringified(input: unknown): SemVerStringified { |
| 49 | + if (typeof input !== "string") throw new TypeError("Bun version must be a string"); |
| 50 | + if (input === "latest") return "999.999.999" as SemVerStringified; |
| 51 | + if (valid(input)) return input as SemVerBaseStringified; |
| 52 | + throw new TypeError("Bun version must be a string like '1.0.0' or 'latest'"); |
| 53 | +} |
0 commit comments