forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcron.ts
More file actions
308 lines (271 loc) · 9.24 KB
/
cron.ts
File metadata and controls
308 lines (271 loc) · 9.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Minimal cron expression parsing and next-run calculation.
//
// Supports the standard 5-field cron subset:
// minute hour day-of-month month day-of-week
//
// Field syntax: wildcard, N, step (star-slash-N), range (N-M), list (N,M,...).
// No L, W, ?, or name aliases. All times are interpreted in the process's
// local timezone — "0 9 * * *" means 9am wherever the CLI is running.
export type CronFields = {
minute: number[]
hour: number[]
dayOfMonth: number[]
month: number[]
dayOfWeek: number[]
}
type FieldRange = { min: number; max: number }
const FIELD_RANGES: FieldRange[] = [
{ min: 0, max: 59 }, // minute
{ min: 0, max: 23 }, // hour
{ min: 1, max: 31 }, // dayOfMonth
{ min: 1, max: 12 }, // month
{ min: 0, max: 6 }, // dayOfWeek (0=Sunday; 7 accepted as Sunday alias)
]
// Parse a single cron field into a sorted array of matching values.
// Supports: wildcard, N, star-slash-N (step), N-M (range), and comma-lists.
// Returns null if invalid.
function expandField(field: string, range: FieldRange): number[] | null {
const { min, max } = range
const out = new Set<number>()
for (const part of field.split(',')) {
// wildcard or star-slash-N
const stepMatch = part.match(/^\*(?:\/(\d+))?$/)
if (stepMatch) {
const step = stepMatch[1] ? parseInt(stepMatch[1], 10) : 1
if (step < 1) return null
for (let i = min; i <= max; i += step) out.add(i)
continue
}
// N-M or N-M/S
const rangeMatch = part.match(/^(\d+)-(\d+)(?:\/(\d+))?$/)
if (rangeMatch) {
const lo = parseInt(rangeMatch[1]!, 10)
const hi = parseInt(rangeMatch[2]!, 10)
const step = rangeMatch[3] ? parseInt(rangeMatch[3], 10) : 1
// dayOfWeek: accept 7 as Sunday alias in ranges (e.g. 5-7 = Fri,Sat,Sun → [5,6,0])
const isDow = min === 0 && max === 6
const effMax = isDow ? 7 : max
if (lo > hi || step < 1 || lo < min || hi > effMax) return null
for (let i = lo; i <= hi; i += step) {
out.add(isDow && i === 7 ? 0 : i)
}
continue
}
// plain N
const singleMatch = part.match(/^\d+$/)
if (singleMatch) {
let n = parseInt(part, 10)
// dayOfWeek: accept 7 as Sunday alias → 0
if (min === 0 && max === 6 && n === 7) n = 0
if (n < min || n > max) return null
out.add(n)
continue
}
return null
}
if (out.size === 0) return null
return Array.from(out).sort((a, b) => a - b)
}
/**
* Parse a 5-field cron expression into expanded number arrays.
* Returns null if invalid or unsupported syntax.
*/
export function parseCronExpression(expr: string): CronFields | null {
const parts = expr.trim().split(/\s+/)
if (parts.length !== 5) return null
const expanded: number[][] = []
for (let i = 0; i < 5; i++) {
const result = expandField(parts[i]!, FIELD_RANGES[i]!)
if (!result) return null
expanded.push(result)
}
return {
minute: expanded[0]!,
hour: expanded[1]!,
dayOfMonth: expanded[2]!,
month: expanded[3]!,
dayOfWeek: expanded[4]!,
}
}
/**
* Compute the next Date strictly after `from` that matches the cron fields,
* using the process's local timezone. Walks forward minute-by-minute. Bounded
* at 366 days; returns null if no match (impossible for valid cron, but
* satisfies the type).
*
* Standard cron semantics: when both dayOfMonth and dayOfWeek are constrained
* (neither is the full range), a date matches if EITHER matches.
*
* DST: fixed-hour crons targeting a spring-forward gap (e.g. `30 2 * * *`
* in a US timezone) skip the transition day — the gap hour never appears
* in local time, so the hour-set check fails and the loop moves on.
* Wildcard-hour crons (`30 * * * *`) fire at the first valid minute after
* the gap. Fall-back repeats fire once (the step-forward logic jumps past
* the second occurrence). This matches vixie-cron behavior.
*/
export function computeNextCronRun(
fields: CronFields,
from: Date,
): Date | null {
const minuteSet = new Set(fields.minute)
const hourSet = new Set(fields.hour)
const domSet = new Set(fields.dayOfMonth)
const monthSet = new Set(fields.month)
const dowSet = new Set(fields.dayOfWeek)
// Is the field wildcarded (full range)?
const domWild = fields.dayOfMonth.length === 31
const dowWild = fields.dayOfWeek.length === 7
// Round up to the next whole minute (strictly after `from`)
const t = new Date(from.getTime())
t.setSeconds(0, 0)
t.setMinutes(t.getMinutes() + 1)
const maxIter = 366 * 24 * 60
for (let i = 0; i < maxIter; i++) {
const month = t.getMonth() + 1
if (!monthSet.has(month)) {
// Jump to start of next month
t.setMonth(t.getMonth() + 1, 1)
t.setHours(0, 0, 0, 0)
continue
}
const dom = t.getDate()
const dow = t.getDay()
// When both dom/dow are constrained, either match is sufficient (OR semantics)
const dayMatches =
domWild && dowWild
? true
: domWild
? dowSet.has(dow)
: dowWild
? domSet.has(dom)
: domSet.has(dom) || dowSet.has(dow)
if (!dayMatches) {
// Jump to start of next day
t.setDate(t.getDate() + 1)
t.setHours(0, 0, 0, 0)
continue
}
if (!hourSet.has(t.getHours())) {
t.setHours(t.getHours() + 1, 0, 0, 0)
continue
}
if (!minuteSet.has(t.getMinutes())) {
t.setMinutes(t.getMinutes() + 1)
continue
}
return t
}
return null
}
// --- cronToHuman ------------------------------------------------------------
// Intentionally narrow: covers common patterns; falls through to the raw cron
// string for anything else. The `utc` option exists for CCR remote triggers
// (agents-platform.tsx), which run on servers and always use UTC cron strings
// — that path translates UTC→local for display and needs midnight-crossing
// logic for the weekday case. Local scheduled tasks (the default) need neither.
const DAY_NAMES = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
]
function formatLocalTime(minute: number, hour: number): string {
// January 1 — no DST gap anywhere. Using `new Date()` (today) would roll
// 2am→3am on the one spring-forward day per year.
const d = new Date(2000, 0, 1, hour, minute)
return d.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })
}
function formatUtcTimeAsLocal(minute: number, hour: number): string {
// Create a date in UTC and format in user's local timezone
const d = new Date()
d.setUTCHours(hour, minute, 0, 0)
return d.toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
timeZoneName: 'short',
})
}
export function cronToHuman(cron: string, opts?: { utc?: boolean }): string {
const utc = opts?.utc ?? false
const parts = cron.trim().split(/\s+/)
if (parts.length !== 5) return cron
const [minute, hour, dayOfMonth, month, dayOfWeek] = parts as [
string,
string,
string,
string,
string,
]
// Every N minutes: step/N * * * *
const everyMinMatch = minute.match(/^\*\/(\d+)$/)
if (
everyMinMatch &&
hour === '*' &&
dayOfMonth === '*' &&
month === '*' &&
dayOfWeek === '*'
) {
const n = parseInt(everyMinMatch[1]!, 10)
return n === 1 ? 'Every minute' : `Every ${n} minutes`
}
// Every hour: 0 * * * *
if (
minute.match(/^\d+$/) &&
hour === '*' &&
dayOfMonth === '*' &&
month === '*' &&
dayOfWeek === '*'
) {
const m = parseInt(minute, 10)
if (m === 0) return 'Every hour'
return `Every hour at :${m.toString().padStart(2, '0')}`
}
// Every N hours: 0 step/N * * *
const everyHourMatch = hour.match(/^\*\/(\d+)$/)
if (
minute.match(/^\d+$/) &&
everyHourMatch &&
dayOfMonth === '*' &&
month === '*' &&
dayOfWeek === '*'
) {
const n = parseInt(everyHourMatch[1]!, 10)
const m = parseInt(minute, 10)
const suffix = m === 0 ? '' : ` at :${m.toString().padStart(2, '0')}`
return n === 1 ? `Every hour${suffix}` : `Every ${n} hours${suffix}`
}
// --- Remaining cases reference hour+minute: branch on utc ----------------
if (!minute.match(/^\d+$/) || !hour.match(/^\d+$/)) return cron
const m = parseInt(minute, 10)
const h = parseInt(hour, 10)
const fmtTime = utc ? formatUtcTimeAsLocal : formatLocalTime
// Daily at specific time: M H * * *
if (dayOfMonth === '*' && month === '*' && dayOfWeek === '*') {
return `Every day at ${fmtTime(m, h)}`
}
// Specific day of week: M H * * D
if (dayOfMonth === '*' && month === '*' && dayOfWeek.match(/^\d$/)) {
const dayIndex = parseInt(dayOfWeek, 10) % 7 // normalize 7 (Sunday alias) -> 0
let dayName: string | undefined
if (utc) {
// UTC day+time may land on a different local day (midnight crossing).
// Compute the actual local weekday by constructing the UTC instant.
const ref = new Date()
const daysToAdd = (dayIndex - ref.getUTCDay() + 7) % 7
ref.setUTCDate(ref.getUTCDate() + daysToAdd)
ref.setUTCHours(h, m, 0, 0)
dayName = DAY_NAMES[ref.getDay()]
} else {
dayName = DAY_NAMES[dayIndex]
}
if (dayName) return `Every ${dayName} at ${fmtTime(m, h)}`
}
// Weekdays: M H * * 1-5
if (dayOfMonth === '*' && month === '*' && dayOfWeek === '1-5') {
return `Weekdays at ${fmtTime(m, h)}`
}
return cron
}