Files
archie/ui/src/devtools/ui-sdk/schedule-rule.ts
T
sam fe4d574976 feat(ui): add an isolated UI SDK lab under devtools
The lab is a dev-only route and a standalone entry so beta SDK patterns stay
out of shipped pages while they are evaluated.
2026-11-25 22:11:42 +11:00

44 lines
1.5 KiB
TypeScript

export type CronRule =
| { cadence: "daily"; time: string }
| { cadence: "weekly"; time: string; weekdays: readonly number[] }
| { cadence: "monthly"; time: string; day: number };
function clockFields(time: string): [number, number] | null {
const match = /^(\d{2}):(\d{2})$/.exec(time);
if (!match) return null;
const hour = Number(match[1]);
const minute = Number(match[2]);
if (hour > 23 || minute > 59) return null;
return [hour, minute];
}
function weekdayField(values: readonly number[]): string | null {
if (!values.length || values.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) {
return null;
}
const days = [...new Set(values)].sort((a, b) => a - b);
if (days.length === 7) return "*";
if (days.join(",") === "1,2,3,4,5") return "1-5";
if (days.join(",") === "0,6") return "0,6";
return days.join(",");
}
export function cronForRule(rule: CronRule): string | null {
if ("cadence" in rule && "time" in rule) {
const clock = clockFields(rule.time);
if (!clock) return null;
const [hour, minute] = clock;
if (rule.cadence === "daily") return `${minute} ${hour} * * *`;
if (rule.cadence === "weekly") {
const weekdays = weekdayField(rule.weekdays);
return weekdays === null ? null : `${minute} ${hour} * * ${weekdays}`;
}
if (rule.cadence === "monthly") {
return Number.isInteger(rule.day) && rule.day >= 1 && rule.day <= 31
? `${minute} ${hour} ${rule.day} * *`
: null;
}
}
return null;
}