import { Ok, Err, type Option, type Result } from "@tsus/runtime";import { fromNullable } from "@tsus/runtime/boundary";export type SemverError = { kind: "invalid_version"; input: string };type Ord = -1 | 0 | 1;type Parsed = { core: string[]; pre: string[] };const NUM = "(0|[1-9][0-9]*)";const PRE_ID = "(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)";const BUILD_ID = "[0-9A-Za-z-]+";const RE = new RegExp( `^${NUM}\\.${NUM}\\.${NUM}(?:-(${PRE_ID}(?:\\.${PRE_ID})*))?(?:\\+${BUILD_ID}(?:\\.${BUILD_ID})*)?$`,);const toParsed = (m: RegExpExecArray): Parsed => ({ core: [m[1], m[2], m[3]], pre: fromNullable(m[4]).map((p: string) => p.split(".")).unwrapOr([]),});const parse = (v: string): Result<Parsed, SemverError> => { const m: Option<RegExpExecArray> = typeof v === "string" ? fromNullable(RE.exec(v)) : fromNullable(RE.exec("")); return match (m) { Some(found) => Ok(toParsed(found)), None => Err({ kind: "invalid_version", input: v }), };};const sign = (n: number): Ord => (n < 0 ? -1 : n > 0 ? 1 : 0);const cmpStr = (x: string, y: string): Ord => (x < y ? -1 : x > y ? 1 : 0);const cmpDigits = (x: string, y: string): Ord => (x.length !== y.length ? sign(x.length - y.length) : cmpStr(x, y));const isNumeric = (s: string): boolean => /^[0-9]+$/.test(s);const cmpIdent = (x: string, y: string): Ord => { const nx = isNumeric(x); const ny = isNumeric(y); return nx && ny ? cmpDigits(x, y) : nx ? -1 : ny ? 1 : cmpStr(x, y);};const firstNonZero = (pairs: Array<[string, string]>, cmp: (x: string, y: string) => Ord): Ord => { for (const [x, y] of pairs) { const c = cmp(x, y); if (c !== 0) { return c; } } return 0;};const compareParsed = (pa: Parsed, pb: Parsed): Ord => { const core = firstNonZero( pa.core.map((x, i): [string, string] => [x, pb.core[i]]), cmpDigits, ); if (core !== 0) { return core; } if (pa.pre.length === 0 && pb.pre.length === 0) { return 0; } if (pa.pre.length === 0) { return 1; } if (pb.pre.length === 0) { return -1; } const n = Math.min(pa.pre.length, pb.pre.length); const pre = firstNonZero( pa.pre.slice(0, n).map((x, i): [string, string] => [x, pb.pre[i]]), cmpIdent, ); return pre !== 0 ? pre : sign(pa.pre.length - pb.pre.length);};export const compareSemver = (a: string, b: string): Result<Ord, SemverError> => parse(a).andThen((pa) => parse(b).map((pb) => compareParsed(pa, pb)));