@xiangyixie/dsh-superagent 0.12.0 → 0.14.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/lib/cron.js ADDED
@@ -0,0 +1,387 @@
1
+ /**
2
+ * Zero-dependency cron parsing for scheduled runs.
3
+ *
4
+ * The scheduler needs two things from this module: a parse that fails when the
5
+ * plan is created (naming the field, not just "invalid cron"), and the next
6
+ * instant a local clock would reach, in a time zone that may be the caller's and
7
+ * not the host's. Both are computed with the runtime's own `Intl` data, so a
8
+ * plan does not depend on a package being installed next to the plugin.
9
+ *
10
+ * Supported: the standard five fields (minute hour day-of-month month
11
+ * day-of-week), star, star-with-step, ranges `a-b`, ranges with a step, lists
12
+ * `a,b,c`, three-letter month and weekday names, and `0`/`7` for Sunday. When
13
+ * both day-of-month and day-of-week are restricted, a day matching either one
14
+ * is selected, which is what Vixie cron does.
15
+ *
16
+ * Not supported, and refused at create time instead of at 03:00: a seconds
17
+ * field (six fields), `@daily`-style macros, and the Quartz extensions `L`,
18
+ * `W`, `#`, and `?`. A year field (seven fields) is also refused.
19
+ *
20
+ * @module dsh-superagent/cron
21
+ */
22
+
23
+ /** Fields in order, with the bounds a value must fall inside. */
24
+ const FIELDS = [
25
+ { name: 'minute', min: 0, max: 59, aliases: null },
26
+ { name: 'hour', min: 0, max: 23, aliases: null },
27
+ { name: 'day-of-month', min: 1, max: 31, aliases: null },
28
+ { name: 'month', min: 1, max: 12, aliases: { JAN: 1, FEB: 2, MAR: 3, APR: 4, MAY: 5, JUN: 6, JUL: 7, AUG: 8, SEP: 9, OCT: 10, NOV: 11, DEC: 12 } },
29
+ { name: 'day-of-week', min: 0, max: 7, aliases: { SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6 } },
30
+ ]
31
+
32
+ /** A create-time cron problem, carrying which field (1-based) was wrong. */
33
+ export class CronError extends Error {
34
+ /**
35
+ * @param {string} message - what is wrong, in one actionable sentence.
36
+ * @param {{ field?: number | null, fieldName?: string | null }} [where] - field position and name.
37
+ */
38
+ constructor(message, { field = null, fieldName = null } = {}) {
39
+ super(message)
40
+ this.name = 'CronError'
41
+ this.field = field
42
+ this.fieldName = fieldName
43
+ }
44
+ }
45
+
46
+ const MAX_SEARCH_DAYS = 366 * 8
47
+ const formatters = new Map()
48
+
49
+ /** Resolve one token (number or three-letter name) to its numeric value. */
50
+ function valueOf(token, spec, index) {
51
+ const text = String(token).toUpperCase()
52
+ const field = index
53
+ if (spec.aliases && Object.hasOwn(spec.aliases, text)) return spec.aliases[text]
54
+ if (!/^\d+$/.test(text)) {
55
+ throw new CronError(
56
+ `cron field ${field} (${spec.name}) has "${token}", which is not a number`
57
+ + `${spec.aliases ? ' or a three-letter name' : ''}`,
58
+ { field, fieldName: spec.name },
59
+ )
60
+ }
61
+ const value = Number(text)
62
+ if (value < spec.min || value > spec.max) {
63
+ throw new CronError(
64
+ `cron field ${field} (${spec.name}) "${token}" is out of range ${spec.min}-${spec.max}`,
65
+ { field, fieldName: spec.name },
66
+ )
67
+ }
68
+ return value
69
+ }
70
+
71
+ /** Parse `*`, `a`, `a-b`, or any of those with `/n`, into sorted values. */
72
+ function parseItem(item, spec, index) {
73
+ const text = item.trim()
74
+ if (!text) {
75
+ throw new CronError(`cron field ${index} (${spec.name}) has an empty list item`, { field: index, fieldName: spec.name })
76
+ }
77
+ // `?` is Quartz for "no specific value", and `L`/`W`/`#` are Quartz
78
+ // extensions. Refusing them by name is the difference between "your cron is
79
+ // wrong" and "your cron is a different dialect".
80
+ if (text.includes('?')) {
81
+ throw new CronError(`cron field ${index} (${spec.name}) uses "?", which is not supported; use "*" instead`, {
82
+ field: index,
83
+ fieldName: spec.name,
84
+ })
85
+ }
86
+ if (/^[LW]$/i.test(text) || (/[LW#]/i.test(text) && !/^[A-Za-z]+$/.test(text))) {
87
+ throw new CronError(
88
+ `cron field ${index} (${spec.name}) uses "${text}"; L, W and # are not supported. `
89
+ + 'This parser supports only *, lists, ranges and /n steps',
90
+ { field: index, fieldName: spec.name },
91
+ )
92
+ }
93
+ const [base, stepText, extra] = text.split('/')
94
+ if (extra !== undefined) {
95
+ throw new CronError(`cron field ${index} (${spec.name}) has more than one "/" step`, { field: index, fieldName: spec.name })
96
+ }
97
+ let step = 1
98
+ if (stepText !== undefined) {
99
+ if (!/^\d+$/.test(stepText) || Number(stepText) < 1) {
100
+ throw new CronError(`cron field ${index} (${spec.name}) has step "${stepText}"; a step must be a number of at least 1`, {
101
+ field: index,
102
+ fieldName: spec.name,
103
+ })
104
+ }
105
+ step = Number(stepText)
106
+ }
107
+ if (base === '*') {
108
+ return { values: expand(spec.min, spec.max, step), restricted: step !== 1 }
109
+ }
110
+ if (base === '' || base.includes('*')) {
111
+ throw new CronError(`cron field ${index} (${spec.name}) has "${text}"; "*" may only be the whole field or "*/n"`, {
112
+ field: index,
113
+ fieldName: spec.name,
114
+ })
115
+ }
116
+ const range = base.split('-')
117
+ if (range.length === 1) {
118
+ const value = valueOf(range[0], spec, index)
119
+ if (stepText !== undefined) {
120
+ // "5/10" is not a range in cron; reject it instead of inventing one.
121
+ throw new CronError(`cron field ${index} (${spec.name}) uses "${text}"; a step needs a range such as "5-20/2"`, {
122
+ field: index,
123
+ fieldName: spec.name,
124
+ })
125
+ }
126
+ return { values: [value], restricted: true }
127
+ }
128
+ if (range.length === 2) {
129
+ const from = valueOf(range[0], spec, index)
130
+ const to = valueOf(range[1], spec, index)
131
+ if (from > to) {
132
+ throw new CronError(`cron field ${index} (${spec.name}) range "${base}" runs backwards`, {
133
+ field: index,
134
+ fieldName: spec.name,
135
+ })
136
+ }
137
+ return { values: expand(from, to, step), restricted: true }
138
+ }
139
+ throw new CronError(`cron field ${index} (${spec.name}) has more than one "-"`, { field: index, fieldName: spec.name })
140
+ }
141
+
142
+ function expand(from, to, step) {
143
+ const values = []
144
+ for (let value = from; value <= to; value += step) values.push(value)
145
+ return values
146
+ }
147
+
148
+ /**
149
+ * Parse one five-field cron expression.
150
+ *
151
+ * @param {string} expression - e.g. `"0 9 * * MON-FRI"`.
152
+ * @returns {Readonly<object>} parsed spec, accepted by `nextCronTime`.
153
+ * @throws {CronError} naming the 1-based field that is wrong.
154
+ */
155
+ export function parseCron(expression) {
156
+ const text = String(expression ?? '').trim()
157
+ if (!text) {
158
+ throw new CronError('cron is empty; expected 5 fields: minute hour day-of-month month day-of-week', {
159
+ field: 1,
160
+ fieldName: 'minute',
161
+ })
162
+ }
163
+ if (text.startsWith('@')) {
164
+ throw new CronError(
165
+ `cron macro "${text}" is not supported; write the five fields instead (e.g. "0 9 * * *" for 09:00 daily)`,
166
+ { field: 1, fieldName: 'minute' },
167
+ )
168
+ }
169
+ const parts = text.split(/\s+/)
170
+ if (parts.length !== 5) {
171
+ const detail = parts.length === 6
172
+ ? 'got 6; a seconds field is not supported — the first field is minutes'
173
+ : parts.length === 7
174
+ ? 'got 7; a year field is not supported'
175
+ : `got ${parts.length}`
176
+ throw new CronError(`cron needs 5 fields (minute hour day-of-month month day-of-week) but ${detail}`, {
177
+ field: 1,
178
+ fieldName: 'minute',
179
+ })
180
+ }
181
+ const parsed = parts.map((part, index) => {
182
+ const field = index + 1
183
+ const spec = FIELDS[index]
184
+ if (part.includes('?')) {
185
+ throw new CronError(`cron field ${field} (${spec.name}) uses "?", which is not supported; use "*" instead`, {
186
+ field,
187
+ fieldName: spec.name,
188
+ })
189
+ }
190
+ const values = new Set()
191
+ let restricted = false
192
+ for (const item of part.split(',')) {
193
+ const result = parseItem(item, spec, field)
194
+ for (const value of result.values) values.add(value)
195
+ if (result.restricted) restricted = true
196
+ }
197
+ if (values.size === 0) {
198
+ throw new CronError(`cron field ${field} (${spec.name}) matches no value`, { field, fieldName: spec.name })
199
+ }
200
+ const list = [...values].sort((a, b) => a - b)
201
+ // 0 and 7 both mean Sunday; keeping both would make a range look larger than
202
+ // it is and would report two matches for one day.
203
+ if (spec.name === 'day-of-week') {
204
+ if (values.has(7)) {
205
+ values.delete(7)
206
+ values.add(0)
207
+ }
208
+ return { values: [...values].sort((a, b) => a - b), restricted: part !== '*' }
209
+ }
210
+ return { values: list, restricted: part !== '*' }
211
+ })
212
+ return Object.freeze({
213
+ expression: text,
214
+ minutes: Object.freeze(parsed[0].values),
215
+ hours: Object.freeze(parsed[1].values),
216
+ daysOfMonth: Object.freeze(parsed[2].values),
217
+ months: Object.freeze(parsed[3].values),
218
+ daysOfWeek: Object.freeze(parsed[4].values),
219
+ domRestricted: parsed[2].restricted,
220
+ dowRestricted: parsed[4].restricted,
221
+ })
222
+ }
223
+
224
+ /**
225
+ * Refuse an unknown time zone at create time.
226
+ *
227
+ * @param {string} timeZone - IANA name such as `Asia/Shanghai`.
228
+ * @throws {CronError} when the runtime cannot resolve it.
229
+ */
230
+ export function validateTimeZone(timeZone) {
231
+ const name = String(timeZone ?? '').trim()
232
+ if (!name) throw new CronError('timeZone is empty; use an IANA name such as "Asia/Shanghai" or "UTC"')
233
+ try {
234
+ formatterFor(name)
235
+ } catch {
236
+ throw new CronError(
237
+ `timeZone "${name}" is not known to this Node runtime; use an IANA name such as "Asia/Shanghai"`,
238
+ )
239
+ }
240
+ return name
241
+ }
242
+
243
+ function formatterFor(timeZone) {
244
+ let formatter = formatters.get(timeZone)
245
+ if (!formatter) {
246
+ formatter = new Intl.DateTimeFormat('en-US', {
247
+ timeZone,
248
+ year: 'numeric',
249
+ month: '2-digit',
250
+ day: '2-digit',
251
+ hour: '2-digit',
252
+ minute: '2-digit',
253
+ second: '2-digit',
254
+ hourCycle: 'h23',
255
+ })
256
+ formatters.set(timeZone, formatter)
257
+ }
258
+ return formatter
259
+ }
260
+
261
+ /**
262
+ * Local calendar parts of one instant in a time zone.
263
+ *
264
+ * @param {number} ms - epoch milliseconds.
265
+ * @param {string} timeZone - IANA zone.
266
+ * @returns {{ year: number, month: number, day: number, hour: number, minute: number, second: number, weekday: number }}
267
+ */
268
+ export function zonedParts(ms, timeZone) {
269
+ const parts = {}
270
+ for (const part of formatterFor(timeZone).formatToParts(new Date(ms))) {
271
+ if (part.type !== 'literal') parts[part.type] = part.value
272
+ }
273
+ const year = Number(parts.year)
274
+ const month = Number(parts.month)
275
+ const day = Number(parts.day)
276
+ const hour = Number(parts.hour)
277
+ const minute = Number(parts.minute)
278
+ const second = Number(parts.second)
279
+ return {
280
+ year,
281
+ month,
282
+ day,
283
+ hour,
284
+ minute,
285
+ second,
286
+ weekday: new Date(Date.UTC(year, month - 1, day)).getUTCDay(),
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Epoch of one local wall-clock time, or null when that time does not exist.
292
+ *
293
+ * A time can be missing on the spring-forward day. Cron semantics run the job
294
+ * at the next existing minute, so null is the honest answer and the caller
295
+ * moves on instead of inventing a shifted time. Ambiguous times on the fall-back
296
+ * day resolve to the earlier offset, which is what a "next run" should pick.
297
+ *
298
+ * @param {{ year: number, month: number, day: number, hour: number, minute: number }} wanted - local parts.
299
+ * @param {string} timeZone - IANA zone.
300
+ * @returns {number | null} epoch milliseconds, or null for a non-existent local time.
301
+ */
302
+ export function localToEpoch(wanted, timeZone) {
303
+ const desired = Date.UTC(wanted.year, wanted.month - 1, wanted.day, wanted.hour, wanted.minute)
304
+ let guess = desired
305
+ for (let attempt = 0; attempt < 3; attempt++) {
306
+ const actual = zonedParts(guess, timeZone)
307
+ const actualMs = Date.UTC(actual.year, actual.month - 1, actual.day, actual.hour, actual.minute)
308
+ const delta = desired - actualMs
309
+ if (delta === 0) break
310
+ guess += delta
311
+ }
312
+ const final = zonedParts(guess, timeZone)
313
+ if (final.year !== wanted.year || final.month !== wanted.month || final.day !== wanted.day
314
+ || final.hour !== wanted.hour || final.minute !== wanted.minute) {
315
+ return null
316
+ }
317
+ return guess
318
+ }
319
+
320
+ function matchesDay(spec, parts) {
321
+ if (!spec.months.includes(parts.month)) return false
322
+ const dom = spec.daysOfMonth.includes(parts.day)
323
+ const dow = spec.daysOfWeek.includes(parts.weekday)
324
+ if (spec.domRestricted && spec.dowRestricted) return dom || dow
325
+ if (spec.domRestricted) return dom
326
+ if (spec.dowRestricted) return dow
327
+ return true
328
+ }
329
+
330
+ function nextLocalDay(parts, timeZone) {
331
+ const midnight = Date.UTC(parts.year, parts.month - 1, parts.day)
332
+ const next = new Date(midnight)
333
+ next.setUTCDate(next.getUTCDate() + 1)
334
+ const wanted = {
335
+ year: next.getUTCFullYear(),
336
+ month: next.getUTCMonth() + 1,
337
+ day: next.getUTCDate(),
338
+ hour: 0,
339
+ minute: 0,
340
+ }
341
+ // Some zones skip midnight itself. Falling back to +24h keeps the search
342
+ // moving; the next iteration reads the real local parts from the clock.
343
+ return localToEpoch(wanted, timeZone) ?? localToEpoch({ ...wanted, hour: 1 }, timeZone) ?? Date.UTC(
344
+ wanted.year,
345
+ wanted.month - 1,
346
+ wanted.day,
347
+ 0,
348
+ 0,
349
+ )
350
+ }
351
+
352
+ /**
353
+ * The first instant strictly after `afterMs` that matches the expression.
354
+ *
355
+ * @param {object} spec - result of `parseCron`.
356
+ * @param {number} afterMs - epoch milliseconds; the boundary is exclusive.
357
+ * @param {string} timeZone - IANA zone the expression is written in.
358
+ * @returns {number} epoch milliseconds of the next match.
359
+ * @throws {CronError} when nothing matches within eight years (impossible dates such as 30 February).
360
+ */
361
+ export function nextCronTime(spec, afterMs, timeZone) {
362
+ validateTimeZone(timeZone)
363
+ if (!Number.isFinite(afterMs)) throw new CronError('nextCronTime needs a finite epoch millisecond value')
364
+ let cursor = Math.floor(afterMs / 60000) * 60000
365
+ if (cursor <= afterMs) cursor += 60000
366
+ let day = zonedParts(cursor, timeZone)
367
+ for (let days = 0; days <= MAX_SEARCH_DAYS; days++) {
368
+ if (!matchesDay(spec, day)) {
369
+ cursor = nextLocalDay(day, timeZone)
370
+ day = zonedParts(cursor, timeZone)
371
+ continue
372
+ }
373
+ for (const hour of spec.hours) {
374
+ if (hour < day.hour) continue
375
+ for (const minute of spec.minutes) {
376
+ if (hour === day.hour && minute < day.minute) continue
377
+ const at = localToEpoch({ year: day.year, month: day.month, day: day.day, hour, minute }, timeZone)
378
+ if (at !== null && at > afterMs) return at
379
+ }
380
+ }
381
+ cursor = nextLocalDay(day, timeZone)
382
+ day = zonedParts(cursor, timeZone)
383
+ }
384
+ throw new CronError(
385
+ `cron "${spec.expression}" has no matching time within 8 years; check the day-of-month and month combination`,
386
+ )
387
+ }