cron-toolkit 0.0.0-stage → 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 +244 -2
  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 +73 -4
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2026, Kev Aldasoro
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,245 @@
1
- # Temporary Holding Version
1
+ # cron-toolkit
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm version](https://img.shields.io/npm/v/cron-toolkit.svg)](https://www.npmjs.com/package/cron-toolkit)
4
+ [![Test](https://github.com/andrewaldasoro/cron-toolkit/actions/workflows/test.yml/badge.svg)](https://github.com/andrewaldasoro/cron-toolkit/actions/workflows/test.yml)
5
+ [![license](https://img.shields.io/npm/l/cron-toolkit.svg)](./LICENSE)
6
+
7
+ A small cron toolkit in TypeScript: **parse, validate, format, convert, describe** (English, Spanish, French) and **compute next / previous runs in any time zone**, with DST handling that matches the scheduler that will actually run the job.
8
+
9
+ - **Quartz** (6–7 fields, seconds first, `?` `L` `W` `#`) and **Unix** crontab (5 fields, `@daily` …) dialects
10
+ - **Zero runtime dependencies**: built on `Temporal` and `Intl`
11
+ - ESM-only, fully typed, tree-shakeable subpath exports
12
+
13
+ > Formerly [`cron-quartz-validator`](https://www.npmjs.com/package/cron-quartz-validator). See [Migrating](#migrating-from-cron-quartz-validator).
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ npm install cron-toolkit
19
+ ```
20
+
21
+ | Import | What | Needs `Temporal` |
22
+ | --- | --- | --- |
23
+ | `cron-toolkit` | `parse`, `validate`, `isValid`, `format`, `convert`, `fromRecurrence`, `toRecurrence` | no |
24
+ | `cron-toolkit/describe` | `describe`, `formatError` | no |
25
+ | `cron-toolkit/locales/en` · `/es` · `/fr` | locale packs for `describe` / `formatError` | no |
26
+ | `cron-toolkit/schedule` | `nextRun`, `nextRuns`, `previousRun`, `runs`, `matches` | **yes** |
27
+
28
+ `Temporal` is built into Node 26+, Chrome/Edge 144+ and Firefox 139+. **Safari** and Node ≤ 24 need a polyfill, loaded once before you use `cron-toolkit/schedule`:
29
+
30
+ ```ts
31
+ import "temporal-polyfill/global";
32
+ ```
33
+
34
+ Without it, `cron-toolkit/schedule` throws a `TemporalUnavailableError`. Everything else works anywhere.
35
+
36
+ ## Validate & parse
37
+
38
+ ```ts
39
+ import { validate, isValid, parse } from "cron-toolkit";
40
+
41
+ isValid("0 0 12 * * ?"); // true (Quartz)
42
+ isValid("*/5 * * * *"); // true (Unix)
43
+
44
+ validate("60 0 99 * * ?");
45
+ // {
46
+ // valid: false,
47
+ // errors: [
48
+ // { code: "INVALID_VALUE", field: "second", params: { token: "60", min: 0, max: 59 }, message: "Seconds must be between 0 and 59" },
49
+ // { code: "INVALID_VALUE", field: "hour", params: { token: "99", min: 0, max: 23 }, message: "Hours must be between 0 and 23" },
50
+ // ],
51
+ // }
52
+
53
+ const result = parse("0 15 10 ? * MON-FRI");
54
+ if (result.success) result.cron; // { dialect: "quartz", source, fields: { second, minute, … } }
55
+ ```
56
+
57
+ The dialect is detected from the field count (`@macro` or 5 fields → Unix, 6–7 → Quartz). Pass `{ dialect: "quartz" | "unix" }` to require one. Every function that takes an expression also accepts an already-parsed `Cron`.
58
+
59
+ Errors carry a stable `code`, the `field` and `params`, so a UI can highlight the field and show its own text. See [Error codes](#error-codes).
60
+
61
+ ## Describe
62
+
63
+ ```ts
64
+ import { describe, formatError } from "cron-toolkit/describe";
65
+ import { es } from "cron-toolkit/locales/es";
66
+ import { fr } from "cron-toolkit/locales/fr";
67
+
68
+ describe("*/15 9-17 * * MON-FRI");
69
+ // "Every 15 minutes, between 9:00 AM and 5:59 PM, Monday through Friday"
70
+ describe("*/15 9-17 * * MON-FRI", { locale: es });
71
+ // "Cada 15 minutos, entre las 09:00 y las 17:59, de lunes a viernes"
72
+ describe("0 0 12 ? * 6#3", { locale: fr });
73
+ // "À 12:00, le troisième vendredi du mois"
74
+ describe("0 30 9 * * ?", { hourCycle: "h23" });
75
+ // "At 09:30"
76
+
77
+ formatError(validate("60 0 0 * * ?").errors[0], { locale: es });
78
+ // "Segundos: el valor debe estar entre 0 y 59"
79
+ ```
80
+
81
+ Day and month names, times and lists come from `Intl`, so they follow each language's conventions. The default `hourCycle` is the locale's own (`en` 12-hour, `es`/`fr` 24-hour). To add a language, implement the `Locale` interface (see `src/locales/en.ts`).
82
+
83
+ ## Next runs & time zones
84
+
85
+ ```ts
86
+ import "temporal-polyfill/global"; // only where Temporal isn't native
87
+ import { nextRun, nextRuns, previousRun, runs, matches } from "cron-toolkit/schedule";
88
+
89
+ nextRuns("0 30 9 ? * MON-FRI", { count: 3, timeZone: "Europe/Madrid" });
90
+ // [Temporal.ZonedDateTime, …] strictly after now
91
+
92
+ const from = Temporal.ZonedDateTime.from("2026-03-07T12:00:00-05:00[America/New_York]");
93
+ nextRun("0 30 2 * * ?", { from }); // 2026-03-08T03:30-04:00 (Quartz: 02:30 doesn't exist that day)
94
+ nextRun("30 2 * * *", { from }); // 2026-03-08T03:00-04:00 (cronie runs it right after the jump)
95
+
96
+ previousRun("0 0 * * *", { timeZone: "Asia/Kathmandu" });
97
+
98
+ for (const run of runs("@hourly", { from })) {
99
+ // lazy, unbounded iterator; break when you have enough
100
+ }
101
+
102
+ matches("0 30 9 ? * MON-FRI", Temporal.PlainDateTime.from("2026-11-23T09:30"));
103
+ // true (wall-clock field check only)
104
+ ```
105
+
106
+ - `from`: `Temporal.Instant` or `Temporal.ZonedDateTime`, exclusive. Defaults to now.
107
+ - `timeZone`: any IANA zone. Defaults to `from`'s zone, or the system zone.
108
+ - Returns `null` / ends the iterator when no run exists (`30 FEB`, an exhausted Quartz year list). Searches never loop forever.
109
+
110
+ ### Daylight-saving time
111
+
112
+ By default, runs around DST transitions match the scheduler that executes each dialect:
113
+
114
+ | | Skipped time (spring forward), e.g. 02:30 | Repeated time (fall back), e.g. 01:30 |
115
+ | --- | --- | --- |
116
+ | **Quartz** | shifted by the gap → 03:30 | once, first occurrence |
117
+ | **Unix, fixed-time job** (minute and hour don't start with `*`) | once, at the transition → 03:00 | once, first occurrence |
118
+ | **Unix, wildcard job** (`*/15 * * * *`, `0 * * * *`) | skipped | both occurrences |
119
+
120
+ Override with `dst: { gap: "later" | "transition" | "skip", overlap: "first" | "all" }`.
121
+
122
+ `matches()` only checks wall-clock fields and ignores DST policy. Use `runs()` to know when a job actually fires.
123
+
124
+ ## Recurrence model (for UIs)
125
+
126
+ `fromRecurrence` / `toRecurrence` map simple form inputs to cron and back. `toRecurrence` returns `null` when an expression doesn't fit the model, so the UI can fall back to a raw editor.
127
+
128
+ ```ts
129
+ import { fromRecurrence, toRecurrence, MINUTE_INTERVALS, HOUR_INTERVALS, WEEKDAYS } from "cron-toolkit";
130
+
131
+ fromRecurrence(
132
+ { frequency: "weekly", weekdays: ["MON", "TUE", "WED", "THU", "FRI"], at: { hours: [9], minute: 0 } },
133
+ { dialect: "quartz" }
134
+ ); // "0 0 9 ? * MON-FRI"
135
+
136
+ fromRecurrence({ frequency: "monthly", on: { nth: 3, weekday: "FRI" }, at: { hours: [12], minute: 0 } }, { dialect: "quartz" });
137
+ // "0 0 12 ? * 6#3"
138
+
139
+ toRecurrence("30 */6 * * *"); // { frequency: "hourly", interval: 6, minute: 30 }
140
+ toRecurrence("0 0 1 * MON"); // null (Unix day-of-month OR day-of-week)
141
+ ```
142
+
143
+ | `frequency` | Fields |
144
+ | --- | --- |
145
+ | `minutely` | `interval`: one of `MINUTE_INTERVALS` (divisors of 60) |
146
+ | `hourly` | `interval`: one of `HOUR_INTERVALS` (divisors of 24), `minute` |
147
+ | `daily` | `at` |
148
+ | `weekly` | `weekdays` (`"SUN"`…`"SAT"`), `at` |
149
+ | `monthly` | `on`, `at` |
150
+ | `yearly` | `months` (1–12), `on`, `at` |
151
+
152
+ - `at` is `{ hours: number[]; minute; second? }`. Cron fields combine as a cartesian product, so "09:00 and 17:30" can't be one expression and isn't representable.
153
+ - `on` is `{ days: number[] }`, `{ lastDay: true }` or `{ nth: 1–5 | "last", weekday }`. The last two are Quartz-only.
154
+ - Intervals are limited to values cron repeats evenly: `*/7` minutes would jump from :56 to :00.
155
+
156
+ Invalid input, or a dialect that can't express the recurrence, throws `CronRecurrenceError`.
157
+
158
+ ## Format & convert
159
+
160
+ ```ts
161
+ import { format, convert } from "cron-toolkit";
162
+
163
+ format("0 15 10 ? * mon-fri"); // "0 15 10 ? * MON-FRI" (weekdays as names, so 0- vs 1-based numbering can't be confused)
164
+ convert("0 30 9 ? * MON-FRI", { to: "unix" }); // "30 9 * * MON-FRI"
165
+ convert("*/5 * * * *", { to: "quartz" }); // "0 */5 * * * ?"
166
+ convert("0 0 0 L * ?", { to: "unix" }); // throws CronConvertError: Unix cron does not support 'L' in day-of-month
167
+ ```
168
+
169
+ ## Accepted syntax
170
+
171
+ **Quartz** (matches real Quartz):
172
+
173
+ Seconds 0-59 * , - /
174
+ Minutes 0-59 * , - /
175
+ Hours 0-23 * , - /
176
+ Day of month 1-31 * , - / ? L L-n nW LW
177
+ Month 1-12 or JAN-DEC * , - /
178
+ Day of week 1-7 or SUN-SAT (1=SUN) * , - / ? L (=SAT) nL n#k
179
+ Year 1970-2199 (optional) * , - /
180
+
181
+ - Exactly one of day-of-month / day-of-week must be `?`.
182
+ - `10/5` means 10, 15, …, 55.
183
+ - `L`, `W`, `#` can't be combined with other values in a list.
184
+ - Wrap-around ranges (`FRI-MON`, `22-2`) are rejected.
185
+
186
+ **Unix** (cronie-compatible):
187
+
188
+ Minute 0-59 * , - /
189
+ Hour 0-23 * , - /
190
+ Day of month 1-31 * , - /
191
+ Month 1-12 or JAN-DEC * , - /
192
+ Day of week 0-7 or SUN-SAT (0 and 7 = SUN) * , - /
193
+ Macros @yearly @annually @monthly @weekly @daily @midnight @hourly
194
+
195
+ - When both day fields are restricted, a run happens on either: `0 0 1 * MON` = the 1st **or** Mondays.
196
+ - If either day field starts with `*` (e.g. `*/2`), both must match.
197
+ - `@reboot` is rejected: it has no schedule.
198
+
199
+ ## Error codes
200
+
201
+ | Code | When |
202
+ | --- | --- |
203
+ | `EMPTY_EXPRESSION` | blank input |
204
+ | `WRONG_FIELD_COUNT` | not 5 (Unix) or 6–7 (Quartz) fields |
205
+ | `UNKNOWN_MACRO` / `UNSUPPORTED_MACRO` | `@often` / `@reboot` |
206
+ | `INVALID_VALUE` | out of range or unknown name |
207
+ | `INVALID_RANGE` | `start > end`, malformed range |
208
+ | `INVALID_STEP` | `/0`, increment too large, named step start in Quartz |
209
+ | `UNSUPPORTED_SYNTAX` | e.g. `?`, `L`, `W`, `#` in Unix |
210
+ | `INVALID_NTH` | `#` occurrence outside 1–5 |
211
+ | `SPECIAL_NOT_COMBINABLE` | `L`/`W`/`#` inside a list |
212
+ | `DAY_FIELDS_BOTH_SET` / `DAY_FIELDS_BOTH_UNSET` | Quartz `?` rule |
213
+
214
+ ## Migrating from `cron-quartz-validator`
215
+
216
+ | Before | After |
217
+ | --- | --- |
218
+ | `validateCronExpression(expr)` | `validate(expr, { dialect: "quartz" })`. Errors are now objects with `code`, `field`, `params`, `message`. |
219
+ | `isValidCronExpression(expr)` | `isValid(expr, { dialect: "quartz" })` |
220
+
221
+ Validation now matches real Quartz:
222
+
223
+ - **Rejected now:** `0 0 12 * * MON` (needs `?`), `3L` in day-of-month, `0L`, `#0`.
224
+ - **Accepted now:** `10/5`, `MON#2`, `15W`, `L-3`.
225
+
226
+ ## Development
227
+
228
+ ```bash
229
+ pnpm i
230
+ pnpm typecheck # tsc --noEmit
231
+ pnpm lint # oxlint .
232
+ pnpm test # vitest run (loads temporal-polyfill when Temporal isn't native)
233
+ pnpm build # tsc -p tsconfig.build.json -> dist/
234
+ ```
235
+
236
+ CI (`.github/workflows/test.yml`) runs typecheck, lint, tests and build on Node 24 (polyfill) and Node 26 (native Temporal), on every push to `main` and every pull request.
237
+
238
+ Releases:
239
+
240
+ - Every push to `main` bumps the patch version and commits it back (`bump-version.yml`).
241
+ - Pushing a `v*.*.*` tag publishes to npm with provenance (`publish.yml`). The version comes from the tag.
242
+
243
+ ## License
244
+
245
+ ISC
@@ -0,0 +1,15 @@
1
+ /** Three-letter names, lowercase. Index 0 = January. */
2
+ export declare const MONTH_NAMES: readonly string[];
3
+ /** Three-letter names, lowercase. Index = canonical weekday (0 = Sunday). */
4
+ export declare const DAY_NAMES: readonly string[];
5
+ /** Canonical (dialect-independent) bounds used by the scheduler and formatter. */
6
+ export declare const CANONICAL_BOUNDS: {
7
+ readonly second: readonly [0, 59];
8
+ readonly minute: readonly [0, 59];
9
+ readonly hour: readonly [0, 23];
10
+ readonly dayOfMonth: readonly [1, 31];
11
+ readonly month: readonly [1, 12];
12
+ readonly dayOfWeek: readonly [0, 6];
13
+ /** Quartz year bound (this library's, Quartz itself uses 2099 / now + 100). */
14
+ readonly year: readonly [1970, 2199];
15
+ };
@@ -0,0 +1,28 @@
1
+ /** Three-letter names, lowercase. Index 0 = January. */
2
+ export const MONTH_NAMES = [
3
+ "jan",
4
+ "feb",
5
+ "mar",
6
+ "apr",
7
+ "may",
8
+ "jun",
9
+ "jul",
10
+ "aug",
11
+ "sep",
12
+ "oct",
13
+ "nov",
14
+ "dec",
15
+ ];
16
+ /** Three-letter names, lowercase. Index = canonical weekday (0 = Sunday). */
17
+ export const DAY_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
18
+ /** Canonical (dialect-independent) bounds used by the scheduler and formatter. */
19
+ export const CANONICAL_BOUNDS = {
20
+ second: [0, 59],
21
+ minute: [0, 59],
22
+ hour: [0, 23],
23
+ dayOfMonth: [1, 31],
24
+ month: [1, 12],
25
+ dayOfWeek: [0, 6],
26
+ /** Quartz year bound (this library's, Quartz itself uses 2099 / now + 100). */
27
+ year: [1970, 2199],
28
+ };
@@ -0,0 +1,10 @@
1
+ import type { FieldExpr, FieldItem } from "./types.js";
2
+ /**
3
+ * Vixie/cronie rule: a day field "starts with `*`" when its text begins with
4
+ * `*` (`*` itself or `*\/n`). If either day field does, unix combines them with
5
+ * AND; otherwise with OR.
6
+ */
7
+ export declare function startsWithWildcard(expr: FieldExpr): boolean;
8
+ /** `L`, `W`, `#` and friends: day-only items with no Unix equivalent. */
9
+ export declare function isSpecialItem(item: FieldItem): boolean;
10
+ export declare function isSingleValue(expr: FieldExpr, value?: number): boolean;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Vixie/cronie rule: a day field "starts with `*`" when its text begins with
3
+ * `*` (`*` itself or `*\/n`). If either day field does, unix combines them with
4
+ * AND; otherwise with OR.
5
+ */
6
+ export function startsWithWildcard(expr) {
7
+ if (expr.kind === "any")
8
+ return true;
9
+ if (expr.kind === "none")
10
+ return false;
11
+ const [first] = expr.items;
12
+ return first?.kind === "step" && first.start === "any";
13
+ }
14
+ /** `L`, `W`, `#` and friends: day-only items with no Unix equivalent. */
15
+ export function isSpecialItem(item) {
16
+ return (item.kind === "lastDay" ||
17
+ item.kind === "nearestWeekday" ||
18
+ item.kind === "lastWeekday" ||
19
+ item.kind === "lastDayOfWeek" ||
20
+ item.kind === "nthDayOfWeek");
21
+ }
22
+ export function isSingleValue(expr, value) {
23
+ return (expr.kind === "list" &&
24
+ expr.items.length === 1 &&
25
+ expr.items[0].kind === "value" &&
26
+ (value === undefined || expr.items[0].value === value));
27
+ }
@@ -0,0 +1,33 @@
1
+ import type { Boundaries } from "../utils/operator-grammar.js";
2
+ import type { Dialect, FieldName } from "./types.js";
3
+ export interface FieldSpec {
4
+ /** Inclusive bounds in the dialect's native numbering. */
5
+ bounds: Boundaries;
6
+ /** Lowercase three-letter names; `names[i]` has native value `nameBase + i`. */
7
+ names?: readonly string[];
8
+ nameBase?: number;
9
+ /** Human hint for the names, used in error messages (e.g. `JAN-DEC`). */
10
+ namesHint?: string;
11
+ maxStep?: number;
12
+ }
13
+ export interface DialectSpec {
14
+ dialect: Dialect;
15
+ /** Fields in the order they appear in an expression. */
16
+ fieldOrder: readonly FieldName[];
17
+ /** A trailing field that may be omitted (Quartz year). */
18
+ optionalField?: FieldName;
19
+ fields: Partial<Record<FieldName, FieldSpec>>;
20
+ /** Quartz silently ignores `/n` after a name, so we reject it there. */
21
+ allowNamedStepStart: boolean;
22
+ /** Supports `?`, `L`, `W`, `#` in the day fields. */
23
+ daySpecials: boolean;
24
+ }
25
+ export declare const QUARTZ: DialectSpec;
26
+ export declare const UNIX: DialectSpec;
27
+ export declare const DIALECTS: Record<Dialect, DialectSpec>;
28
+ /** Native (dialect) weekday → canonical weekday (0 = Sunday … 6 = Saturday). */
29
+ export declare function toCanonicalWeekday(dialect: Dialect, native: number): number;
30
+ /** Canonical weekday → native weekday of the dialect. */
31
+ export declare function fromCanonicalWeekday(dialect: Dialect, canonical: number): number;
32
+ /** Unix `@macros` that expand to a schedule. `@reboot` is deliberately absent. */
33
+ export declare const UNIX_MACROS: Record<string, string>;
@@ -0,0 +1,50 @@
1
+ import { DAY_NAMES, MONTH_NAMES } from "../constants.js";
2
+ const MONTH = { bounds: [1, 12], names: MONTH_NAMES, nameBase: 1, namesHint: "JAN-DEC" };
3
+ export const QUARTZ = {
4
+ dialect: "quartz",
5
+ fieldOrder: ["second", "minute", "hour", "dayOfMonth", "month", "dayOfWeek"],
6
+ optionalField: "year",
7
+ fields: {
8
+ second: { bounds: [0, 59], maxStep: 59 },
9
+ minute: { bounds: [0, 59], maxStep: 59 },
10
+ hour: { bounds: [0, 23], maxStep: 23 },
11
+ dayOfMonth: { bounds: [1, 31], maxStep: 31 },
12
+ month: { ...MONTH, maxStep: 12 },
13
+ dayOfWeek: { bounds: [1, 7], names: DAY_NAMES, nameBase: 1, namesHint: "SUN-SAT", maxStep: 7 },
14
+ year: { bounds: [1970, 2199] },
15
+ },
16
+ allowNamedStepStart: false,
17
+ daySpecials: true,
18
+ };
19
+ export const UNIX = {
20
+ dialect: "unix",
21
+ fieldOrder: ["minute", "hour", "dayOfMonth", "month", "dayOfWeek"],
22
+ fields: {
23
+ minute: { bounds: [0, 59] },
24
+ hour: { bounds: [0, 23] },
25
+ dayOfMonth: { bounds: [1, 31] },
26
+ month: MONTH,
27
+ dayOfWeek: { bounds: [0, 7], names: DAY_NAMES, nameBase: 0, namesHint: "SUN-SAT" },
28
+ },
29
+ allowNamedStepStart: true,
30
+ daySpecials: false,
31
+ };
32
+ export const DIALECTS = { quartz: QUARTZ, unix: UNIX };
33
+ /** Native (dialect) weekday → canonical weekday (0 = Sunday … 6 = Saturday). */
34
+ export function toCanonicalWeekday(dialect, native) {
35
+ return dialect === "quartz" ? native - 1 : native % 7;
36
+ }
37
+ /** Canonical weekday → native weekday of the dialect. */
38
+ export function fromCanonicalWeekday(dialect, canonical) {
39
+ return dialect === "quartz" ? canonical + 1 : canonical;
40
+ }
41
+ /** Unix `@macros` that expand to a schedule. `@reboot` is deliberately absent. */
42
+ export const UNIX_MACROS = {
43
+ "@yearly": "0 0 1 1 *",
44
+ "@annually": "0 0 1 1 *",
45
+ "@monthly": "0 0 1 * *",
46
+ "@weekly": "0 0 * * 0",
47
+ "@daily": "0 0 * * *",
48
+ "@midnight": "0 0 * * *",
49
+ "@hourly": "0 * * * *",
50
+ };
@@ -0,0 +1,19 @@
1
+ import type { CronError, CronErrorCode, FieldName } from "./types.js";
2
+ export declare const FIELD_LABELS: Record<FieldName, string>;
3
+ type ErrorParams = CronError["params"];
4
+ /** English text for an error. Also the `en` locale's error formatter. */
5
+ export declare function englishErrorMessage(error: Pick<CronError, "code" | "field" | "params">): string;
6
+ export declare function createError(code: CronErrorCode, field?: FieldName, params?: ErrorParams): CronError;
7
+ /** Thrown by functions that accept `string | Cron` when the string is invalid. */
8
+ export declare class CronParseError extends Error {
9
+ name: string;
10
+ readonly errors: CronError[];
11
+ constructor(errors: CronError[]);
12
+ }
13
+ /** Thrown by `convert` when the target dialect can't express part of the expression. */
14
+ export declare class CronConvertError extends Error {
15
+ name: string;
16
+ readonly reasons: string[];
17
+ constructor(reasons: string[]);
18
+ }
19
+ export {};
@@ -0,0 +1,74 @@
1
+ export const FIELD_LABELS = {
2
+ second: "Seconds",
3
+ minute: "Minutes",
4
+ hour: "Hours",
5
+ dayOfMonth: "Day-of-month",
6
+ month: "Month",
7
+ dayOfWeek: "Day-of-week",
8
+ year: "Year",
9
+ };
10
+ const DIALECT_LABELS = { quartz: "Quartz", unix: "Unix" };
11
+ /** English text for an error. Also the `en` locale's error formatter. */
12
+ export function englishErrorMessage(error) {
13
+ const { code, field, params } = error;
14
+ const label = field ? FIELD_LABELS[field] : "Field";
15
+ const lowerLabel = label.toLowerCase();
16
+ switch (code) {
17
+ case "EMPTY_EXPRESSION":
18
+ return "Cron expression is empty";
19
+ case "WRONG_FIELD_COUNT": {
20
+ const got = params.count === undefined ? "" : ` (got ${params.count})`;
21
+ if (params.dialect === "quartz")
22
+ return `Quartz cron expressions must have 6 fields, or 7 including a year${got}`;
23
+ if (params.dialect === "unix")
24
+ return `Unix cron expressions must have 5 fields${got}`;
25
+ return `Cron expressions must have 5 fields (Unix) or 6-7 fields (Quartz)${got}`;
26
+ }
27
+ case "UNKNOWN_MACRO":
28
+ return `Unknown macro '${params.macro}'`;
29
+ case "UNSUPPORTED_MACRO":
30
+ return `'${params.macro}' runs at startup, not on a schedule, and is not supported`;
31
+ case "INVALID_VALUE": {
32
+ const names = params.names ? `, or ${params.names}` : "";
33
+ return `${label} must be between ${params.min} and ${params.max}${names}`;
34
+ }
35
+ case "INVALID_RANGE":
36
+ return `${label} has an invalid range '${params.token}' (start must not be after end)`;
37
+ case "INVALID_STEP": {
38
+ const bound = params.max === undefined ? "" : ` (increment must be between 1 and ${params.max})`;
39
+ return `${label} has an invalid step '${params.token}'${bound}`;
40
+ }
41
+ case "UNSUPPORTED_SYNTAX":
42
+ return `${label} does not support '${params.token}' in ${DIALECT_LABELS[params.dialect] ?? params.dialect} cron`;
43
+ case "INVALID_NTH":
44
+ return "The occurrence after '#' must be between 1 and 5";
45
+ case "SPECIAL_NOT_COMBINABLE":
46
+ return `'${params.token}' cannot be combined with other values in ${lowerLabel}`;
47
+ case "DAY_FIELDS_BOTH_SET":
48
+ return "Quartz requires '?' in either day-of-month or day-of-week";
49
+ case "DAY_FIELDS_BOTH_UNSET":
50
+ return "'?' can be used in day-of-month or day-of-week, not both";
51
+ }
52
+ }
53
+ export function createError(code, field, params = {}) {
54
+ const draft = field ? { code, field, params } : { code, params };
55
+ return { ...draft, message: englishErrorMessage(draft) };
56
+ }
57
+ /** Thrown by functions that accept `string | Cron` when the string is invalid. */
58
+ export class CronParseError extends Error {
59
+ name = "CronParseError";
60
+ errors;
61
+ constructor(errors) {
62
+ super(errors.map((error) => error.message).join("; "));
63
+ this.errors = errors;
64
+ }
65
+ }
66
+ /** Thrown by `convert` when the target dialect can't express part of the expression. */
67
+ export class CronConvertError extends Error {
68
+ name = "CronConvertError";
69
+ reasons;
70
+ constructor(reasons) {
71
+ super(reasons.join("; "));
72
+ this.reasons = reasons;
73
+ }
74
+ }
@@ -0,0 +1,15 @@
1
+ import { type DialectSpec } from "./dialects.js";
2
+ import type { CronError, CronErrorCode, FieldExpr, FieldName } from "./types.js";
3
+ export interface FieldIssue {
4
+ code: CronErrorCode;
5
+ params: CronError["params"];
6
+ }
7
+ export type FieldParseResult = {
8
+ ok: true;
9
+ expr: FieldExpr;
10
+ } | {
11
+ ok: false;
12
+ issue: FieldIssue;
13
+ };
14
+ /** Parses one field's text into canonical form for the given dialect. */
15
+ export declare function parseField(dialect: DialectSpec, field: FieldName, text: string): FieldParseResult;