cron-toolkit 0.0.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +245 -0
  3. package/dist/constants.d.ts +15 -0
  4. package/dist/constants.js +28 -0
  5. package/dist/core/ast.d.ts +10 -0
  6. package/dist/core/ast.js +27 -0
  7. package/dist/core/dialects.d.ts +33 -0
  8. package/dist/core/dialects.js +50 -0
  9. package/dist/core/errors.d.ts +19 -0
  10. package/dist/core/errors.js +74 -0
  11. package/dist/core/fields.d.ts +15 -0
  12. package/dist/core/fields.js +167 -0
  13. package/dist/core/format.d.ts +17 -0
  14. package/dist/core/format.js +110 -0
  15. package/dist/core/parse.d.ts +10 -0
  16. package/dist/core/parse.js +102 -0
  17. package/dist/core/types.d.ts +88 -0
  18. package/dist/core/types.js +1 -0
  19. package/dist/describe/describer.d.ts +4 -0
  20. package/dist/describe/describer.js +224 -0
  21. package/dist/describe/intl.d.ts +11 -0
  22. package/dist/describe/intl.js +32 -0
  23. package/dist/describe/locale.d.ts +64 -0
  24. package/dist/describe/locale.js +1 -0
  25. package/dist/describe.d.ts +19 -0
  26. package/dist/describe.js +14 -0
  27. package/dist/index.d.ts +6 -0
  28. package/dist/index.js +4 -0
  29. package/dist/locales/en.d.ts +2 -0
  30. package/dist/locales/en.js +40 -0
  31. package/dist/locales/es.d.ts +2 -0
  32. package/dist/locales/es.js +101 -0
  33. package/dist/locales/fr.d.ts +2 -0
  34. package/dist/locales/fr.js +101 -0
  35. package/dist/recurrence/recurrence.d.ts +15 -0
  36. package/dist/recurrence/recurrence.js +222 -0
  37. package/dist/recurrence/types.d.ts +56 -0
  38. package/dist/recurrence/types.js +5 -0
  39. package/dist/schedule/civil.d.ts +26 -0
  40. package/dist/schedule/civil.js +53 -0
  41. package/dist/schedule/compile.d.ts +18 -0
  42. package/dist/schedule/compile.js +122 -0
  43. package/dist/schedule/engine.d.ts +32 -0
  44. package/dist/schedule/engine.js +97 -0
  45. package/dist/schedule/search.d.ts +9 -0
  46. package/dist/schedule/search.js +137 -0
  47. package/dist/schedule/temporal.d.ts +7 -0
  48. package/dist/schedule/temporal.js +14 -0
  49. package/dist/schedule/zone.d.ts +29 -0
  50. package/dist/schedule/zone.js +66 -0
  51. package/dist/schedule.d.ts +36 -0
  52. package/dist/schedule.js +84 -0
  53. package/dist/utils/operator-grammar.d.ts +49 -0
  54. package/dist/utils/operator-grammar.js +79 -0
  55. package/dist/utils/parse-cron-int.d.ts +1 -0
  56. package/dist/utils/parse-cron-int.js +3 -0
  57. package/package.json +69 -7
@@ -0,0 +1,15 @@
1
+ import type { Cron, Dialect, ParseOptions } from "../core/types.js";
2
+ import { type Recurrence } from "./types.js";
3
+ export { HOUR_INTERVALS, MINUTE_INTERVALS, WEEKDAYS } from "./types.js";
4
+ /** Thrown by `fromRecurrence` for invalid input or a dialect that can't express it. */
5
+ export declare class CronRecurrenceError extends Error {
6
+ name: string;
7
+ }
8
+ export declare function fromRecurrence(recurrence: Recurrence, options: {
9
+ dialect: Dialect;
10
+ }): string;
11
+ /**
12
+ * The simple recurrence an expression represents, or null when it doesn't fit
13
+ * the model (the UI should then fall back to a raw/advanced editor).
14
+ */
15
+ export declare function toRecurrence(input: string | Cron, options?: ParseOptions): Recurrence | null;
@@ -0,0 +1,222 @@
1
+ import { CANONICAL_BOUNDS } from "../constants.js";
2
+ import { format } from "../core/format.js";
3
+ import { resolveCron } from "../core/parse.js";
4
+ import { expand } from "../schedule/compile.js";
5
+ import { HOUR_INTERVALS, MINUTE_INTERVALS, WEEKDAYS, } from "./types.js";
6
+ export { HOUR_INTERVALS, MINUTE_INTERVALS, WEEKDAYS } from "./types.js";
7
+ /** Thrown by `fromRecurrence` for invalid input or a dialect that can't express it. */
8
+ export class CronRecurrenceError extends Error {
9
+ name = "CronRecurrenceError";
10
+ }
11
+ const ANY = { kind: "any" };
12
+ const NONE = { kind: "none" };
13
+ // ── Recurrence → cron ───────────────────────────────────────────────────────
14
+ export function fromRecurrence(recurrence, options) {
15
+ const { dialect } = options;
16
+ const fields = {
17
+ second: values([0]),
18
+ minute: ANY,
19
+ hour: ANY,
20
+ dayOfMonth: ANY,
21
+ month: ANY,
22
+ dayOfWeek: ANY,
23
+ year: ANY,
24
+ };
25
+ switch (recurrence.frequency) {
26
+ case "minutely":
27
+ fields.minute = every(checkInterval(recurrence.interval, MINUTE_INTERVALS, "minute"));
28
+ break;
29
+ case "hourly":
30
+ fields.minute = values([checkInteger(recurrence.minute, CANONICAL_BOUNDS.minute, "minute")]);
31
+ fields.hour = every(checkInterval(recurrence.interval, HOUR_INTERVALS, "hour"));
32
+ break;
33
+ case "daily":
34
+ setTime(fields, recurrence.at, dialect);
35
+ break;
36
+ case "weekly":
37
+ setTime(fields, recurrence.at, dialect);
38
+ fields.dayOfWeek = weekdayList(recurrence.weekdays);
39
+ break;
40
+ case "monthly":
41
+ setTime(fields, recurrence.at, dialect);
42
+ setMonthDay(fields, recurrence.on, dialect);
43
+ break;
44
+ case "yearly":
45
+ setTime(fields, recurrence.at, dialect);
46
+ setMonthDay(fields, recurrence.on, dialect);
47
+ fields.month = values(checkList(recurrence.months, CANONICAL_BOUNDS.month, "month"));
48
+ break;
49
+ default:
50
+ throw new CronRecurrenceError(`Unknown frequency '${recurrence.frequency}'`);
51
+ }
52
+ if (dialect === "quartz") {
53
+ // Quartz needs '?' in exactly one day field.
54
+ if (fields.dayOfWeek.kind !== "any")
55
+ fields.dayOfMonth = fields.dayOfMonth.kind === "any" ? NONE : fields.dayOfMonth;
56
+ else
57
+ fields.dayOfWeek = NONE;
58
+ }
59
+ return format({ dialect, source: "", fields });
60
+ }
61
+ function setTime(fields, at, dialect) {
62
+ const second = checkInteger(at.second ?? 0, CANONICAL_BOUNDS.second, "second");
63
+ if (second !== 0 && dialect === "unix")
64
+ throw new CronRecurrenceError("Unix cron has no seconds; second must be 0");
65
+ fields.second = values([second]);
66
+ fields.minute = values([checkInteger(at.minute, CANONICAL_BOUNDS.minute, "minute")]);
67
+ fields.hour = values(checkList(at.hours, CANONICAL_BOUNDS.hour, "hour"));
68
+ }
69
+ function setMonthDay(fields, on, dialect) {
70
+ if ("days" in on) {
71
+ fields.dayOfMonth = values(checkList(on.days, CANONICAL_BOUNDS.dayOfMonth, "day"));
72
+ return;
73
+ }
74
+ if (dialect === "unix") {
75
+ throw new CronRecurrenceError("Unix cron can't express the last day or the nth weekday of a month (Quartz only)");
76
+ }
77
+ if ("lastDay" in on) {
78
+ fields.dayOfMonth = { kind: "list", items: [{ kind: "lastDay", offset: 0 }] };
79
+ return;
80
+ }
81
+ const weekday = weekdayIndex(on.weekday);
82
+ if (on.nth === "last") {
83
+ fields.dayOfWeek = { kind: "list", items: [{ kind: "lastDayOfWeek", weekday }] };
84
+ }
85
+ else if ([1, 2, 3, 4, 5].includes(on.nth)) {
86
+ fields.dayOfWeek = { kind: "list", items: [{ kind: "nthDayOfWeek", weekday, nth: on.nth }] };
87
+ }
88
+ else {
89
+ throw new CronRecurrenceError(`nth must be 1-5 or "last", got ${String(on.nth)}`);
90
+ }
91
+ }
92
+ /** Weekdays as values, collapsing a contiguous run of 3+ into a range (`MON-FRI`). */
93
+ function weekdayList(weekdays) {
94
+ if (weekdays.length === 0)
95
+ throw new CronRecurrenceError("weekdays must not be empty");
96
+ const sorted = [...new Set(weekdays.map(weekdayIndex))].sort((a, b) => a - b);
97
+ const contiguous = sorted.every((day, index) => index === 0 || day === sorted[index - 1] + 1);
98
+ if (contiguous && sorted.length >= 3 && sorted.length < 7) {
99
+ return { kind: "list", items: [{ kind: "range", start: sorted[0], end: sorted.at(-1) }] };
100
+ }
101
+ return sorted.length === 7 ? ANY : values(sorted);
102
+ }
103
+ function weekdayIndex(weekday) {
104
+ const index = WEEKDAYS.indexOf(weekday);
105
+ if (index === -1)
106
+ throw new CronRecurrenceError(`Unknown weekday '${String(weekday)}'`);
107
+ return index;
108
+ }
109
+ function checkInterval(interval, allowed, unit) {
110
+ if (!allowed.includes(interval)) {
111
+ throw new CronRecurrenceError(`A ${unit} interval must be one of ${allowed.join(", ")} (got ${interval})`);
112
+ }
113
+ return interval;
114
+ }
115
+ function checkInteger(value, [min, max], unit) {
116
+ if (!Number.isInteger(value) || value < min || value > max) {
117
+ throw new CronRecurrenceError(`${unit} must be a whole number between ${min} and ${max} (got ${value})`);
118
+ }
119
+ return value;
120
+ }
121
+ function checkList(list, bounds, unit) {
122
+ if (list.length === 0)
123
+ throw new CronRecurrenceError(`${unit} list must not be empty`);
124
+ return [...new Set(list.map((value) => checkInteger(value, bounds, unit)))].sort((a, b) => a - b);
125
+ }
126
+ function every(interval) {
127
+ return interval === 1 ? ANY : { kind: "list", items: [{ kind: "step", start: "any", step: interval }] };
128
+ }
129
+ function values(list) {
130
+ return { kind: "list", items: list.map((value) => ({ kind: "value", value })) };
131
+ }
132
+ // ── cron → Recurrence ───────────────────────────────────────────────────────
133
+ /**
134
+ * The simple recurrence an expression represents, or null when it doesn't fit
135
+ * the model (the UI should then fall back to a raw/advanced editor).
136
+ */
137
+ export function toRecurrence(input, options = {}) {
138
+ const { fields } = resolveCron(input, options);
139
+ if (fields.year.kind !== "any")
140
+ return null;
141
+ const second = singleValue(fields.second);
142
+ if (second === null)
143
+ return null;
144
+ const daysOpen = isOpen(fields.dayOfMonth) && isOpen(fields.dayOfWeek);
145
+ const monthsOpen = fields.month.kind === "any";
146
+ if (second === 0 && daysOpen && monthsOpen && fields.hour.kind === "any") {
147
+ const interval = evenInterval(fields.minute, MINUTE_INTERVALS);
148
+ if (interval !== null)
149
+ return { frequency: "minutely", interval: interval };
150
+ }
151
+ const minute = singleValue(fields.minute);
152
+ if (minute === null)
153
+ return null;
154
+ if (second === 0 && daysOpen && monthsOpen) {
155
+ const interval = evenInterval(fields.hour, HOUR_INTERVALS);
156
+ if (interval !== null) {
157
+ return { frequency: "hourly", interval: interval, minute };
158
+ }
159
+ }
160
+ const hours = plainValues(fields.hour, CANONICAL_BOUNDS.hour);
161
+ if (hours === null)
162
+ return null;
163
+ const at = second === 0 ? { hours, minute } : { hours, minute, second };
164
+ if (daysOpen)
165
+ return monthsOpen ? { frequency: "daily", at } : null;
166
+ if (isOpen(fields.dayOfMonth)) {
167
+ const weekdays = plainValues(fields.dayOfWeek, CANONICAL_BOUNDS.dayOfWeek);
168
+ if (weekdays !== null) {
169
+ return monthsOpen ? { frequency: "weekly", weekdays: weekdays.map((day) => WEEKDAYS[day]), at } : null;
170
+ }
171
+ }
172
+ const on = monthDayOf(fields.dayOfMonth, fields.dayOfWeek);
173
+ if (on === null)
174
+ return null;
175
+ if (monthsOpen)
176
+ return { frequency: "monthly", on, at };
177
+ const months = plainValues(fields.month, CANONICAL_BOUNDS.month);
178
+ return months === null ? null : { frequency: "yearly", months: months, on, at };
179
+ }
180
+ function monthDayOf(dayOfMonth, dayOfWeek) {
181
+ if (isOpen(dayOfWeek)) {
182
+ const [item] = dayOfMonth.kind === "list" ? dayOfMonth.items : [];
183
+ if (item?.kind === "lastDay" && item.offset === 0)
184
+ return { lastDay: true };
185
+ const days = plainValues(dayOfMonth, CANONICAL_BOUNDS.dayOfMonth);
186
+ return days === null ? null : { days };
187
+ }
188
+ if (isOpen(dayOfMonth) && dayOfWeek.kind === "list" && dayOfWeek.items.length === 1) {
189
+ const [item] = dayOfWeek.items;
190
+ if (item.kind === "nthDayOfWeek")
191
+ return { nth: item.nth, weekday: WEEKDAYS[item.weekday] };
192
+ if (item.kind === "lastDayOfWeek")
193
+ return { nth: "last", weekday: WEEKDAYS[item.weekday] };
194
+ }
195
+ return null;
196
+ }
197
+ /** `*` or `?`: the field doesn't restrict anything. */
198
+ function isOpen(expr) {
199
+ return expr.kind === "any" || expr.kind === "none";
200
+ }
201
+ function singleValue(expr) {
202
+ return expr.kind === "list" && expr.items.length === 1 && expr.items[0].kind === "value" ? expr.items[0].value : null;
203
+ }
204
+ /** `*` → 1, `*\/n` or `0/n` → n, when n is an interval cron repeats evenly. */
205
+ function evenInterval(expr, allowed) {
206
+ if (expr.kind === "any")
207
+ return 1;
208
+ if (expr.kind !== "list" || expr.items.length !== 1)
209
+ return null;
210
+ const [item] = expr.items;
211
+ const startsAtZero = item.kind === "step" && (item.start === "any" || item.start === 0);
212
+ return startsAtZero && allowed.includes(item.step) ? item.step : null;
213
+ }
214
+ /** Explicit values of a value/range/step list; null for `*`, `?` or special items. */
215
+ function plainValues(expr, bounds) {
216
+ if (expr.kind !== "list" || expr.items.some(isSpecial))
217
+ return null;
218
+ return expand(expr, bounds);
219
+ }
220
+ function isSpecial(item) {
221
+ return item.kind !== "value" && item.kind !== "range" && item.kind !== "step";
222
+ }
@@ -0,0 +1,56 @@
1
+ export declare const WEEKDAYS: readonly ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
2
+ export type Weekday = (typeof WEEKDAYS)[number];
3
+ /** Minute intervals cron repeats evenly (divisors of 60): `*\/7` would jump :56 → :00. */
4
+ export declare const MINUTE_INTERVALS: readonly [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30];
5
+ export type MinuteInterval = (typeof MINUTE_INTERVALS)[number];
6
+ /** Hour intervals cron repeats evenly (divisors of 24). */
7
+ export declare const HOUR_INTERVALS: readonly [1, 2, 3, 4, 6, 8, 12];
8
+ export type HourInterval = (typeof HOUR_INTERVALS)[number];
9
+ export type Month = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12;
10
+ /**
11
+ * Times of day as cron expresses them: every listed hour at the same minute
12
+ * (cron fields are a cartesian product, so "09:00 and 17:30" isn't one cron).
13
+ */
14
+ export interface TimeOfDay {
15
+ hours: number[];
16
+ minute: number;
17
+ /** Quartz only; omitted means 0. */
18
+ second?: number;
19
+ }
20
+ export type MonthDay = {
21
+ days: number[];
22
+ }
23
+ /** Quartz only (`L`). */
24
+ | {
25
+ lastDay: true;
26
+ }
27
+ /** Quartz only (`FRI#3`, or `FRIL` for "last"). */
28
+ | {
29
+ nth: 1 | 2 | 3 | 4 | 5 | "last";
30
+ weekday: Weekday;
31
+ };
32
+ /** The simple schedules a recurring-task UI offers, each mapping to exactly one cron. */
33
+ export type Recurrence = {
34
+ frequency: "minutely";
35
+ interval: MinuteInterval;
36
+ } | {
37
+ frequency: "hourly";
38
+ interval: HourInterval;
39
+ minute: number;
40
+ } | {
41
+ frequency: "daily";
42
+ at: TimeOfDay;
43
+ } | {
44
+ frequency: "weekly";
45
+ weekdays: Weekday[];
46
+ at: TimeOfDay;
47
+ } | {
48
+ frequency: "monthly";
49
+ on: MonthDay;
50
+ at: TimeOfDay;
51
+ } | {
52
+ frequency: "yearly";
53
+ months: Month[];
54
+ on: MonthDay;
55
+ at: TimeOfDay;
56
+ };
@@ -0,0 +1,5 @@
1
+ export const WEEKDAYS = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
2
+ /** Minute intervals cron repeats evenly (divisors of 60): `*\/7` would jump :56 → :00. */
3
+ export const MINUTE_INTERVALS = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30];
4
+ /** Hour intervals cron repeats evenly (divisors of 24). */
5
+ export const HOUR_INTERVALS = [1, 2, 3, 4, 6, 8, 12];
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Proleptic Gregorian calendar math on plain numbers. The scheduler searches
3
+ * wall-clock time in "wall seconds" (seconds since 1970-01-01T00:00 as if the
4
+ * zone were UTC) and only asks Temporal for UTC offsets and transitions.
5
+ * Algorithms: Howard Hinnant, "chrono-Compatible Low-Level Date Algorithms".
6
+ */
7
+ export interface WallTime {
8
+ year: number;
9
+ month: number;
10
+ day: number;
11
+ hour: number;
12
+ minute: number;
13
+ second: number;
14
+ }
15
+ export declare function daysFromCivil(year: number, month: number, day: number): number;
16
+ export declare function civilFromDays(days: number): {
17
+ year: number;
18
+ month: number;
19
+ day: number;
20
+ };
21
+ export declare function isLeapYear(year: number): boolean;
22
+ export declare function daysInMonth(year: number, month: number): number;
23
+ /** 0 = Sunday … 6 = Saturday. 1970-01-01 was a Thursday. */
24
+ export declare function weekdayOf(days: number): number;
25
+ export declare function toWallSeconds(wall: WallTime): number;
26
+ export declare function fromWallSeconds(seconds: number): WallTime;
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Proleptic Gregorian calendar math on plain numbers. The scheduler searches
3
+ * wall-clock time in "wall seconds" (seconds since 1970-01-01T00:00 as if the
4
+ * zone were UTC) and only asks Temporal for UTC offsets and transitions.
5
+ * Algorithms: Howard Hinnant, "chrono-Compatible Low-Level Date Algorithms".
6
+ */
7
+ const SECONDS_PER_DAY = 86_400;
8
+ export function daysFromCivil(year, month, day) {
9
+ const y = month <= 2 ? year - 1 : year;
10
+ const era = Math.floor(y / 400);
11
+ const yearOfEra = y - era * 400;
12
+ const shiftedMonth = (month + 9) % 12; // March = 0
13
+ const dayOfYear = Math.floor((153 * shiftedMonth + 2) / 5) + day - 1;
14
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
15
+ return era * 146_097 + dayOfEra - 719_468;
16
+ }
17
+ export function civilFromDays(days) {
18
+ const z = days + 719_468;
19
+ const era = Math.floor(z / 146_097);
20
+ const dayOfEra = z - era * 146_097;
21
+ const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36_524) - Math.floor(dayOfEra / 146_096)) / 365);
22
+ const dayOfYear = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
23
+ const shiftedMonth = Math.floor((5 * dayOfYear + 2) / 153);
24
+ const day = dayOfYear - Math.floor((153 * shiftedMonth + 2) / 5) + 1;
25
+ const month = shiftedMonth < 10 ? shiftedMonth + 3 : shiftedMonth - 9;
26
+ const year = yearOfEra + era * 400 + (month <= 2 ? 1 : 0);
27
+ return { year, month, day };
28
+ }
29
+ export function isLeapYear(year) {
30
+ return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
31
+ }
32
+ const MONTH_LENGTHS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
33
+ export function daysInMonth(year, month) {
34
+ return month === 2 && isLeapYear(year) ? 29 : MONTH_LENGTHS[month - 1];
35
+ }
36
+ /** 0 = Sunday … 6 = Saturday. 1970-01-01 was a Thursday. */
37
+ export function weekdayOf(days) {
38
+ return (((days + 4) % 7) + 7) % 7;
39
+ }
40
+ export function toWallSeconds(wall) {
41
+ return (daysFromCivil(wall.year, wall.month, wall.day) * SECONDS_PER_DAY +
42
+ wall.hour * 3600 +
43
+ wall.minute * 60 +
44
+ wall.second);
45
+ }
46
+ export function fromWallSeconds(seconds) {
47
+ const days = Math.floor(seconds / SECONDS_PER_DAY);
48
+ let rest = seconds - days * SECONDS_PER_DAY;
49
+ const hour = Math.floor(rest / 3600);
50
+ rest -= hour * 3600;
51
+ const minute = Math.floor(rest / 60);
52
+ return { ...civilFromDays(days), hour, minute, second: rest - minute * 60 };
53
+ }
@@ -0,0 +1,18 @@
1
+ import type { Cron, FieldExpr } from "../core/types.js";
2
+ export interface CompiledCron {
3
+ dialect: Cron["dialect"];
4
+ seconds: number[];
5
+ minutes: number[];
6
+ hours: number[];
7
+ months: number[];
8
+ /** Explicit allowed years, or null when any year in `yearBounds` matches. */
9
+ years: number[] | null;
10
+ yearBounds: readonly [number, number];
11
+ /** Sorted days of the given month that match both day fields. */
12
+ daysOf: (year: number, month: number) => number[];
13
+ /** Unix (cronie) "wildcard job": minute or hour starts with `*`. Drives DST defaults. */
14
+ isWildcardJob: boolean;
15
+ }
16
+ export declare function compile(cron: Cron): CompiledCron;
17
+ /** Sorted unique values of a value/range/step field within [min, max]. */
18
+ export declare function expand(expr: FieldExpr, [min, max]: readonly [number, number]): number[];
@@ -0,0 +1,122 @@
1
+ import { CANONICAL_BOUNDS } from "../constants.js";
2
+ import { startsWithWildcard } from "../core/ast.js";
3
+ import { daysFromCivil, daysInMonth, weekdayOf } from "./civil.js";
4
+ const UNBOUNDED_YEARS = [Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY];
5
+ export function compile(cron) {
6
+ const { fields } = cron;
7
+ const yearBounds = cron.dialect === "quartz" ? CANONICAL_BOUNDS.year : UNBOUNDED_YEARS;
8
+ return {
9
+ dialect: cron.dialect,
10
+ seconds: expand(fields.second, CANONICAL_BOUNDS.second),
11
+ minutes: expand(fields.minute, CANONICAL_BOUNDS.minute),
12
+ hours: expand(fields.hour, CANONICAL_BOUNDS.hour),
13
+ months: expand(fields.month, CANONICAL_BOUNDS.month),
14
+ years: fields.year.kind === "any" ? null : expand(fields.year, CANONICAL_BOUNDS.year),
15
+ yearBounds,
16
+ daysOf: memoizeLast(createDayMatcher(cron)),
17
+ isWildcardJob: startsWithWildcard(fields.minute) || startsWithWildcard(fields.hour),
18
+ };
19
+ }
20
+ /** Sorted unique values of a value/range/step field within [min, max]. */
21
+ export function expand(expr, [min, max]) {
22
+ if (expr.kind !== "list")
23
+ return range(min, max, 1);
24
+ const values = new Set();
25
+ for (const item of expr.items) {
26
+ for (const value of expandItem(item, min, max))
27
+ values.add(value);
28
+ }
29
+ return [...values].sort((a, b) => a - b);
30
+ }
31
+ function expandItem(item, min, max) {
32
+ switch (item.kind) {
33
+ case "value":
34
+ return item.value >= min && item.value <= max ? [item.value] : [];
35
+ case "range":
36
+ return range(item.start, Math.min(item.end, max), item.step ?? 1);
37
+ case "step":
38
+ return range(item.start === "any" ? min : item.start, max, item.step);
39
+ default:
40
+ return [];
41
+ }
42
+ }
43
+ function range(start, end, step) {
44
+ const values = [];
45
+ for (let value = start; value <= end; value += step)
46
+ values.push(value);
47
+ return values;
48
+ }
49
+ function createDayMatcher(cron) {
50
+ const { dayOfMonth, dayOfWeek } = cron.fields;
51
+ const weekdays = expand(dayOfWeek, CANONICAL_BOUNDS.dayOfWeek);
52
+ const unixAnd = startsWithWildcard(dayOfMonth) || startsWithWildcard(dayOfWeek);
53
+ return (year, month) => {
54
+ const length = daysInMonth(year, month);
55
+ const firstWeekday = weekdayOf(daysFromCivil(year, month, 1));
56
+ const weekdayOfDay = (day) => (firstWeekday + day - 1) % 7;
57
+ const all = range(1, length, 1);
58
+ const domDays = dayOfMonth.kind === "list" ? dayOfMonthDays(dayOfMonth.items, length, weekdayOfDay) : all;
59
+ const dowDays = dayOfWeek.kind === "list" ? dayOfWeekDays(dayOfWeek.items, weekdays, length, firstWeekday, weekdayOfDay) : all;
60
+ if (cron.dialect === "quartz") {
61
+ return dayOfMonth.kind === "none" ? dowDays : domDays;
62
+ }
63
+ if (unixAnd)
64
+ return domDays.filter((day) => dowDays.includes(day));
65
+ return [...new Set([...domDays, ...dowDays])].sort((a, b) => a - b);
66
+ };
67
+ }
68
+ function dayOfMonthDays(items, length, weekdayOfDay) {
69
+ const days = new Set();
70
+ for (const item of items) {
71
+ switch (item.kind) {
72
+ case "lastDay":
73
+ if (length - item.offset >= 1)
74
+ days.add(length - item.offset);
75
+ break;
76
+ case "lastWeekday":
77
+ days.add(nearestWeekday(length, length, weekdayOfDay));
78
+ break;
79
+ case "nearestWeekday":
80
+ if (item.day <= length)
81
+ days.add(nearestWeekday(item.day, length, weekdayOfDay));
82
+ break;
83
+ default:
84
+ for (const day of expandItem(item, 1, length))
85
+ days.add(day);
86
+ }
87
+ }
88
+ return [...days].sort((a, b) => a - b);
89
+ }
90
+ /** Quartz `W`: Saturday → Friday, Sunday → Monday, never crossing the month boundary. */
91
+ function nearestWeekday(day, length, weekdayOfDay) {
92
+ const weekday = weekdayOfDay(day);
93
+ if (weekday === 6)
94
+ return day === 1 ? day + 2 : day - 1;
95
+ if (weekday === 0)
96
+ return day === length ? day - 2 : day + 1;
97
+ return day;
98
+ }
99
+ function dayOfWeekDays(items, weekdays, length, firstWeekday, weekdayOfDay) {
100
+ const special = items.find((item) => item.kind === "lastDayOfWeek" || item.kind === "nthDayOfWeek");
101
+ if (special?.kind === "nthDayOfWeek") {
102
+ const first = 1 + ((special.weekday - firstWeekday + 7) % 7);
103
+ const day = first + 7 * (special.nth - 1);
104
+ return day <= length ? [day] : [];
105
+ }
106
+ if (special?.kind === "lastDayOfWeek") {
107
+ return [length - ((weekdayOfDay(length) - special.weekday + 7) % 7)];
108
+ }
109
+ return range(1, length, 1).filter((day) => weekdays.includes(weekdayOfDay(day)));
110
+ }
111
+ function memoizeLast(fn) {
112
+ let lastKey = Number.NaN;
113
+ let lastValue = [];
114
+ return (year, month) => {
115
+ const key = year * 16 + month;
116
+ if (key !== lastKey) {
117
+ lastKey = key;
118
+ lastValue = fn(year, month);
119
+ }
120
+ return lastValue;
121
+ };
122
+ }
@@ -0,0 +1,32 @@
1
+ import type { CompiledCron } from "./compile.js";
2
+ import { type Segment, type Zone } from "./zone.js";
3
+ export interface DstPolicy {
4
+ /**
5
+ * Wall times skipped by a forward jump (spring forward):
6
+ * - `later`: shift forward by the gap length (02:30 → 03:30), like Quartz / Java Calendar.
7
+ * - `transition`: run once at the transition instant (≈03:00), like cronie fixed-time jobs.
8
+ * - `skip`: don't run, like cronie wildcard jobs.
9
+ */
10
+ gap: "later" | "transition" | "skip";
11
+ /**
12
+ * Wall times repeated by a backward jump (fall back):
13
+ * - `first`: run once, at the earlier offset (Quartz; cronie fixed-time jobs).
14
+ * - `all`: run in both passes (cronie wildcard jobs).
15
+ */
16
+ overlap: "first" | "all";
17
+ }
18
+ /** Mirrors the scheduler that actually runs each dialect. */
19
+ export declare function defaultDstPolicy(compiled: CompiledCron): DstPolicy;
20
+ export interface Context {
21
+ compiled: CompiledCron;
22
+ zone: Zone;
23
+ policy: DstPolicy;
24
+ }
25
+ export interface Found {
26
+ instant: number;
27
+ segment: Segment;
28
+ }
29
+ /** Earliest run instant strictly after `cursor` (epoch seconds). */
30
+ export declare function nextInstant(context: Context, cursor: number, hint?: Segment): Found | null;
31
+ /** Latest run instant at or before `upper` (epoch seconds). */
32
+ export declare function previousInstant(context: Context, upper: number, hint?: Segment): Found | null;
@@ -0,0 +1,97 @@
1
+ import { fromWallSeconds } from "./civil.js";
2
+ import { nextWallMatch, previousWallMatch } from "./search.js";
3
+ import { contains } from "./zone.js";
4
+ /** Mirrors the scheduler that actually runs each dialect. */
5
+ export function defaultDstPolicy(compiled) {
6
+ if (compiled.dialect === "quartz")
7
+ return { gap: "later", overlap: "first" };
8
+ return compiled.isWildcardJob ? { gap: "skip", overlap: "all" } : { gap: "transition", overlap: "first" };
9
+ }
10
+ /** Upper bound on how far a search looks; covers the full 400-year Gregorian cycle. */
11
+ const HORIZON_YEARS = 400;
12
+ function gapAt(segment) {
13
+ const { start, previousOffset, offset } = segment;
14
+ if (start === null || previousOffset === null || offset <= previousOffset)
15
+ return null;
16
+ return { wallStart: start + previousOffset, wallEnd: start + offset, offsetBefore: previousOffset };
17
+ }
18
+ /** Wall time where regular (non-gap) runs of the segment begin. */
19
+ function regularWallStart(segment, policy) {
20
+ if (segment.start === null)
21
+ return Number.NEGATIVE_INFINITY;
22
+ const repeatsWallTime = segment.previousOffset !== null && segment.previousOffset > segment.offset;
23
+ if (repeatsWallTime && policy.overlap === "first")
24
+ return segment.start + segment.previousOffset;
25
+ return segment.start + segment.offset;
26
+ }
27
+ /** Earliest run instant strictly after `cursor` (epoch seconds). */
28
+ export function nextInstant(context, cursor, hint) {
29
+ const { compiled, zone, policy } = context;
30
+ const maxYear = fromWallSeconds(cursor).year + HORIZON_YEARS;
31
+ let segment = hint && contains(hint, cursor) ? hint : zone.segmentAt(cursor);
32
+ for (;;) {
33
+ let best = null;
34
+ const consider = (instant) => {
35
+ if (instant > cursor && (best === null || instant < best))
36
+ best = instant;
37
+ };
38
+ const gap = gapAt(segment);
39
+ if (gap && policy.gap === "later") {
40
+ const from = Math.max(gap.wallStart, cursor + gap.offsetBefore + 1);
41
+ const wall = nextWallMatch(compiled, from, maxYear);
42
+ if (wall !== null && wall < gap.wallEnd)
43
+ consider(wall - gap.offsetBefore);
44
+ }
45
+ else if (gap && policy.gap === "transition") {
46
+ const wall = nextWallMatch(compiled, gap.wallStart, maxYear);
47
+ if (wall !== null && wall < gap.wallEnd)
48
+ consider(segment.start);
49
+ }
50
+ const from = Math.max(cursor + segment.offset + 1, regularWallStart(segment, policy));
51
+ const wall = nextWallMatch(compiled, from, maxYear);
52
+ if (wall !== null && (segment.end === null || wall < segment.end + segment.offset)) {
53
+ consider(wall - segment.offset);
54
+ }
55
+ if (best !== null)
56
+ return { instant: best, segment };
57
+ if (wall === null || segment.end === null)
58
+ return null;
59
+ segment = zone.next(segment);
60
+ }
61
+ }
62
+ /** Latest run instant at or before `upper` (epoch seconds). */
63
+ export function previousInstant(context, upper, hint) {
64
+ const { compiled, zone, policy } = context;
65
+ const minYear = fromWallSeconds(upper).year - HORIZON_YEARS;
66
+ let segment = hint && contains(hint, upper) ? hint : zone.segmentAt(upper);
67
+ for (;;) {
68
+ let best = null;
69
+ const consider = (instant) => {
70
+ if (instant <= upper && (best === null || instant > best))
71
+ best = instant;
72
+ };
73
+ let to = upper + segment.offset;
74
+ if (segment.end !== null)
75
+ to = Math.min(to, segment.end + segment.offset - 1);
76
+ const wall = previousWallMatch(compiled, to, minYear);
77
+ if (wall !== null && wall >= regularWallStart(segment, policy))
78
+ consider(wall - segment.offset);
79
+ const gap = gapAt(segment);
80
+ if (gap && policy.gap === "later") {
81
+ const gapTo = Math.min(gap.wallEnd - 1, upper + gap.offsetBefore);
82
+ const gapWall = previousWallMatch(compiled, gapTo, minYear);
83
+ if (gapWall !== null && gapWall >= gap.wallStart)
84
+ consider(gapWall - gap.offsetBefore);
85
+ }
86
+ else if (gap && policy.gap === "transition") {
87
+ const gapWall = previousWallMatch(compiled, gap.wallEnd - 1, minYear);
88
+ if (gapWall !== null && gapWall >= gap.wallStart)
89
+ consider(segment.start);
90
+ }
91
+ if (best !== null)
92
+ return { instant: best, segment };
93
+ if (wall === null || segment.start === null)
94
+ return null;
95
+ segment = zone.previous(segment);
96
+ }
97
+ }
@@ -0,0 +1,9 @@
1
+ import type { CompiledCron } from "./compile.js";
2
+ /**
3
+ * First matching wall second ≥ `start`, or null if none before the end of
4
+ * `maxYear`. Field-by-field: a mismatch bumps that field to its next allowed
5
+ * value (resetting smaller fields) or carries into the next larger field.
6
+ */
7
+ export declare function nextWallMatch(compiled: CompiledCron, start: number, maxYear: number): number | null;
8
+ /** Last matching wall second ≤ `start`, or null if none since the start of `minYear`. */
9
+ export declare function previousWallMatch(compiled: CompiledCron, start: number, minYear: number): number | null;