@nixxie-cms/fields-cron 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.
- package/LICENSE +23 -0
- package/README.md +38 -0
- package/dist/declarations/src/index.d.ts +30 -0
- package/dist/declarations/src/index.d.ts.map +1 -0
- package/dist/nixxie-cms-fields-cron.cjs.d.ts +2 -0
- package/dist/nixxie-cms-fields-cron.cjs.js +230 -0
- package/dist/nixxie-cms-fields-cron.esm.js +223 -0
- package/package.json +33 -0
- package/src/index.ts +234 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Nixxie International DMCC
|
|
4
|
+
Portions Copyright (c) 2023 Thinkmill Labs Pty Ltd and contributors
|
|
5
|
+
(this software is derived from the KeystoneJS project, https://keystonejs.com)
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
# @nixxie-cms/fields-cron
|
|
2
|
+
|
|
3
|
+
A cron-expression field for Nixxie CMS. Stores a validated 5-field schedule
|
|
4
|
+
(`minute hour day-of-month month day-of-week`) using the same syntax subset as
|
|
5
|
+
`@nixxie-cms/jobs`: `*`, literals, ranges (`a-b`), steps (`*/n`, `a/n`, `a-b/n`) and
|
|
6
|
+
comma-separated lists. `L`/`W`/`#` and month/day names are not supported.
|
|
7
|
+
|
|
8
|
+
```ts
|
|
9
|
+
import { cron } from '@nixxie-cms/fields-cron'
|
|
10
|
+
|
|
11
|
+
fields: {
|
|
12
|
+
schedule: cron({ validation: { isRequired: true } }),
|
|
13
|
+
}
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Invalid expressions are rejected with the reason, e.g. `minute value 61 is out of range (0-59)`.
|
|
17
|
+
|
|
18
|
+
## Helpers
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { isValidCron, nextRuns, describeCron } from '@nixxie-cms/fields-cron'
|
|
22
|
+
|
|
23
|
+
isValidCron('*/15 9-17 * * 1-5') // true
|
|
24
|
+
isValidCron('61 * * * *') // false
|
|
25
|
+
|
|
26
|
+
nextRuns('0 9 * * 1', 3) // next 3 Mondays at 09:00 (scan capped at 366 days ahead)
|
|
27
|
+
nextRuns('*/5 * * * *', 5, new Date('2026-06-12T10:00:00')) // from a specific time
|
|
28
|
+
|
|
29
|
+
describeCron('* * * * *') // 'every minute'
|
|
30
|
+
describeCron('*/10 * * * *') // 'every 10 minutes'
|
|
31
|
+
describeCron('30 9 * * *') // 'daily at 09:30'
|
|
32
|
+
describeCron('0 8 * * 1') // 'weekly on Monday at 08:00'
|
|
33
|
+
describeCron('15 0 1 * *') // 'monthly on day 1 at 00:15'
|
|
34
|
+
describeCron('0 0 1 1 *') // 'cron: 0 0 1 1 *' (best-effort fallback)
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
`nextRuns` scans minute-by-minute (like the jobs scheduler) in the server's local time and stops
|
|
38
|
+
after 366 days, so rare or impossible schedules may return fewer dates than requested.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { TextFieldConfig } from '@nixxie-cms/core/fields';
|
|
2
|
+
import type { BaseCollectionTypeInfo, FieldTypeFunc } from '@nixxie-cms/core/types';
|
|
3
|
+
/** Whether `expr` is a valid 5-field cron expression in the supported subset. */
|
|
4
|
+
export declare function isValidCron(expr: string): boolean;
|
|
5
|
+
/**
|
|
6
|
+
* Compute the next `count` (default 5) times `expr` will fire after `from` (default now), using
|
|
7
|
+
* the same minute-by-minute scan as @nixxie-cms/jobs. The scan is capped at 366 days ahead, so
|
|
8
|
+
* fewer (or zero) dates are returned for expressions that fire rarely or never (e.g. `0 0 31 2 *`).
|
|
9
|
+
* Throws when the expression is invalid.
|
|
10
|
+
*/
|
|
11
|
+
export declare function nextRuns(expr: string, count?: number, from?: Date): Date[];
|
|
12
|
+
/**
|
|
13
|
+
* Best-effort human description of a cron expression. Handles the common shapes — "every minute",
|
|
14
|
+
* "every N minutes", "daily at HH:MM", "weekly on <day> at HH:MM" and "monthly on day N at HH:MM"
|
|
15
|
+
* — and falls back to `cron: <expr>` for anything else (including invalid expressions).
|
|
16
|
+
*/
|
|
17
|
+
export declare function describeCron(expr: string): string;
|
|
18
|
+
export type CronFieldConfig<CollectionTypeInfo extends BaseCollectionTypeInfo> = Omit<TextFieldConfig<CollectionTypeInfo>, 'validation'> & {
|
|
19
|
+
validation?: {
|
|
20
|
+
/** Reject saving when no value is present. */
|
|
21
|
+
isRequired?: boolean;
|
|
22
|
+
};
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* A cron-expression field storing a validated 5-field schedule (`minute hour dom month dow`).
|
|
26
|
+
* Built on the core `text` field. Supports the same subset as @nixxie-cms/jobs: `*`, literals,
|
|
27
|
+
* ranges, steps and comma-separated lists. Whitespace is normalised on save.
|
|
28
|
+
*/
|
|
29
|
+
export declare function cron<CollectionTypeInfo extends BaseCollectionTypeInfo>(config?: CronFieldConfig<CollectionTypeInfo>): FieldTypeFunc<CollectionTypeInfo>;
|
|
30
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"../../../src","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAA;AAC9D,OAAO,KAAK,EAAE,sBAAsB,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA;AAyHnF,iFAAiF;AACjF,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAOjD;AAED;;;;;GAKG;AACH,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,GAAE,MAAU,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,IAAI,EAAE,CAW7E;AAID;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAwBjD;AAID,MAAM,MAAM,eAAe,CAAC,kBAAkB,SAAS,sBAAsB,IAAI,IAAI,CACnF,eAAe,CAAC,kBAAkB,CAAC,EACnC,YAAY,CACb,GAAG;IACF,UAAU,CAAC,EAAE;QACX,8CAA8C;QAC9C,UAAU,CAAC,EAAE,OAAO,CAAA;KACrB,CAAA;CACF,CAAA;AAED;;;;GAIG;AACH,wBAAgB,IAAI,CAAC,kBAAkB,SAAS,sBAAsB,EACpE,MAAM,GAAE,eAAe,CAAC,kBAAkB,CAAM,GAC/C,aAAa,CAAC,kBAAkB,CAAC,CA6BnC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export * from "./declarations/src/index.js";
|
|
2
|
+
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibml4eGllLWNtcy1maWVsZHMtY3Jvbi5janMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4vZGVjbGFyYXRpb25zL3NyYy9pbmRleC5kLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBIn0=
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
|
+
|
|
5
|
+
var fields = require('@nixxie-cms/core/fields');
|
|
6
|
+
|
|
7
|
+
// ── Cron parsing ──
|
|
8
|
+
//
|
|
9
|
+
// Supports the same subset as @nixxie-cms/jobs: five fields (minute hour dom month dow) with
|
|
10
|
+
// `*`, literals, ranges (`a-b`), steps (`*/n`, `a/n`, `a-b/n`) and comma-separated lists of any
|
|
11
|
+
// of the above. L/W/# and names (JAN, MON) are not supported.
|
|
12
|
+
|
|
13
|
+
const FIELD_SPECS = [{
|
|
14
|
+
name: 'minute',
|
|
15
|
+
min: 0,
|
|
16
|
+
max: 59
|
|
17
|
+
}, {
|
|
18
|
+
name: 'hour',
|
|
19
|
+
min: 0,
|
|
20
|
+
max: 23
|
|
21
|
+
}, {
|
|
22
|
+
name: 'day-of-month',
|
|
23
|
+
min: 1,
|
|
24
|
+
max: 31
|
|
25
|
+
}, {
|
|
26
|
+
name: 'month',
|
|
27
|
+
min: 1,
|
|
28
|
+
max: 12
|
|
29
|
+
}, {
|
|
30
|
+
name: 'day-of-week',
|
|
31
|
+
min: 0,
|
|
32
|
+
max: 6
|
|
33
|
+
}];
|
|
34
|
+
function parseNumber(token, spec) {
|
|
35
|
+
if (!/^\d+$/.test(token)) {
|
|
36
|
+
throw new Error(`${spec.name} field has invalid value "${token}"`);
|
|
37
|
+
}
|
|
38
|
+
const n = parseInt(token, 10);
|
|
39
|
+
if (n < spec.min || n > spec.max) {
|
|
40
|
+
throw new Error(`${spec.name} value ${n} is out of range (${spec.min}-${spec.max})`);
|
|
41
|
+
}
|
|
42
|
+
return n;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Parse one comma-separated part of a cron field into a matcher; throws on invalid syntax. */
|
|
46
|
+
function parsePart(part, spec) {
|
|
47
|
+
if (part === '') {
|
|
48
|
+
throw new Error(`${spec.name} field has an empty entry`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Step: base/step, where base is '*', a single number, or a range a-b
|
|
52
|
+
if (part.includes('/')) {
|
|
53
|
+
const pieces = part.split('/');
|
|
54
|
+
if (pieces.length !== 2) {
|
|
55
|
+
throw new Error(`${spec.name} field has invalid step expression "${part}"`);
|
|
56
|
+
}
|
|
57
|
+
const [base, stepStr] = pieces;
|
|
58
|
+
if (!/^\d+$/.test(stepStr) || parseInt(stepStr, 10) <= 0) {
|
|
59
|
+
throw new Error(`${spec.name} field has invalid step "/${stepStr}" (must be a positive integer)`);
|
|
60
|
+
}
|
|
61
|
+
const step = parseInt(stepStr, 10);
|
|
62
|
+
let from = spec.min;
|
|
63
|
+
let to = spec.max;
|
|
64
|
+
if (base !== '*') {
|
|
65
|
+
if (base.includes('-')) {
|
|
66
|
+
const range = base.split('-');
|
|
67
|
+
if (range.length !== 2) {
|
|
68
|
+
throw new Error(`${spec.name} field has invalid range "${base}"`);
|
|
69
|
+
}
|
|
70
|
+
from = parseNumber(range[0], spec);
|
|
71
|
+
to = parseNumber(range[1], spec);
|
|
72
|
+
if (from > to) {
|
|
73
|
+
throw new Error(`${spec.name} range ${from}-${to} is inverted (start must be <= end)`);
|
|
74
|
+
}
|
|
75
|
+
} else {
|
|
76
|
+
// a/n means "starting at a, every n" (open-ended), matching @nixxie-cms/jobs
|
|
77
|
+
from = parseNumber(base, spec);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return value => value >= from && value <= to && (value - from) % step === 0;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Range: a-b
|
|
84
|
+
if (part.includes('-')) {
|
|
85
|
+
const range = part.split('-');
|
|
86
|
+
if (range.length !== 2) {
|
|
87
|
+
throw new Error(`${spec.name} field has invalid range "${part}"`);
|
|
88
|
+
}
|
|
89
|
+
const from = parseNumber(range[0], spec);
|
|
90
|
+
const to = parseNumber(range[1], spec);
|
|
91
|
+
if (from > to) {
|
|
92
|
+
throw new Error(`${spec.name} range ${from}-${to} is inverted (start must be <= end)`);
|
|
93
|
+
}
|
|
94
|
+
return value => value >= from && value <= to;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Wildcard
|
|
98
|
+
if (part === '*') return () => true;
|
|
99
|
+
|
|
100
|
+
// Literal
|
|
101
|
+
const literal = parseNumber(part, spec);
|
|
102
|
+
return value => value === literal;
|
|
103
|
+
}
|
|
104
|
+
function parseField(field, spec) {
|
|
105
|
+
const matchers = field.split(',').map(part => parsePart(part, spec));
|
|
106
|
+
return value => matchers.some(m => m(value));
|
|
107
|
+
}
|
|
108
|
+
/** Compile a 5-field cron expression into a Date matcher; throws with the reason when invalid. */
|
|
109
|
+
function compileCron(expr) {
|
|
110
|
+
if (typeof expr !== 'string' || expr.trim() === '') {
|
|
111
|
+
throw new Error('cron expression must be a non-empty string');
|
|
112
|
+
}
|
|
113
|
+
const fields = expr.trim().split(/\s+/);
|
|
114
|
+
if (fields.length !== 5) {
|
|
115
|
+
throw new Error(`cron expression must have 5 fields (minute hour day-of-month month day-of-week), got ${fields.length}`);
|
|
116
|
+
}
|
|
117
|
+
const [minute, hour, dom, month, dow] = fields.map((field, i) => parseField(field, FIELD_SPECS[i]));
|
|
118
|
+
return date => minute(date.getMinutes()) && hour(date.getHours()) && dom(date.getDate()) && month(date.getMonth() + 1) && dow(date.getDay());
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Whether `expr` is a valid 5-field cron expression in the supported subset. */
|
|
122
|
+
function isValidCron(expr) {
|
|
123
|
+
try {
|
|
124
|
+
compileCron(expr);
|
|
125
|
+
return true;
|
|
126
|
+
} catch {
|
|
127
|
+
return false;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Compute the next `count` (default 5) times `expr` will fire after `from` (default now), using
|
|
133
|
+
* the same minute-by-minute scan as @nixxie-cms/jobs. The scan is capped at 366 days ahead, so
|
|
134
|
+
* fewer (or zero) dates are returned for expressions that fire rarely or never (e.g. `0 0 31 2 *`).
|
|
135
|
+
* Throws when the expression is invalid.
|
|
136
|
+
*/
|
|
137
|
+
function nextRuns(expr, count = 5, from) {
|
|
138
|
+
var _from$getTime;
|
|
139
|
+
const matcher = compileCron(expr);
|
|
140
|
+
const results = [];
|
|
141
|
+
const start = new Date((_from$getTime = from === null || from === void 0 ? void 0 : from.getTime()) !== null && _from$getTime !== void 0 ? _from$getTime : Date.now());
|
|
142
|
+
start.setSeconds(0, 0);
|
|
143
|
+
const limit = 366 * 24 * 60; // cap the scan at ~366 days, covering yearly schedules
|
|
144
|
+
for (let i = 1; i <= limit && results.length < count; i++) {
|
|
145
|
+
const candidate = new Date(start.getTime() + i * 60000);
|
|
146
|
+
if (matcher(candidate)) results.push(candidate);
|
|
147
|
+
}
|
|
148
|
+
return results;
|
|
149
|
+
}
|
|
150
|
+
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Best-effort human description of a cron expression. Handles the common shapes — "every minute",
|
|
154
|
+
* "every N minutes", "daily at HH:MM", "weekly on <day> at HH:MM" and "monthly on day N at HH:MM"
|
|
155
|
+
* — and falls back to `cron: <expr>` for anything else (including invalid expressions).
|
|
156
|
+
*/
|
|
157
|
+
function describeCron(expr) {
|
|
158
|
+
const fallback = `cron: ${expr}`;
|
|
159
|
+
if (!isValidCron(expr)) return fallback;
|
|
160
|
+
const [minute, hour, dom, month, dow] = expr.trim().split(/\s+/);
|
|
161
|
+
if (minute === '*' && hour === '*' && dom === '*' && month === '*' && dow === '*') {
|
|
162
|
+
return 'every minute';
|
|
163
|
+
}
|
|
164
|
+
const everyN = /^\*\/(\d+)$/.exec(minute);
|
|
165
|
+
if (everyN && hour === '*' && dom === '*' && month === '*' && dow === '*') {
|
|
166
|
+
const n = parseInt(everyN[1], 10);
|
|
167
|
+
return n === 1 ? 'every minute' : `every ${n} minutes`;
|
|
168
|
+
}
|
|
169
|
+
if (/^\d+$/.test(minute) && /^\d+$/.test(hour) && month === '*') {
|
|
170
|
+
const time = `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
|
|
171
|
+
if (dom === '*' && dow === '*') return `daily at ${time}`;
|
|
172
|
+
if (dom === '*' && /^\d+$/.test(dow)) return `weekly on ${WEEKDAYS[parseInt(dow, 10)]} at ${time}`;
|
|
173
|
+
if (dow === '*' && /^\d+$/.test(dom)) return `monthly on day ${parseInt(dom, 10)} at ${time}`;
|
|
174
|
+
}
|
|
175
|
+
return fallback;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ── Field type ──
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* A cron-expression field storing a validated 5-field schedule (`minute hour dom month dow`).
|
|
182
|
+
* Built on the core `text` field. Supports the same subset as @nixxie-cms/jobs: `*`, literals,
|
|
183
|
+
* ranges, steps and comma-separated lists. Whitespace is normalised on save.
|
|
184
|
+
*/
|
|
185
|
+
function cron(config = {}) {
|
|
186
|
+
const {
|
|
187
|
+
hooks,
|
|
188
|
+
validation,
|
|
189
|
+
...rest
|
|
190
|
+
} = config;
|
|
191
|
+
return fields.text({
|
|
192
|
+
...rest,
|
|
193
|
+
validation: {
|
|
194
|
+
isRequired: validation === null || validation === void 0 ? void 0 : validation.isRequired
|
|
195
|
+
},
|
|
196
|
+
ui: {
|
|
197
|
+
description: 'Cron expression, e.g. */15 9-17 * * 1-5',
|
|
198
|
+
...rest.ui
|
|
199
|
+
},
|
|
200
|
+
hooks: {
|
|
201
|
+
...hooks,
|
|
202
|
+
resolveInput: args => {
|
|
203
|
+
const v = args.resolvedData[args.fieldKey];
|
|
204
|
+
return typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : v;
|
|
205
|
+
},
|
|
206
|
+
validate: args => {
|
|
207
|
+
const {
|
|
208
|
+
resolvedData,
|
|
209
|
+
fieldKey,
|
|
210
|
+
addValidationError,
|
|
211
|
+
operation
|
|
212
|
+
} = args;
|
|
213
|
+
if (operation === 'delete') return;
|
|
214
|
+
const value = resolvedData[fieldKey];
|
|
215
|
+
if (typeof value === 'string' && value.length > 0) {
|
|
216
|
+
try {
|
|
217
|
+
compileCron(value);
|
|
218
|
+
} catch (err) {
|
|
219
|
+
addValidationError(`${fieldKey} is not a valid cron expression: ${err instanceof Error ? err.message : String(err)}`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
exports.cron = cron;
|
|
228
|
+
exports.describeCron = describeCron;
|
|
229
|
+
exports.isValidCron = isValidCron;
|
|
230
|
+
exports.nextRuns = nextRuns;
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { text } from '@nixxie-cms/core/fields';
|
|
2
|
+
|
|
3
|
+
// ── Cron parsing ──
|
|
4
|
+
//
|
|
5
|
+
// Supports the same subset as @nixxie-cms/jobs: five fields (minute hour dom month dow) with
|
|
6
|
+
// `*`, literals, ranges (`a-b`), steps (`*/n`, `a/n`, `a-b/n`) and comma-separated lists of any
|
|
7
|
+
// of the above. L/W/# and names (JAN, MON) are not supported.
|
|
8
|
+
|
|
9
|
+
const FIELD_SPECS = [{
|
|
10
|
+
name: 'minute',
|
|
11
|
+
min: 0,
|
|
12
|
+
max: 59
|
|
13
|
+
}, {
|
|
14
|
+
name: 'hour',
|
|
15
|
+
min: 0,
|
|
16
|
+
max: 23
|
|
17
|
+
}, {
|
|
18
|
+
name: 'day-of-month',
|
|
19
|
+
min: 1,
|
|
20
|
+
max: 31
|
|
21
|
+
}, {
|
|
22
|
+
name: 'month',
|
|
23
|
+
min: 1,
|
|
24
|
+
max: 12
|
|
25
|
+
}, {
|
|
26
|
+
name: 'day-of-week',
|
|
27
|
+
min: 0,
|
|
28
|
+
max: 6
|
|
29
|
+
}];
|
|
30
|
+
function parseNumber(token, spec) {
|
|
31
|
+
if (!/^\d+$/.test(token)) {
|
|
32
|
+
throw new Error(`${spec.name} field has invalid value "${token}"`);
|
|
33
|
+
}
|
|
34
|
+
const n = parseInt(token, 10);
|
|
35
|
+
if (n < spec.min || n > spec.max) {
|
|
36
|
+
throw new Error(`${spec.name} value ${n} is out of range (${spec.min}-${spec.max})`);
|
|
37
|
+
}
|
|
38
|
+
return n;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Parse one comma-separated part of a cron field into a matcher; throws on invalid syntax. */
|
|
42
|
+
function parsePart(part, spec) {
|
|
43
|
+
if (part === '') {
|
|
44
|
+
throw new Error(`${spec.name} field has an empty entry`);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Step: base/step, where base is '*', a single number, or a range a-b
|
|
48
|
+
if (part.includes('/')) {
|
|
49
|
+
const pieces = part.split('/');
|
|
50
|
+
if (pieces.length !== 2) {
|
|
51
|
+
throw new Error(`${spec.name} field has invalid step expression "${part}"`);
|
|
52
|
+
}
|
|
53
|
+
const [base, stepStr] = pieces;
|
|
54
|
+
if (!/^\d+$/.test(stepStr) || parseInt(stepStr, 10) <= 0) {
|
|
55
|
+
throw new Error(`${spec.name} field has invalid step "/${stepStr}" (must be a positive integer)`);
|
|
56
|
+
}
|
|
57
|
+
const step = parseInt(stepStr, 10);
|
|
58
|
+
let from = spec.min;
|
|
59
|
+
let to = spec.max;
|
|
60
|
+
if (base !== '*') {
|
|
61
|
+
if (base.includes('-')) {
|
|
62
|
+
const range = base.split('-');
|
|
63
|
+
if (range.length !== 2) {
|
|
64
|
+
throw new Error(`${spec.name} field has invalid range "${base}"`);
|
|
65
|
+
}
|
|
66
|
+
from = parseNumber(range[0], spec);
|
|
67
|
+
to = parseNumber(range[1], spec);
|
|
68
|
+
if (from > to) {
|
|
69
|
+
throw new Error(`${spec.name} range ${from}-${to} is inverted (start must be <= end)`);
|
|
70
|
+
}
|
|
71
|
+
} else {
|
|
72
|
+
// a/n means "starting at a, every n" (open-ended), matching @nixxie-cms/jobs
|
|
73
|
+
from = parseNumber(base, spec);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return value => value >= from && value <= to && (value - from) % step === 0;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Range: a-b
|
|
80
|
+
if (part.includes('-')) {
|
|
81
|
+
const range = part.split('-');
|
|
82
|
+
if (range.length !== 2) {
|
|
83
|
+
throw new Error(`${spec.name} field has invalid range "${part}"`);
|
|
84
|
+
}
|
|
85
|
+
const from = parseNumber(range[0], spec);
|
|
86
|
+
const to = parseNumber(range[1], spec);
|
|
87
|
+
if (from > to) {
|
|
88
|
+
throw new Error(`${spec.name} range ${from}-${to} is inverted (start must be <= end)`);
|
|
89
|
+
}
|
|
90
|
+
return value => value >= from && value <= to;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Wildcard
|
|
94
|
+
if (part === '*') return () => true;
|
|
95
|
+
|
|
96
|
+
// Literal
|
|
97
|
+
const literal = parseNumber(part, spec);
|
|
98
|
+
return value => value === literal;
|
|
99
|
+
}
|
|
100
|
+
function parseField(field, spec) {
|
|
101
|
+
const matchers = field.split(',').map(part => parsePart(part, spec));
|
|
102
|
+
return value => matchers.some(m => m(value));
|
|
103
|
+
}
|
|
104
|
+
/** Compile a 5-field cron expression into a Date matcher; throws with the reason when invalid. */
|
|
105
|
+
function compileCron(expr) {
|
|
106
|
+
if (typeof expr !== 'string' || expr.trim() === '') {
|
|
107
|
+
throw new Error('cron expression must be a non-empty string');
|
|
108
|
+
}
|
|
109
|
+
const fields = expr.trim().split(/\s+/);
|
|
110
|
+
if (fields.length !== 5) {
|
|
111
|
+
throw new Error(`cron expression must have 5 fields (minute hour day-of-month month day-of-week), got ${fields.length}`);
|
|
112
|
+
}
|
|
113
|
+
const [minute, hour, dom, month, dow] = fields.map((field, i) => parseField(field, FIELD_SPECS[i]));
|
|
114
|
+
return date => minute(date.getMinutes()) && hour(date.getHours()) && dom(date.getDate()) && month(date.getMonth() + 1) && dow(date.getDay());
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Whether `expr` is a valid 5-field cron expression in the supported subset. */
|
|
118
|
+
function isValidCron(expr) {
|
|
119
|
+
try {
|
|
120
|
+
compileCron(expr);
|
|
121
|
+
return true;
|
|
122
|
+
} catch {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Compute the next `count` (default 5) times `expr` will fire after `from` (default now), using
|
|
129
|
+
* the same minute-by-minute scan as @nixxie-cms/jobs. The scan is capped at 366 days ahead, so
|
|
130
|
+
* fewer (or zero) dates are returned for expressions that fire rarely or never (e.g. `0 0 31 2 *`).
|
|
131
|
+
* Throws when the expression is invalid.
|
|
132
|
+
*/
|
|
133
|
+
function nextRuns(expr, count = 5, from) {
|
|
134
|
+
var _from$getTime;
|
|
135
|
+
const matcher = compileCron(expr);
|
|
136
|
+
const results = [];
|
|
137
|
+
const start = new Date((_from$getTime = from === null || from === void 0 ? void 0 : from.getTime()) !== null && _from$getTime !== void 0 ? _from$getTime : Date.now());
|
|
138
|
+
start.setSeconds(0, 0);
|
|
139
|
+
const limit = 366 * 24 * 60; // cap the scan at ~366 days, covering yearly schedules
|
|
140
|
+
for (let i = 1; i <= limit && results.length < count; i++) {
|
|
141
|
+
const candidate = new Date(start.getTime() + i * 60000);
|
|
142
|
+
if (matcher(candidate)) results.push(candidate);
|
|
143
|
+
}
|
|
144
|
+
return results;
|
|
145
|
+
}
|
|
146
|
+
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Best-effort human description of a cron expression. Handles the common shapes — "every minute",
|
|
150
|
+
* "every N minutes", "daily at HH:MM", "weekly on <day> at HH:MM" and "monthly on day N at HH:MM"
|
|
151
|
+
* — and falls back to `cron: <expr>` for anything else (including invalid expressions).
|
|
152
|
+
*/
|
|
153
|
+
function describeCron(expr) {
|
|
154
|
+
const fallback = `cron: ${expr}`;
|
|
155
|
+
if (!isValidCron(expr)) return fallback;
|
|
156
|
+
const [minute, hour, dom, month, dow] = expr.trim().split(/\s+/);
|
|
157
|
+
if (minute === '*' && hour === '*' && dom === '*' && month === '*' && dow === '*') {
|
|
158
|
+
return 'every minute';
|
|
159
|
+
}
|
|
160
|
+
const everyN = /^\*\/(\d+)$/.exec(minute);
|
|
161
|
+
if (everyN && hour === '*' && dom === '*' && month === '*' && dow === '*') {
|
|
162
|
+
const n = parseInt(everyN[1], 10);
|
|
163
|
+
return n === 1 ? 'every minute' : `every ${n} minutes`;
|
|
164
|
+
}
|
|
165
|
+
if (/^\d+$/.test(minute) && /^\d+$/.test(hour) && month === '*') {
|
|
166
|
+
const time = `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`;
|
|
167
|
+
if (dom === '*' && dow === '*') return `daily at ${time}`;
|
|
168
|
+
if (dom === '*' && /^\d+$/.test(dow)) return `weekly on ${WEEKDAYS[parseInt(dow, 10)]} at ${time}`;
|
|
169
|
+
if (dow === '*' && /^\d+$/.test(dom)) return `monthly on day ${parseInt(dom, 10)} at ${time}`;
|
|
170
|
+
}
|
|
171
|
+
return fallback;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ── Field type ──
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* A cron-expression field storing a validated 5-field schedule (`minute hour dom month dow`).
|
|
178
|
+
* Built on the core `text` field. Supports the same subset as @nixxie-cms/jobs: `*`, literals,
|
|
179
|
+
* ranges, steps and comma-separated lists. Whitespace is normalised on save.
|
|
180
|
+
*/
|
|
181
|
+
function cron(config = {}) {
|
|
182
|
+
const {
|
|
183
|
+
hooks,
|
|
184
|
+
validation,
|
|
185
|
+
...rest
|
|
186
|
+
} = config;
|
|
187
|
+
return text({
|
|
188
|
+
...rest,
|
|
189
|
+
validation: {
|
|
190
|
+
isRequired: validation === null || validation === void 0 ? void 0 : validation.isRequired
|
|
191
|
+
},
|
|
192
|
+
ui: {
|
|
193
|
+
description: 'Cron expression, e.g. */15 9-17 * * 1-5',
|
|
194
|
+
...rest.ui
|
|
195
|
+
},
|
|
196
|
+
hooks: {
|
|
197
|
+
...hooks,
|
|
198
|
+
resolveInput: args => {
|
|
199
|
+
const v = args.resolvedData[args.fieldKey];
|
|
200
|
+
return typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : v;
|
|
201
|
+
},
|
|
202
|
+
validate: args => {
|
|
203
|
+
const {
|
|
204
|
+
resolvedData,
|
|
205
|
+
fieldKey,
|
|
206
|
+
addValidationError,
|
|
207
|
+
operation
|
|
208
|
+
} = args;
|
|
209
|
+
if (operation === 'delete') return;
|
|
210
|
+
const value = resolvedData[fieldKey];
|
|
211
|
+
if (typeof value === 'string' && value.length > 0) {
|
|
212
|
+
try {
|
|
213
|
+
compileCron(value);
|
|
214
|
+
} catch (err) {
|
|
215
|
+
addValidationError(`${fieldKey} is not a valid cron expression: ${err instanceof Error ? err.message : String(err)}`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export { cron, describeCron, isValidCron, nextRuns };
|
package/package.json
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@nixxie-cms/fields-cron",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"main": "dist/nixxie-cms-fields-cron.cjs.js",
|
|
6
|
+
"module": "dist/nixxie-cms-fields-cron.esm.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": {
|
|
9
|
+
"types": "./dist/nixxie-cms-fields-cron.cjs.js",
|
|
10
|
+
"module": "./dist/nixxie-cms-fields-cron.esm.js",
|
|
11
|
+
"default": "./dist/nixxie-cms-fields-cron.cjs.js"
|
|
12
|
+
},
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"dependencies": {
|
|
16
|
+
"@babel/runtime": "^7.24.7"
|
|
17
|
+
},
|
|
18
|
+
"devDependencies": {
|
|
19
|
+
"@nixxie-cms/core": "^1.1.0"
|
|
20
|
+
},
|
|
21
|
+
"peerDependencies": {
|
|
22
|
+
"@nixxie-cms/core": "^1.0.1"
|
|
23
|
+
},
|
|
24
|
+
"preconstruct": {
|
|
25
|
+
"entrypoints": [
|
|
26
|
+
"index.ts"
|
|
27
|
+
]
|
|
28
|
+
},
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "https://github.com/nixxiecms/nixxie/tree/main/packages/fields-cron"
|
|
32
|
+
}
|
|
33
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
import { text } from '@nixxie-cms/core/fields'
|
|
2
|
+
import type { TextFieldConfig } from '@nixxie-cms/core/fields'
|
|
3
|
+
import type { BaseCollectionTypeInfo, FieldTypeFunc } from '@nixxie-cms/core/types'
|
|
4
|
+
|
|
5
|
+
// ── Cron parsing ──
|
|
6
|
+
//
|
|
7
|
+
// Supports the same subset as @nixxie-cms/jobs: five fields (minute hour dom month dow) with
|
|
8
|
+
// `*`, literals, ranges (`a-b`), steps (`*/n`, `a/n`, `a-b/n`) and comma-separated lists of any
|
|
9
|
+
// of the above. L/W/# and names (JAN, MON) are not supported.
|
|
10
|
+
|
|
11
|
+
type FieldSpec = { name: string; min: number; max: number }
|
|
12
|
+
|
|
13
|
+
const FIELD_SPECS: FieldSpec[] = [
|
|
14
|
+
{ name: 'minute', min: 0, max: 59 },
|
|
15
|
+
{ name: 'hour', min: 0, max: 23 },
|
|
16
|
+
{ name: 'day-of-month', min: 1, max: 31 },
|
|
17
|
+
{ name: 'month', min: 1, max: 12 },
|
|
18
|
+
{ name: 'day-of-week', min: 0, max: 6 },
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
type Matcher = (value: number) => boolean
|
|
22
|
+
|
|
23
|
+
function parseNumber(token: string, spec: FieldSpec): number {
|
|
24
|
+
if (!/^\d+$/.test(token)) {
|
|
25
|
+
throw new Error(`${spec.name} field has invalid value "${token}"`)
|
|
26
|
+
}
|
|
27
|
+
const n = parseInt(token, 10)
|
|
28
|
+
if (n < spec.min || n > spec.max) {
|
|
29
|
+
throw new Error(`${spec.name} value ${n} is out of range (${spec.min}-${spec.max})`)
|
|
30
|
+
}
|
|
31
|
+
return n
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Parse one comma-separated part of a cron field into a matcher; throws on invalid syntax. */
|
|
35
|
+
function parsePart(part: string, spec: FieldSpec): Matcher {
|
|
36
|
+
if (part === '') {
|
|
37
|
+
throw new Error(`${spec.name} field has an empty entry`)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Step: base/step, where base is '*', a single number, or a range a-b
|
|
41
|
+
if (part.includes('/')) {
|
|
42
|
+
const pieces = part.split('/')
|
|
43
|
+
if (pieces.length !== 2) {
|
|
44
|
+
throw new Error(`${spec.name} field has invalid step expression "${part}"`)
|
|
45
|
+
}
|
|
46
|
+
const [base, stepStr] = pieces
|
|
47
|
+
if (!/^\d+$/.test(stepStr) || parseInt(stepStr, 10) <= 0) {
|
|
48
|
+
throw new Error(`${spec.name} field has invalid step "/${stepStr}" (must be a positive integer)`)
|
|
49
|
+
}
|
|
50
|
+
const step = parseInt(stepStr, 10)
|
|
51
|
+
|
|
52
|
+
let from = spec.min
|
|
53
|
+
let to = spec.max
|
|
54
|
+
if (base !== '*') {
|
|
55
|
+
if (base.includes('-')) {
|
|
56
|
+
const range = base.split('-')
|
|
57
|
+
if (range.length !== 2) {
|
|
58
|
+
throw new Error(`${spec.name} field has invalid range "${base}"`)
|
|
59
|
+
}
|
|
60
|
+
from = parseNumber(range[0], spec)
|
|
61
|
+
to = parseNumber(range[1], spec)
|
|
62
|
+
if (from > to) {
|
|
63
|
+
throw new Error(`${spec.name} range ${from}-${to} is inverted (start must be <= end)`)
|
|
64
|
+
}
|
|
65
|
+
} else {
|
|
66
|
+
// a/n means "starting at a, every n" (open-ended), matching @nixxie-cms/jobs
|
|
67
|
+
from = parseNumber(base, spec)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return value => value >= from && value <= to && (value - from) % step === 0
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Range: a-b
|
|
74
|
+
if (part.includes('-')) {
|
|
75
|
+
const range = part.split('-')
|
|
76
|
+
if (range.length !== 2) {
|
|
77
|
+
throw new Error(`${spec.name} field has invalid range "${part}"`)
|
|
78
|
+
}
|
|
79
|
+
const from = parseNumber(range[0], spec)
|
|
80
|
+
const to = parseNumber(range[1], spec)
|
|
81
|
+
if (from > to) {
|
|
82
|
+
throw new Error(`${spec.name} range ${from}-${to} is inverted (start must be <= end)`)
|
|
83
|
+
}
|
|
84
|
+
return value => value >= from && value <= to
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Wildcard
|
|
88
|
+
if (part === '*') return () => true
|
|
89
|
+
|
|
90
|
+
// Literal
|
|
91
|
+
const literal = parseNumber(part, spec)
|
|
92
|
+
return value => value === literal
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function parseField(field: string, spec: FieldSpec): Matcher {
|
|
96
|
+
const matchers = field.split(',').map(part => parsePart(part, spec))
|
|
97
|
+
return value => matchers.some(m => m(value))
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
type CronMatcher = (date: Date) => boolean
|
|
101
|
+
|
|
102
|
+
/** Compile a 5-field cron expression into a Date matcher; throws with the reason when invalid. */
|
|
103
|
+
function compileCron(expr: string): CronMatcher {
|
|
104
|
+
if (typeof expr !== 'string' || expr.trim() === '') {
|
|
105
|
+
throw new Error('cron expression must be a non-empty string')
|
|
106
|
+
}
|
|
107
|
+
const fields = expr.trim().split(/\s+/)
|
|
108
|
+
if (fields.length !== 5) {
|
|
109
|
+
throw new Error(
|
|
110
|
+
`cron expression must have 5 fields (minute hour day-of-month month day-of-week), got ${fields.length}`
|
|
111
|
+
)
|
|
112
|
+
}
|
|
113
|
+
const [minute, hour, dom, month, dow] = fields.map((field, i) =>
|
|
114
|
+
parseField(field, FIELD_SPECS[i])
|
|
115
|
+
)
|
|
116
|
+
return date =>
|
|
117
|
+
minute(date.getMinutes()) &&
|
|
118
|
+
hour(date.getHours()) &&
|
|
119
|
+
dom(date.getDate()) &&
|
|
120
|
+
month(date.getMonth() + 1) &&
|
|
121
|
+
dow(date.getDay())
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Whether `expr` is a valid 5-field cron expression in the supported subset. */
|
|
125
|
+
export function isValidCron(expr: string): boolean {
|
|
126
|
+
try {
|
|
127
|
+
compileCron(expr)
|
|
128
|
+
return true
|
|
129
|
+
} catch {
|
|
130
|
+
return false
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Compute the next `count` (default 5) times `expr` will fire after `from` (default now), using
|
|
136
|
+
* the same minute-by-minute scan as @nixxie-cms/jobs. The scan is capped at 366 days ahead, so
|
|
137
|
+
* fewer (or zero) dates are returned for expressions that fire rarely or never (e.g. `0 0 31 2 *`).
|
|
138
|
+
* Throws when the expression is invalid.
|
|
139
|
+
*/
|
|
140
|
+
export function nextRuns(expr: string, count: number = 5, from?: Date): Date[] {
|
|
141
|
+
const matcher = compileCron(expr)
|
|
142
|
+
const results: Date[] = []
|
|
143
|
+
const start = new Date(from?.getTime() ?? Date.now())
|
|
144
|
+
start.setSeconds(0, 0)
|
|
145
|
+
const limit = 366 * 24 * 60 // cap the scan at ~366 days, covering yearly schedules
|
|
146
|
+
for (let i = 1; i <= limit && results.length < count; i++) {
|
|
147
|
+
const candidate = new Date(start.getTime() + i * 60_000)
|
|
148
|
+
if (matcher(candidate)) results.push(candidate)
|
|
149
|
+
}
|
|
150
|
+
return results
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Best-effort human description of a cron expression. Handles the common shapes — "every minute",
|
|
157
|
+
* "every N minutes", "daily at HH:MM", "weekly on <day> at HH:MM" and "monthly on day N at HH:MM"
|
|
158
|
+
* — and falls back to `cron: <expr>` for anything else (including invalid expressions).
|
|
159
|
+
*/
|
|
160
|
+
export function describeCron(expr: string): string {
|
|
161
|
+
const fallback = `cron: ${expr}`
|
|
162
|
+
if (!isValidCron(expr)) return fallback
|
|
163
|
+
|
|
164
|
+
const [minute, hour, dom, month, dow] = expr.trim().split(/\s+/)
|
|
165
|
+
|
|
166
|
+
if (minute === '*' && hour === '*' && dom === '*' && month === '*' && dow === '*') {
|
|
167
|
+
return 'every minute'
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const everyN = /^\*\/(\d+)$/.exec(minute)
|
|
171
|
+
if (everyN && hour === '*' && dom === '*' && month === '*' && dow === '*') {
|
|
172
|
+
const n = parseInt(everyN[1], 10)
|
|
173
|
+
return n === 1 ? 'every minute' : `every ${n} minutes`
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (/^\d+$/.test(minute) && /^\d+$/.test(hour) && month === '*') {
|
|
177
|
+
const time = `${hour.padStart(2, '0')}:${minute.padStart(2, '0')}`
|
|
178
|
+
if (dom === '*' && dow === '*') return `daily at ${time}`
|
|
179
|
+
if (dom === '*' && /^\d+$/.test(dow)) return `weekly on ${WEEKDAYS[parseInt(dow, 10)]} at ${time}`
|
|
180
|
+
if (dow === '*' && /^\d+$/.test(dom)) return `monthly on day ${parseInt(dom, 10)} at ${time}`
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
return fallback
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ── Field type ──
|
|
187
|
+
|
|
188
|
+
export type CronFieldConfig<CollectionTypeInfo extends BaseCollectionTypeInfo> = Omit<
|
|
189
|
+
TextFieldConfig<CollectionTypeInfo>,
|
|
190
|
+
'validation'
|
|
191
|
+
> & {
|
|
192
|
+
validation?: {
|
|
193
|
+
/** Reject saving when no value is present. */
|
|
194
|
+
isRequired?: boolean
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* A cron-expression field storing a validated 5-field schedule (`minute hour dom month dow`).
|
|
200
|
+
* Built on the core `text` field. Supports the same subset as @nixxie-cms/jobs: `*`, literals,
|
|
201
|
+
* ranges, steps and comma-separated lists. Whitespace is normalised on save.
|
|
202
|
+
*/
|
|
203
|
+
export function cron<CollectionTypeInfo extends BaseCollectionTypeInfo>(
|
|
204
|
+
config: CronFieldConfig<CollectionTypeInfo> = {}
|
|
205
|
+
): FieldTypeFunc<CollectionTypeInfo> {
|
|
206
|
+
const { hooks, validation, ...rest } = config
|
|
207
|
+
|
|
208
|
+
return text<CollectionTypeInfo>({
|
|
209
|
+
...(rest as TextFieldConfig<CollectionTypeInfo>),
|
|
210
|
+
validation: { isRequired: validation?.isRequired },
|
|
211
|
+
ui: { description: 'Cron expression, e.g. */15 9-17 * * 1-5', ...rest.ui },
|
|
212
|
+
hooks: {
|
|
213
|
+
...hooks,
|
|
214
|
+
resolveInput: (args: any) => {
|
|
215
|
+
const v = args.resolvedData[args.fieldKey]
|
|
216
|
+
return typeof v === 'string' ? v.trim().replace(/\s+/g, ' ') : v
|
|
217
|
+
},
|
|
218
|
+
validate: (args: any) => {
|
|
219
|
+
const { resolvedData, fieldKey, addValidationError, operation } = args
|
|
220
|
+
if (operation === 'delete') return
|
|
221
|
+
const value = resolvedData[fieldKey]
|
|
222
|
+
if (typeof value === 'string' && value.length > 0) {
|
|
223
|
+
try {
|
|
224
|
+
compileCron(value)
|
|
225
|
+
} catch (err) {
|
|
226
|
+
addValidationError(
|
|
227
|
+
`${fieldKey} is not a valid cron expression: ${err instanceof Error ? err.message : String(err)}`
|
|
228
|
+
)
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
})
|
|
234
|
+
}
|