diff --git a/src/util/time.ts b/src/util/time.ts index cc87e52..0d7ba8a 100644 --- a/src/util/time.ts +++ b/src/util/time.ts @@ -24,7 +24,7 @@ export function toNumber(v: unknown): number | null { if (typeof v === "number") { return Number.isFinite(v) ? v : null; } - if (typeof v === "string") { + if (typeof v === "string" && v.trim() !== "") { const n = Number(v); return Number.isFinite(n) ? n : null; } @@ -53,16 +53,19 @@ function pad2(n: number): string { /** `{year:2026,month:8,day:5}` -> `"2026-08-05"`. */ export function apiDateToIso(d: ApiDate | undefined | null): string | null { if ( - !( - d && - Number.isFinite(d.year) && - Number.isFinite(d.month) && - Number.isFinite(d.day) - ) + !(d && Number.isInteger(d.year)) || + d.year < 1 || + d.year > 9999 || + !Number.isInteger(d.month) || + !Number.isInteger(d.day) ) { return null; } - return `${d.year}-${pad2(d.month)}-${pad2(d.day)}`; + const iso = `${String(d.year).padStart(4, "0")}-${pad2(d.month)}-${pad2(d.day)}`; + const ms = Date.parse(`${iso}T00:00:00Z`); + return Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === iso + ? iso + : null; } /** @@ -200,12 +203,15 @@ export function parseSince(input: string, now: Date = new Date()): Date { } else if (rel[2] === "w") { days = n * 7; } - return new Date(now.getTime() - days * 86_400_000); + const result = new Date(now.getTime() - days * 86_400_000); + if (Number.isFinite(result.getTime())) { + return result; + } } if (ISO_DATE_RE.test(s)) { const ms = Date.parse(`${s}T00:00:00Z`); - if (Number.isFinite(ms)) { + if (Number.isFinite(ms) && new Date(ms).toISOString().slice(0, 10) === s) { return new Date(ms); } } diff --git a/test/time-regression.test.ts b/test/time-regression.test.ts new file mode 100644 index 0000000..72fe210 --- /dev/null +++ b/test/time-regression.test.ts @@ -0,0 +1,29 @@ +import { expect, it } from "vitest"; +import { apiDateToIso, parseSince, toNumber } from "../src/util/time.js"; + +it("does not turn whitespace-only API measurements into zero", () => { + expect(toNumber(" \t\n")).toBeNull(); + expect(toNumber(" 0 ")).toBe(0); + expect(toNumber(" 71.5 ")).toBe(71.5); +}); + +it("rejects invalid calendar dates instead of archiving or normalizing them", () => { + for (const date of [ + { day: 30, month: 2, year: 2026 }, + { day: 1, month: 13, year: 2026 }, + { day: 0, month: 1, year: 2026 }, + { day: 1, month: 1.5, year: 2026 }, + ]) { + expect(apiDateToIso(date)).toBeNull(); + } + expect(() => parseSince("2026-02-30")).toThrow(); + expect(apiDateToIso({ day: 29, month: 2, year: 2024 })).toBe("2024-02-29"); + expect(apiDateToIso({ day: 1, month: 1, year: 99 })).toBe("0099-01-01"); +}); + +it("rejects relative durations outside the representable date range", () => { + expect(() => parseSince("999999999999999999999999999999d")).toThrow(); + expect(parseSince("1d", new Date("2026-10-22T00:00:00Z")).toISOString()).toBe( + "2026-10-21T00:00:00.000Z" + ); +});