Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

TypeScript · 59 lines · 1.9 KiB · at 2e2b18f

export class SemverError extends Error {  constructor(    public readonly kind: "invalid_version",    public readonly input: string,  ) {    super(`${kind}: ${input}`);  }}type Parsed = { core: [string, string, 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 parse = (v: string): Parsed => {  const m = typeof v === "string" ? RE.exec(v) : null;  if (!m) throw new SemverError("invalid_version", v);  return { core: [m[1], m[2], m[3]], pre: m[4] === undefined ? [] : m[4].split(".") };};const sign = (n: number): -1 | 0 | 1 => (n < 0 ? -1 : n > 0 ? 1 : 0);// Digit strings without leading zeros: longer is larger, else lexical.const cmpDigits = (x: string, y: string): -1 | 0 | 1 =>  x.length !== y.length ? sign(x.length - y.length) : x < y ? -1 : x > y ? 1 : 0;const isNumeric = (s: string): boolean => /^[0-9]+$/.test(s);const cmpIdent = (x: string, y: string): -1 | 0 | 1 => {  const nx = isNumeric(x);  const ny = isNumeric(y);  if (nx && ny) return cmpDigits(x, y);  if (nx) return -1;  if (ny) return 1;  return x < y ? -1 : x > y ? 1 : 0;};/** Throws SemverError when either version is invalid (a is checked first). */export function compareSemver(a: string, b: string): -1 | 0 | 1 {  const pa = parse(a);  const pb = parse(b);  for (let i = 0; i < 3; i++) {    const c = cmpDigits(pa.core[i], pb.core[i]);    if (c !== 0) return c;  }  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);  for (let i = 0; i < n; i++) {    const c = cmpIdent(pa.pre[i], pb.pre[i]);    if (c !== 0) return c;  }  return sign(pa.pre.length - pb.pre.length);}