// A RECURRING REPORT'S CADENCE (umtool R5; plans/umtool-redesign.md "R5 — // Recurring reports"): when a schedule ticks, as pure maths on the local // clock of a named time zone. No disk, no Date.now(): every function takes // the instant it reasons about, so the editor's runner, the ops action's plan // and umtool's chip agree and the tests can stand on a DST change. // // daily every day at HH:MM // weekly every (0 = Sunday … 6 = Saturday) at HH:MM // every N days every N days at HH:MM, counted from the ANCHOR — the // local date of the schedule's first tick (2 ≤ N ≤ 365) // // THE LOCAL CLOCK. "06:00" is wall-clock time in the schedule's `tz` (the // editor's zone when it was made). A wall time a spring-forward skips // (02:30 on the day clocks jump 02:00 → 03:00) ticks at the same distance // past the gap (03:30); a time a fall-back repeats (01:30 twice) ticks at its // FIRST occurrence. Never twice, never not at all. // // A MISSED WINDOW IS ONE CATCH-UP TICK, NEVER N. An editor down over three // daily windows ticks ONCE when it comes back (`dueTick`), and the next tick // is the next window after now — the three it missed are counted, not run. // // Pure: safe for a client component. export const CADENCE_KINDS = ["daily", "weekly", "every"] as const; export type CadenceKind = (typeof CADENCE_KINDS)[number]; export type Cadence = | { kind: "daily"; at: string } | { kind: "weekly"; dow: number; at: string } | { kind: "every"; days: number; at: string }; export const DOW_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const; const DOW_LONG = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]; export const EVERY_MIN_DAYS = 2; export const EVERY_MAX_DAYS = 365; const HHMM = /^([01]\d|2[0-3]):([0-5]\d)$/; const YMD = /^(\d{4})-(\d{2})-(\d{2})$/; const DAY_MS = 86_400_000; export class CadenceError extends Error {} /** The editor's (this process's) IANA zone. */ export function localTimeZone(): string { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; } catch { return "UTC"; } } /** Whether `tz` is a zone this runtime knows. */ export function isTimeZone(tz: unknown): tz is string { if (typeof tz !== "string" || !tz) return false; try { new Intl.DateTimeFormat("en-US", { timeZone: tz }); return true; } catch { return false; } } // ─── parsing ─── function normAt(v: unknown): string { if (typeof v !== "string") throw new CadenceError('"at" is a time of day, HH:MM (24-hour)'); const s = v.trim(); const m = /^(\d{1,2}):(\d{2})$/.exec(s); const t = m ? `${m[1].padStart(2, "0")}:${m[2]}` : s; if (!HHMM.test(t)) throw new CadenceError(`"at" is a time of day, HH:MM (24-hour): not ${JSON.stringify(v)}`); return t; } function normDow(v: unknown): number { if (typeof v === "number" && Number.isInteger(v) && v >= 0 && v <= 6) return v; if (typeof v === "string") { const s = v.trim().toLowerCase(); if (/^[0-6]$/.test(s)) return Number(s); const i = DOW_LONG.findIndex((d) => s.length >= 3 && d.startsWith(s)); if (i >= 0) return i; } throw new CadenceError(`"dow" is a day of the week (0 = Sunday … 6 = Saturday, or its name): not ${JSON.stringify(v)}`); } /** * A cadence from an object (`{kind, at, dow?, days?}`) or a phrase: * "daily 06:00", "weekly mon 06:00", "every 3 days 06:00" (the time defaults * to 06:00 when a phrase leaves it out). Throws CadenceError, saying what to fix. */ export function parseCadence(input: unknown): Cadence { if (typeof input === "string") { const words = input.trim().toLowerCase().split(/\s+/).filter(Boolean); const at = words.find((w) => /^\d{1,2}:\d{2}$/.test(w)) ?? "06:00"; const rest = words.filter((w) => w !== at && w !== "at" && w !== "on"); if (rest[0] === "daily" || (rest[0] === "every" && rest[1] === "day")) return { kind: "daily", at: normAt(at) }; if (rest[0] === "weekly") return { kind: "weekly", dow: normDow(rest[1]), at: normAt(at) }; if (rest[0] === "every" && rest[1] && /^\d+$/.test(rest[1])) return parseCadence({ kind: "every", days: Number(rest[1]), at }); throw new CadenceError(`a cadence is "daily HH:MM", "weekly HH:MM" or "every N days HH:MM": not ${JSON.stringify(input)}`); } if (!input || typeof input !== "object" || Array.isArray(input)) { throw new CadenceError('"cadence" is {kind: "daily" | "weekly" | "every", at: "HH:MM", dow?, days?} or a phrase like "weekly mon 06:00"'); } const r = input as Record; const at = normAt(r.at ?? "06:00"); if (r.kind === "daily") return { kind: "daily", at }; if (r.kind === "weekly") return { kind: "weekly", dow: normDow(r.dow), at }; if (r.kind === "every") { const days = typeof r.days === "string" ? Number(r.days) : r.days; if (typeof days !== "number" || !Number.isInteger(days) || days < EVERY_MIN_DAYS || days > EVERY_MAX_DAYS) { throw new CadenceError(`"days" is a whole number of days, ${EVERY_MIN_DAYS} to ${EVERY_MAX_DAYS} (every day is "daily")`); } return { kind: "every", days, at }; } throw new CadenceError(`"kind" is one of ${CADENCE_KINDS.join(", ")}`); } /** The cadence's length in days: what one window covers. */ export function cadenceDays(c: Cadence): number { return c.kind === "daily" ? 1 : c.kind === "weekly" ? 7 : c.days; } // ─── the local clock ─── export type CivilDate = { y: number; m: number; d: number }; type Wall = CivilDate & { hh: number; mm: number }; const fmtCache = new Map(); function fmt(tz: string): Intl.DateTimeFormat { let f = fmtCache.get(tz); if (!f) { f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", }); fmtCache.set(tz, f); } return f; } /** The wall clock in `tz` at instant `t` (ms). */ export function wallOf(t: number, tz: string): Wall & { ss: number } { const parts = fmt(tz).formatToParts(new Date(t)); const n = (type: string) => Number(parts.find((p) => p.type === type)?.value ?? 0); return { y: n("year"), m: n("month"), d: n("day"), hh: n("hour") % 24, mm: n("minute"), ss: n("second") }; } // The zone's offset from UTC at instant t, in ms (local = utc + offset). function offsetAt(t: number, tz: string): number { const w = wallOf(t, tz); const asUtc = Date.UTC(w.y, w.m - 1, w.d, w.hh, w.mm, w.ss); return asUtc - Math.floor(t / 1000) * 1000; } /** * The instant whose wall clock in `tz` is `w` — the first of two in a * fall-back, the same distance past the gap in a spring-forward. */ export function instantOf(w: Wall, tz: string): number { const asUtc = Date.UTC(w.y, w.m - 1, w.d, w.hh, w.mm); const before = asUtc - offsetAt(asUtc - DAY_MS, tz); const after = asUtc - offsetAt(asUtc + DAY_MS, tz); const ok = (t: number) => { const x = wallOf(t, tz); return x.y === w.y && x.m === w.m && x.d === w.d && x.hh === w.hh && x.mm === w.mm; }; const hits = [before, after].filter(ok); if (hits.length) return Math.min(...hits); // In the gap: the offset before it carries the wall time past it. return before; } /** Days since 1970-01-01 of a civil date. */ const dayNumber = (c: CivilDate) => Math.round(Date.UTC(c.y, c.m - 1, c.d) / DAY_MS); const civilOf = (n: number): CivilDate => { const dt = new Date(n * DAY_MS); return { y: dt.getUTCFullYear(), m: dt.getUTCMonth() + 1, d: dt.getUTCDate() }; }; const dowOf = (c: CivilDate) => new Date(Date.UTC(c.y, c.m - 1, c.d)).getUTCDay(); export const ymdOf = (c: CivilDate) => `${String(c.y).padStart(4, "0")}-${String(c.m).padStart(2, "0")}-${String(c.d).padStart(2, "0")}`; export function parseYmd(s: string): CivilDate { const m = YMD.exec(s); if (!m) throw new CadenceError(`not a YYYY-MM-DD date: ${JSON.stringify(s)}`); return { y: Number(m[1]), m: Number(m[2]), d: Number(m[3]) }; } /** The local date (YYYY-MM-DD) in `tz` at instant t. */ export function localDate(t: number, tz: string): string { return ymdOf(wallOf(t, tz)); } /** `ymd` moved by `days` (negative: back). */ export function addDays(ymd: string, days: number): string { return ymdOf(civilOf(dayNumber(parseYmd(ymd)) + days)); } const atOf = (c: Cadence) => { const [hh, mm] = c.at.split(":").map(Number); return { hh, mm }; }; // ─── the windows ─── /** * The first tick strictly after `after` (ms). `anchor` (YYYY-MM-DD) is an * every-N-days schedule's first tick's local date; without one the series * starts at the next HH:MM, as a daily one would. */ export function nextTickAfter(c: Cadence, after: number, tz: string, anchor?: string | null): number { const { hh, mm } = atOf(c); const today = dayNumber(wallOf(after, tz)); const at = (day: number) => instantOf({ ...civilOf(day), hh, mm }, tz); if (c.kind === "daily" || (c.kind === "every" && !anchor)) { for (let k = 0; k < 3; k++) { const t = at(today + k); if (t > after) return t; } } else if (c.kind === "weekly") { for (let k = 0; k < 9; k++) { const day = today + k; if (dowOf(civilOf(day)) !== c.dow) continue; const t = at(day); if (t > after) return t; } } else { const a = dayNumber(parseYmd(anchor!)); const first = Math.max(0, Math.floor((today - a) / c.days)); for (let k = first; k < first + 3; k++) { const t = at(a + k * c.days); if (t > after) return t; } } // Unreachable for a valid cadence; never a tick in the past. throw new CadenceError("no next tick: the cadence is not valid"); } /** The anchor an every-N-days schedule takes from its first tick (its local date); null for the others. */ export function anchorFor(c: Cadence, firstTick: number, tz: string): string | null { return c.kind === "every" ? localDate(firstTick, tz) : null; } /** * Is a tick due at `now`? `nextTick` is the window the schedule waits for. * Due: ONE tick, for that window, however many have passed since (`missed` * counts the later ones it stands in for), and the window after it is the * first one after now — never a queue of catch-ups. */ export function dueTick( s: { cadence: Cadence; tz: string; anchor?: string | null; nextTick: string | null; paused?: boolean }, now: number, ): { due: false } | { due: true; scheduledFor: number; missed: number; next: number } { if (s.paused || !s.nextTick) return { due: false }; const scheduledFor = Date.parse(s.nextTick); if (!Number.isFinite(scheduledFor) || scheduledFor > now) return { due: false }; let missed = 0; let t = scheduledFor; // Count the windows passed since (bounded: a schedule asleep for years is // not a loop of thousands). for (; missed < 1000; missed++) { t = nextTickAfter(s.cadence, t, s.tz, s.anchor); if (t > now) break; } return { due: true, scheduledFor, missed, next: t }; } // ─── words ─── /** "daily 06:00", "weekly · Mon 06:00", "every 3 days 06:00". */ export function cadenceWords(c: Cadence): string { if (c.kind === "daily") return `daily ${c.at}`; if (c.kind === "weekly") return `weekly · ${DOW_NAMES[c.dow]} ${c.at}`; return `every ${c.days} days ${c.at}`; } /** "Mon 06:00" — a tick's local day and time; with the date when it is a week or more away (or past). */ export function tickWords(t: number, tz: string, now?: number): string { const w = wallOf(t, tz); const time = `${String(w.hh).padStart(2, "0")}:${String(w.mm).padStart(2, "0")}`; const day = DOW_NAMES[dowOf(w)]; if (now !== undefined && (t - now >= 7 * DAY_MS || t < now - DAY_MS)) return `${ymdOf(w)} ${time}`; return `${day} ${time}`; } /** The chip: "weekly · next Mon 06:00", "daily · paused". */ export function chipWords( s: { cadence: Cadence; tz: string; nextTick: string | null; paused?: boolean }, now?: number, ): string { const kind = s.cadence.kind === "every" ? `every ${s.cadence.days} days` : s.cadence.kind; if (s.paused) return `${kind} · paused`; const next = s.nextTick ? Date.parse(s.nextTick) : NaN; if (!Number.isFinite(next)) return kind; return `${kind} · next ${tickWords(next, s.tz, now)}`; }