UNPKG

better-auth

Version:

The most comprehensive authentication framework for TypeScript.

100 lines (99 loc) 2.36 kB
//#region src/utils/time.ts const SEC = 1e3; const MIN = SEC * 60; const HOUR = MIN * 60; const DAY = HOUR * 24; const WEEK = DAY * 7; const MONTH = DAY * 30; const YEAR = DAY * 365.25; const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)(?: (ago|from now))?$/i; function parse(value) { const match = REGEX.exec(value); if (!match || match[4] && match[1]) throw new TypeError(`Invalid time string format: "${value}". Use formats like "7d", "30m", "1 hour", etc.`); const n = parseFloat(match[2]); const unit = match[3].toLowerCase(); let result; switch (unit) { case "years": case "year": case "yrs": case "yr": case "y": result = n * YEAR; break; case "months": case "month": case "mo": result = n * MONTH; break; case "weeks": case "week": case "w": result = n * WEEK; break; case "days": case "day": case "d": result = n * DAY; break; case "hours": case "hour": case "hrs": case "hr": case "h": result = n * HOUR; break; case "minutes": case "minute": case "mins": case "min": case "m": result = n * MIN; break; case "seconds": case "second": case "secs": case "sec": case "s": result = n * SEC; break; default: throw new TypeError(`Unknown time unit: "${unit}"`); } if (match[1] === "-" || match[4] === "ago") return -result; return result; } /** * Parse a time string and return the value in milliseconds. * * @param value - A time string like "7d", "30m", "1 hour", "2 hours ago" * @returns The parsed value in milliseconds * @throws TypeError if the string format is invalid * * @example * ms("1d") // 86400000 * ms("2 hours") // 7200000 * ms("30s") // 30000 * ms("2 hours ago") // -7200000 */ function ms(value) { return parse(value); } /** * Parse a time string and return the value in seconds. * * @param value - A time string like "7d", "30m", "1 hour", "2 hours ago" * @returns The parsed value in seconds (rounded) * @throws TypeError if the string format is invalid * * @example * sec("1d") // 86400 * sec("2 hours") // 7200 * sec("-30s") // -30 * sec("2 hours ago") // -7200 */ function sec(value) { return Math.round(parse(value) / 1e3); } //#endregion export { ms, sec }; //# sourceMappingURL=time.mjs.map