croner 5.7.1-dev.0 → 6.0.0-dev.1

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/types/croner.d.ts CHANGED
@@ -1,4 +1,108 @@
1
- export default Cron;
1
+ export type TimePoint = {
2
+ /**
3
+ * - 1970--
4
+ */
5
+ y: number;
6
+ /**
7
+ * - 1-12
8
+ */
9
+ m: number;
10
+ /**
11
+ * - 1-31
12
+ */
13
+ d: number;
14
+ /**
15
+ * - 0-24
16
+ */
17
+ h: number;
18
+ /**
19
+ * - 0-60 Minute
20
+ */
21
+ i: number;
22
+ /**
23
+ * - 0-60
24
+ */
25
+ s: number;
26
+ /**
27
+ * - Time zone in IANA database format 'Europe/Stockholm'
28
+ */
29
+ tz: string;
30
+ };
31
+ export type CatchCallbackFn = (e: unknown, job: Cron) => any;
32
+ export type ProtectCallbackFn = (job: Cron) => any;
33
+ /**
34
+ * - Cron scheduler options
35
+ */
36
+ export type CronOptions = {
37
+ /**
38
+ * - Name of a job
39
+ */
40
+ name?: string;
41
+ /**
42
+ * - Job is paused
43
+ */
44
+ paused?: boolean;
45
+ /**
46
+ * - Job is about to be killed or killed
47
+ */
48
+ kill?: boolean;
49
+ /**
50
+ * - Continue exection even if a unhandled error is thrown by triggered function
51
+ * - If set to a function, execute function on catching the error.
52
+ */
53
+ catch?: boolean | CatchCallbackFn;
54
+ /**
55
+ * - Abort job instantly if nothing else keeps the event loop running.
56
+ */
57
+ unref?: boolean;
58
+ /**
59
+ * - Maximum nuber of executions
60
+ */
61
+ maxRuns?: number;
62
+ /**
63
+ * - Minimum interval between executions, in seconds
64
+ */
65
+ interval?: number;
66
+ /**
67
+ * - Skip current run if job is already running
68
+ */
69
+ protect?: boolean | ProtectCallbackFn;
70
+ /**
71
+ * - When to start running
72
+ */
73
+ startAt?: string | Date;
74
+ /**
75
+ * - When to stop running
76
+ */
77
+ stopAt?: string | Date;
78
+ /**
79
+ * - Time zone in Europe/Stockholm format
80
+ */
81
+ timezone?: string;
82
+ /**
83
+ * - Offset from UTC in minutes
84
+ */
85
+ utcOffset?: number;
86
+ /**
87
+ * - Combine day-of-month and day-of-week using true = OR, false = AND. Default is true = OR.
88
+ */
89
+ legacyMode?: boolean;
90
+ /**
91
+ * - Used to pass any object to scheduled function
92
+ */
93
+ context?: unknown;
94
+ };
95
+ /**
96
+ * Name for each part of the cron pattern
97
+ */
98
+ export type CronPatternPart = ("second" | "minute" | "hour" | "day" | "month" | "dayOfWeek");
99
+ /**
100
+ * Offset, 0 or -1.
101
+ *
102
+ * 0 offset is used for seconds,minutes and hours as they start on 1.
103
+ * -1 on days and months, as they start on 0
104
+ */
105
+ export type CronIndexOffset = number;
2
106
  /**
3
107
  * Cron entrypoint
4
108
  *
@@ -20,13 +124,20 @@ export class Cron {
20
124
  * @returns {Cron}
21
125
  */
22
126
  constructor(pattern: string | Date, fnOrOptions1?: CronOptions | Function, fnOrOptions2?: CronOptions | Function);
23
- /** @type {string|undefined} */
24
- name: string | undefined;
25
- /** @type {CronOptions} */
26
- options: CronOptions;
27
- /** @type {boolean} */
28
- blocking: boolean;
29
- once: CronDate;
127
+ /**
128
+ * @public
129
+ * @type {string|undefined} */
130
+ public name: string | undefined;
131
+ /**
132
+ * @public
133
+ * @type {CronOptions} */
134
+ public options: CronOptions;
135
+ /**
136
+ * Encapsulate all internal states in an object.
137
+ * Duplicate all options that can change to internal states, for example maxRuns and paused.
138
+ * @private
139
+ */
140
+ private _states;
30
141
  pattern: CronPattern;
31
142
  fn: Function | CronOptions;
32
143
  /**
@@ -111,10 +222,7 @@ export class Cron {
111
222
  * @returns {Cron}
112
223
  */
113
224
  public schedule(func: Function, partial?: Date): Cron;
114
- currentTimeout: number;
115
225
  private _trigger;
116
- runstarted: CronDate;
117
- previousrun: CronDate;
118
226
  /**
119
227
  * Trigger a run manually
120
228
  * @public
@@ -134,6 +242,162 @@ export namespace Cron {
134
242
  * @type {Cron[]}
135
243
  */
136
244
  export const scheduledJobs: Cron[];
137
- import { CronOptions } from "./options.js";
138
- import { CronDate } from "./date.js";
139
- import { CronPattern } from "./pattern.js";
245
+ /**
246
+ * @callback CatchCallbackFn
247
+ * @param {unknown} e
248
+ * @param {Cron} job
249
+ */
250
+ /**
251
+ * @callback ProtectCallbackFn
252
+ * @param {Cron} job
253
+ */
254
+ /**
255
+ * @typedef {Object} CronOptions - Cron scheduler options
256
+ * @property {string} [name] - Name of a job
257
+ * @property {boolean} [paused] - Job is paused
258
+ * @property {boolean} [kill] - Job is about to be killed or killed
259
+ * @property {boolean | CatchCallbackFn} [catch] - Continue exection even if a unhandled error is thrown by triggered function
260
+ * - If set to a function, execute function on catching the error.
261
+ * @property {boolean} [unref] - Abort job instantly if nothing else keeps the event loop running.
262
+ * @property {number} [maxRuns] - Maximum nuber of executions
263
+ * @property {number} [interval] - Minimum interval between executions, in seconds
264
+ * @property {boolean | ProtectCallbackFn} [protect] - Skip current run if job is already running
265
+ * @property {string | Date} [startAt] - When to start running
266
+ * @property {string | Date} [stopAt] - When to stop running
267
+ * @property {string} [timezone] - Time zone in Europe/Stockholm format
268
+ * @property {number} [utcOffset] - Offset from UTC in minutes
269
+ * @property {boolean} [legacyMode] - Combine day-of-month and day-of-week using true = OR, false = AND. Default is true = OR.
270
+ * @property {?} [context] - Used to pass any object to scheduled function
271
+ */
272
+ /**
273
+ * Internal function that validates options, and sets defaults
274
+ * @private
275
+ *
276
+ * @param {CronOptions} options
277
+ * @returns {CronOptions}
278
+ */
279
+ declare function CronOptions(options: CronOptions): CronOptions;
280
+ /**
281
+ * Name for each part of the cron pattern
282
+ * @typedef {("second" | "minute" | "hour" | "day" | "month" | "dayOfWeek")} CronPatternPart
283
+ */
284
+ /**
285
+ * Offset, 0 or -1.
286
+ *
287
+ * 0 offset is used for seconds,minutes and hours as they start on 1.
288
+ * -1 on days and months, as they start on 0
289
+ *
290
+ * @typedef {Number} CronIndexOffset
291
+ */
292
+ /**
293
+ * Create a CronPattern instance from pattern string ('* * * * * *')
294
+ * @constructor
295
+ * @param {string} pattern - Input pattern
296
+ * @param {string} timezone - Input timezone, used for '?'-substitution
297
+ */
298
+ declare function CronPattern(pattern: string, timezone: string): void;
299
+ declare class CronPattern {
300
+ /**
301
+ * Name for each part of the cron pattern
302
+ * @typedef {("second" | "minute" | "hour" | "day" | "month" | "dayOfWeek")} CronPatternPart
303
+ */
304
+ /**
305
+ * Offset, 0 or -1.
306
+ *
307
+ * 0 offset is used for seconds,minutes and hours as they start on 1.
308
+ * -1 on days and months, as they start on 0
309
+ *
310
+ * @typedef {Number} CronIndexOffset
311
+ */
312
+ /**
313
+ * Create a CronPattern instance from pattern string ('* * * * * *')
314
+ * @constructor
315
+ * @param {string} pattern - Input pattern
316
+ * @param {string} timezone - Input timezone, used for '?'-substitution
317
+ */
318
+ constructor(pattern: string, timezone: string);
319
+ pattern: string;
320
+ timezone: string;
321
+ second: any;
322
+ minute: any;
323
+ hour: any;
324
+ day: any;
325
+ month: any;
326
+ dayOfWeek: any;
327
+ lastDayOfMonth: boolean;
328
+ lastWeekdayOfMonth: boolean;
329
+ starDOM: boolean;
330
+ starDOW: boolean;
331
+ private parse;
332
+ private partToArray;
333
+ private throwAtIllegalCharacters;
334
+ private handleNumber;
335
+ private handleRangeWithStepping;
336
+ private handleRange;
337
+ private handleStepping;
338
+ private replaceAlphaDays;
339
+ private replaceAlphaMonths;
340
+ private handleNicknames;
341
+ }
342
+ /**
343
+ * Converts date to CronDate
344
+ * @constructor
345
+ *
346
+ * @param {CronDate|Date|string} [d] - Input date, if using string representation ISO 8001 (2015-11-24T19:40:00) local timezone is expected
347
+ * @param {string|number} [tz] - String representation of target timezone in Europe/Stockholm format, or a number representing offset in minutes.
348
+ */
349
+ declare function CronDate(d?: CronDate | Date | string, tz?: string | number): void;
350
+ declare class CronDate {
351
+ /**
352
+ * Converts date to CronDate
353
+ * @constructor
354
+ *
355
+ * @param {CronDate|Date|string} [d] - Input date, if using string representation ISO 8001 (2015-11-24T19:40:00) local timezone is expected
356
+ * @param {string|number} [tz] - String representation of target timezone in Europe/Stockholm format, or a number representing offset in minutes.
357
+ */
358
+ constructor(d?: CronDate | Date | string, tz?: string | number);
359
+ /**
360
+ * TimeZone
361
+ * @type {string|number|undefined}
362
+ */
363
+ tz: string | number | undefined;
364
+ private fromDate;
365
+ ms: number;
366
+ second: number;
367
+ minute: number;
368
+ hour: number;
369
+ day: number;
370
+ month: number;
371
+ year: number;
372
+ private fromCronDate;
373
+ private apply;
374
+ private fromString;
375
+ private findNext;
376
+ private recurse;
377
+ /**
378
+ * Increment to next run time
379
+ * @public
380
+ *
381
+ * @param {string} pattern - The pattern used to increment current state
382
+ * @param {CronOptions} options - Cron options used for incrementing
383
+ * @param {boolean} [hasPreviousRun] - If this run should adhere to minimum interval
384
+ * @return {CronDate|null} - Returns itthis for chaining, or null if increment wasnt possible
385
+ */
386
+ public increment(pattern: string, options: CronOptions, hasPreviousRun?: boolean): CronDate | null;
387
+ /**
388
+ * Convert current state back to a javascript Date()
389
+ * @public
390
+ *
391
+ * @param {boolean} internal - If this is an internal call
392
+ * @returns {Date}
393
+ */
394
+ public getDate(internal: boolean): Date;
395
+ /**
396
+ * Convert current state back to a javascript Date() and return UTC milliseconds
397
+ * @public
398
+ *
399
+ * @returns {Date}
400
+ */
401
+ public getTime(): Date;
402
+ }
403
+ export { Cron as default };
@@ -1 +0,0 @@
1
- (function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):(global=typeof globalThis!=="undefined"?globalThis:global||self,global.Cron=factory())})(this,function(){"use strict";function minitz(y,m,d,h,i,s,tz,throwOnInvalid){return minitz.fromTZ(minitz.tp(y,m,d,h,i,s,tz),throwOnInvalid)}minitz.fromTZISO=(localTimeStr,tz,throwOnInvalid)=>{return minitz.fromTZ(parseISOLocal(localTimeStr,tz),throwOnInvalid)};minitz.fromTZ=function(tp,throwOnInvalid){const inDate=new Date(Date.UTC(tp.y,tp.m-1,tp.d,tp.h,tp.i,tp.s)),offset=getTimezoneOffset(tp.tz,inDate),dateGuess=new Date(inDate.getTime()-offset),dateOffsGuess=getTimezoneOffset(tp.tz,dateGuess);if(dateOffsGuess-offset===0){return dateGuess}else{const dateGuess2=new Date(inDate.getTime()-dateOffsGuess),dateOffsGuess2=getTimezoneOffset(tp.tz,dateGuess2);if(dateOffsGuess2-dateOffsGuess===0){return dateGuess2}else if(!throwOnInvalid&&dateOffsGuess2-dateOffsGuess>0){return dateGuess2}else if(!throwOnInvalid){return dateGuess}else{throw new Error("Invalid date passed to fromTZ()")}}};minitz.toTZ=function(d,tzStr){const td=new Date(d.toLocaleString("sv-SE",{timeZone:tzStr}));return{y:td.getFullYear(),m:td.getMonth()+1,d:td.getDate(),h:td.getHours(),i:td.getMinutes(),s:td.getSeconds(),tz:tzStr}};minitz.tp=(y,m,d,h,i,s,tz)=>{return{y:y,m:m,d:d,h:h,i:i,s:s,tz:tz}};function getTimezoneOffset(timeZone,date=new Date){const tz=date.toLocaleString("en",{timeZone:timeZone,timeStyle:"long"}).split(" ").slice(-1)[0];const dateString=date.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${dateString} GMT`)-Date.parse(`${dateString} ${tz}`)}function parseISOLocal(dtStr,tz){const pd=new Date(Date.parse(dtStr));if(isNaN(pd)){throw new Error("minitz: Invalid ISO8601 passed to parser.")}const stringEnd=dtStr.substring(9);if(dtStr.includes("Z")||stringEnd.includes("-")||stringEnd.includes("+")){return minitz.tp(pd.getUTCFullYear(),pd.getUTCMonth()+1,pd.getUTCDate(),pd.getUTCHours(),pd.getUTCMinutes(),pd.getUTCSeconds(),"Etc/UTC")}else{return minitz.tp(pd.getFullYear(),pd.getMonth()+1,pd.getDate(),pd.getHours(),pd.getMinutes(),pd.getSeconds(),tz)}}minitz.minitz=minitz;function CronOptions(options){if(options===void 0){options={}}delete options.name;options.legacyMode=options.legacyMode===void 0?true:options.legacyMode;options.paused=options.paused===void 0?false:options.paused;options.maxRuns=options.maxRuns===void 0?Infinity:options.maxRuns;options.catch=options.catch===void 0?false:options.catch;options.interval=options.interval===void 0?0:parseInt(options.interval,10);options.utcOffset=options.utcOffset===void 0?void 0:parseInt(options.utcOffset,10);options.unref=options.unref===void 0?false:options.unref;options.kill=false;if(options.startAt){options.startAt=new CronDate(options.startAt,options.timezone)}if(options.stopAt){options.stopAt=new CronDate(options.stopAt,options.timezone)}if(options.interval!==null){if(isNaN(options.interval)){throw new Error("CronOptions: Supplied value for interval is not a number")}else if(options.interval<0){throw new Error("CronOptions: Supplied value for interval can not be negative")}}if(options.utcOffset!==void 0){if(isNaN(options.utcOffset)){throw new Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.")}else if(options.utcOffset<-870||options.utcOffset>870){throw new Error("CronOptions: utcOffset out of bounds.")}if(options.utcOffset!==void 0&&options.timezone){throw new Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}}if(options.unref!==true&&options.unref!==false){throw new Error("CronOptions: Unref should be either true, false or undefined(false).")}return options}const DaysOfMonth=[31,28,31,30,31,30,31,31,30,31,30,31];const RecursionSteps=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];function CronDate(d,tz){this.tz=tz;if(d&&d instanceof Date){if(!isNaN(d)){this.fromDate(d)}else{throw new TypeError("CronDate: Invalid date passed to CronDate constructor")}}else if(d===void 0){this.fromDate(new Date)}else if(d&&typeof d==="string"){this.fromString(d)}else if(d instanceof CronDate){this.fromCronDate(d)}else{throw new TypeError("CronDate: Invalid type ("+typeof d+") passed to CronDate constructor")}}CronDate.prototype.fromDate=function(inDate){if(this.tz!==void 0){if(typeof this.tz==="number"){this.ms=inDate.getUTCMilliseconds();this.second=inDate.getUTCSeconds();this.minute=inDate.getUTCMinutes()+this.tz;this.hour=inDate.getUTCHours();this.day=inDate.getUTCDate();this.month=inDate.getUTCMonth();this.year=inDate.getUTCFullYear();this.apply()}else{const d=minitz.toTZ(inDate,this.tz);this.ms=inDate.getMilliseconds();this.second=d.s;this.minute=d.i;this.hour=d.h;this.day=d.d;this.month=d.m-1;this.year=d.y}}else{this.ms=inDate.getMilliseconds();this.second=inDate.getSeconds();this.minute=inDate.getMinutes();this.hour=inDate.getHours();this.day=inDate.getDate();this.month=inDate.getMonth();this.year=inDate.getFullYear()}};CronDate.prototype.fromCronDate=function(d){this.tz=d.tz;this.year=d.year;this.month=d.month;this.day=d.day;this.hour=d.hour;this.minute=d.minute;this.second=d.second;this.ms=d.ms};CronDate.prototype.apply=function(){if(this.month>11||this.day>DaysOfMonth[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){const d=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));this.ms=d.getUTCMilliseconds();this.second=d.getUTCSeconds();this.minute=d.getUTCMinutes();this.hour=d.getUTCHours();this.day=d.getUTCDate();this.month=d.getUTCMonth();this.year=d.getUTCFullYear();return true}else{return false}};CronDate.prototype.fromString=function(str){return this.fromDate(minitz.fromTZISO(str,this.tz))};CronDate.prototype.findNext=function(options,target,pattern,offset){const originalTarget=this[target];let lastDayOfMonth;if(pattern.lastDayOfMonth){if(this.month!==1){lastDayOfMonth=DaysOfMonth[this.month]}else{lastDayOfMonth=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate()}}const fDomWeekDay=!pattern.starDOW&&target=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():undefined;for(let i=this[target]+offset;i<pattern[target].length;i++){let match=pattern[target][i];if(target==="day"&&pattern.lastDayOfMonth&&i-offset==lastDayOfMonth){match=true}if(target==="day"&&!pattern.starDOW){const dowMatch=pattern.dow[(fDomWeekDay+(i-offset-1))%7];if(options.legacyMode&&!pattern.starDOM){match=match||dowMatch}else{match=match&&dowMatch}}if(match){this[target]=i-offset;return originalTarget!==this[target]?2:1}}return 3};CronDate.prototype.recurse=function(pattern,options,doing){const res=this.findNext(options,RecursionSteps[doing][0],pattern,RecursionSteps[doing][2]);if(res>1){let resetLevel=doing+1;while(resetLevel<RecursionSteps.length){this[RecursionSteps[resetLevel][0]]=-RecursionSteps[resetLevel][2];resetLevel++}if(res===3){this[RecursionSteps[doing][1]]++;this[RecursionSteps[doing][0]]=-RecursionSteps[doing][2];this.apply();return this.recurse(pattern,options,0)}else if(this.apply()){return this.recurse(pattern,options,doing-1)}}doing+=1;if(doing>=RecursionSteps.length){return this}else if(this.year>=3e3){return null}else{return this.recurse(pattern,options,doing)}};CronDate.prototype.increment=function(pattern,options,hasPreviousRun){if(options.interval>1&&hasPreviousRun){this.second+=options.interval}else{this.second+=1}this.ms=0;this.apply();return this.recurse(pattern,options,0)};CronDate.prototype.getDate=function(internal){if(internal||this.tz===void 0&&this.utcOffset===void 0){return new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms)}else{if(typeof this.tz==="number"){return new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms))}else{return minitz(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz)}}};CronDate.prototype.getTime=function(){return this.getDate().getTime()};function CronPattern(pattern,timezone){this.pattern=pattern;this.timezone=timezone;this.second=Array(60).fill(0);this.minute=Array(60).fill(0);this.hour=Array(24).fill(0);this.day=Array(31).fill(0);this.month=Array(12).fill(0);this.dow=Array(8).fill(0);this.lastDayOfMonth=false;this.starDOM=false;this.starDOW=false;this.parse()}CronPattern.prototype.parse=function(){if(!(typeof this.pattern==="string"||this.pattern.constructor===String)){throw new TypeError("CronPattern: Pattern has to be of type string.")}if(this.pattern.indexOf("@")>=0)this.pattern=this.handleNicknames(this.pattern).trim();const parts=this.pattern.replace(/\s+/g," ").split(" ");if(parts.length<5||parts.length>6){throw new TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exacly five or six space separated parts required.")}if(parts.length===5){parts.unshift("0")}if(parts[3].indexOf("L")>=0){parts[3]=parts[3].replace("L","");this.lastDayOfMonth=true}if(parts[3]=="*"){this.starDOM=true}if(parts[4].length>=3)parts[4]=this.replaceAlphaMonths(parts[4]);if(parts[5].length>=3)parts[5]=this.replaceAlphaDays(parts[5]);if(parts[5]=="*"){this.starDOW=true}if(this.pattern.indexOf("?")>=0){const initDate=new CronDate(new Date,this.timezone).getDate(true);parts[0]=parts[0].replace("?",initDate.getSeconds());parts[1]=parts[1].replace("?",initDate.getMinutes());parts[2]=parts[2].replace("?",initDate.getHours());if(!this.starDOM)parts[3]=parts[3].replace("?",initDate.getDate());parts[4]=parts[4].replace("?",initDate.getMonth()+1);if(!this.starDOW)parts[5]=parts[5].replace("?",initDate.getDay())}this.throwAtIllegalCharacters(parts);this.partToArray("second",parts[0],0);this.partToArray("minute",parts[1],0);this.partToArray("hour",parts[2],0);this.partToArray("day",parts[3],-1);this.partToArray("month",parts[4],-1);this.partToArray("dow",parts[5],0);if(this.dow[7]){this.dow[0]=1}};CronPattern.prototype.partToArray=function(type,conf,valueIndexOffset){const arr=this[type];if(conf==="*")return arr.fill(1);const split=conf.split(",");if(split.length>1){for(let i=0;i<split.length;i++){this.partToArray(type,split[i],valueIndexOffset)}}else if(conf.indexOf("-")!==-1&&conf.indexOf("/")!==-1){this.handleRangeWithStepping(conf,type,valueIndexOffset)}else if(conf.indexOf("-")!==-1){this.handleRange(conf,type,valueIndexOffset)}else if(conf.indexOf("/")!==-1){this.handleStepping(conf,type,valueIndexOffset)}else if(conf!==""){this.handleNumber(conf,type,valueIndexOffset)}};CronPattern.prototype.throwAtIllegalCharacters=function(parts){const reValidCron=/[^/*0-9,-]+/;for(let i=0;i<parts.length;i++){if(reValidCron.test(parts[i])){throw new TypeError("CronPattern: configuration entry "+i+" ("+parts[i]+") contains illegal characters.")}}};CronPattern.prototype.handleNumber=function(conf,type,valueIndexOffset){const i=parseInt(conf,10)+valueIndexOffset;if(isNaN(i)){throw new TypeError("CronPattern: "+type+" is not a number: '"+conf+"'")}if(i<0||i>=this[type].length){throw new TypeError("CronPattern: "+type+" value out of range: '"+conf+"'")}this[type][i]=1};CronPattern.prototype.handleRangeWithStepping=function(conf,type,valueIndexOffset){const matches=conf.match(/^(\d+)-(\d+)\/(\d+)$/);if(matches===null)throw new TypeError("CronPattern: Syntax error, illegal range with stepping: '"+conf+"'");let[,lower,upper,steps]=matches;lower=parseInt(lower,10)+valueIndexOffset;upper=parseInt(upper,10)+valueIndexOffset;steps=parseInt(steps,10);if(isNaN(lower))throw new TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(upper))throw new TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(steps))throw new TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(steps===0)throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");if(steps>this[type].length)throw new TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[type].length+")");if(lower<0||upper>=this[type].length)throw new TypeError("CronPattern: Value out of range: '"+conf+"'");if(lower>upper)throw new TypeError("CronPattern: From value is larger than to value: '"+conf+"'");for(let i=lower;i<=upper;i+=steps){this[type][i]=1}};CronPattern.prototype.handleRange=function(conf,type,valueIndexOffset){const split=conf.split("-");if(split.length!==2){throw new TypeError("CronPattern: Syntax error, illegal range: '"+conf+"'")}const lower=parseInt(split[0],10)+valueIndexOffset,upper=parseInt(split[1],10)+valueIndexOffset;if(isNaN(lower)){throw new TypeError("CronPattern: Syntax error, illegal lower range (NaN)")}else if(isNaN(upper)){throw new TypeError("CronPattern: Syntax error, illegal upper range (NaN)")}if(lower<0||upper>=this[type].length){throw new TypeError("CronPattern: Value out of range: '"+conf+"'")}if(lower>upper){throw new TypeError("CronPattern: From value is larger than to value: '"+conf+"'")}for(let i=lower;i<=upper;i++){this[type][i]=1}};CronPattern.prototype.handleStepping=function(conf,type){const split=conf.split("/");if(split.length!==2){throw new TypeError("CronPattern: Syntax error, illegal stepping: '"+conf+"'")}let start=0;if(split[0]!=="*"){start=parseInt(split[0],10)}const steps=parseInt(split[1],10);if(isNaN(steps))throw new TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(steps===0)throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");if(steps>this[type].length)throw new TypeError("CronPattern: Syntax error, max steps for part is ("+this[type].length+")");for(let i=start;i<this[type].length;i+=steps){this[type][i]=1}};CronPattern.prototype.replaceAlphaDays=function(conf){return conf.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")};CronPattern.prototype.replaceAlphaMonths=function(conf){return conf.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")};CronPattern.prototype.handleNicknames=function(pattern){const cleanPattern=pattern.trim().toLowerCase();if(cleanPattern==="@yearly"||cleanPattern==="@annually"){return"0 0 1 1 *"}else if(cleanPattern==="@monthly"){return"0 0 1 * *"}else if(cleanPattern==="@weekly"){return"0 0 * * 0"}else if(cleanPattern==="@daily"){return"0 0 * * *"}else if(cleanPattern==="@hourly"){return"0 * * * *"}else{return pattern}};const maxDelay=Math.pow(2,32-1)-1;const scheduledJobs=[];function isFn(v){return Object.prototype.toString.call(v)==="[object Function]"||"function"===typeof v||v instanceof Function}function unref(timer){if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer!=="undefined"){Deno.unrefTimer(timer)}else if(timer&&typeof timer.unref!=="undefined"){timer.unref()}}function Cron(pattern,fnOrOptions1,fnOrOptions2){if(!(this instanceof Cron)){return new Cron(pattern,fnOrOptions1,fnOrOptions2)}let options,func;if(isFn(fnOrOptions1)){func=fnOrOptions1}else if(typeof fnOrOptions1==="object"){options=fnOrOptions1}else if(fnOrOptions1!==void 0){throw new Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).")}if(isFn(fnOrOptions2)){func=fnOrOptions2}else if(typeof fnOrOptions2==="object"){options=fnOrOptions2}else if(fnOrOptions2!==void 0){throw new Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).")}this.name=options?options.name:void 0;this.options=CronOptions(options);this.once=void 0;this.pattern=void 0;this.blocking=false;this.previousrun=void 0;this.runstarted=void 0;if(pattern&&(pattern instanceof Date||typeof pattern==="string"&&pattern.indexOf(":")>0)){this.once=new CronDate(pattern,this.options.timezone||this.options.utcOffset)}else{this.pattern=new CronPattern(pattern,this.options.timezone)}if(func!==void 0){this.fn=func;this.schedule()}if(this.name){const existing=scheduledJobs.find(j=>j.name===this.name);if(existing){throw new Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.")}else{scheduledJobs.push(this)}}return this}Cron.prototype.next=function(prev){const next=this._next(prev);return next?next.getDate():null};Cron.prototype.enumerate=function(n,previous){if(n>this.options.maxRuns){n=this.options.maxRuns}const enumeration=[];let prev=previous||this.previousrun;while(n--&&(prev=this.next(prev))){enumeration.push(prev)}return enumeration};Cron.prototype.running=function(){const msLeft=this.msToNext(this.previousrun);const running=!this.options.paused&&this.fn!==void 0;return msLeft!==null&&running};Cron.prototype.busy=function(){return this.blocking};Cron.prototype.started=function(){return this.runstarted?this.runstarted.getDate():null};Cron.prototype.previous=function(){return this.previousrun?this.previousrun.getDate():null};Cron.prototype.msToNext=function(prev){const next=this._next(prev);prev=new CronDate(prev,this.options.timezone||this.options.utcOffset);if(next){return next.getTime(true)-prev.getTime(true)}else{return null}};Cron.prototype.stop=function(){this.options.kill=true;if(this.currentTimeout){clearTimeout(this.currentTimeout)}};Cron.prototype.pause=function(){return(this.options.paused=true)&&!this.options.kill};Cron.prototype.resume=function(){return!(this.options.paused=false)&&!this.options.kill};Cron.prototype.schedule=function(func,partial){if(func&&this.fn){throw new Error("Cron: It is not allowed to schedule two functions using the same Croner instance.")}else if(func){this.fn=func}let waitMs=this.msToNext(partial?partial:this.previousrun);const target=this.next(partial?partial:this.previousrun);if(waitMs===null||target===null)return this;if(waitMs>maxDelay){waitMs=maxDelay}this.currentTimeout=setTimeout(()=>this._checkTrigger(target),waitMs);if(this.currentTimeout&&this.options.unref){unref(this.currentTimeout)}return this};Cron.prototype._trigger=async function(initiationDate){this.blocking=true;this.runstarted=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);if(this.options.catch){try{await this.fn(this,this.options.context)}catch(_e){if(isFn(this.options.catch)){(inst=>inst.options.catch(_e,inst))(this)}}finally{this.blocking=false}}else{await this.fn(this,this.options.context);this.blocking=false}this.previousrun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset)};Cron.prototype.trigger=async function(){await this._trigger()};Cron.prototype._checkTrigger=function(target){const now=new Date,shouldRun=!this.options.paused&&now.getTime()>=target,isBlocked=this.blocking&&this.options.protect;if(shouldRun&&!isBlocked){this.options.maxRuns--;this._trigger();this.schedule(undefined,now)}else{if(shouldRun&&isBlocked&&isFn(this.options.protect)){(async inst=>inst.options.protect(inst))(this)}this.schedule(undefined,now)}};Cron.prototype._next=function(prev){const hasPreviousRun=prev||this.previousrun?true:false;prev=new CronDate(prev,this.options.timezone||this.options.utcOffset);if(this.options.startAt&&prev&&prev.getTime()<this.options.startAt.getTime()){prev=this.options.startAt}const nextRun=this.once||new CronDate(prev,this.options.timezone||this.options.utcOffset).increment(this.pattern,this.options,hasPreviousRun);if(this.once&&this.once.getTime()<=prev.getTime()){return null}else if(nextRun===null||this.options.maxRuns<=0||this.options.kill||this.options.stopAt&&nextRun.getTime()>=this.options.stopAt.getTime()){return null}else{return nextRun}};Cron.Cron=Cron;Cron.scheduledJobs=scheduledJobs;return Cron});
@@ -1 +0,0 @@
1
- function minitz(y,m,d,h,i,s,tz,throwOnInvalid){return minitz.fromTZ(minitz.tp(y,m,d,h,i,s,tz),throwOnInvalid)}minitz.fromTZISO=(localTimeStr,tz,throwOnInvalid)=>{return minitz.fromTZ(parseISOLocal(localTimeStr,tz),throwOnInvalid)};minitz.fromTZ=function(tp,throwOnInvalid){const inDate=new Date(Date.UTC(tp.y,tp.m-1,tp.d,tp.h,tp.i,tp.s)),offset=getTimezoneOffset(tp.tz,inDate),dateGuess=new Date(inDate.getTime()-offset),dateOffsGuess=getTimezoneOffset(tp.tz,dateGuess);if(dateOffsGuess-offset===0){return dateGuess}else{const dateGuess2=new Date(inDate.getTime()-dateOffsGuess),dateOffsGuess2=getTimezoneOffset(tp.tz,dateGuess2);if(dateOffsGuess2-dateOffsGuess===0){return dateGuess2}else if(!throwOnInvalid&&dateOffsGuess2-dateOffsGuess>0){return dateGuess2}else if(!throwOnInvalid){return dateGuess}else{throw new Error("Invalid date passed to fromTZ()")}}};minitz.toTZ=function(d,tzStr){const td=new Date(d.toLocaleString("sv-SE",{timeZone:tzStr}));return{y:td.getFullYear(),m:td.getMonth()+1,d:td.getDate(),h:td.getHours(),i:td.getMinutes(),s:td.getSeconds(),tz:tzStr}};minitz.tp=(y,m,d,h,i,s,tz)=>{return{y:y,m:m,d:d,h:h,i:i,s:s,tz:tz}};function getTimezoneOffset(timeZone,date=new Date){const tz=date.toLocaleString("en",{timeZone:timeZone,timeStyle:"long"}).split(" ").slice(-1)[0];const dateString=date.toLocaleString("en-US").replace(/[\u202f]/," ");return Date.parse(`${dateString} GMT`)-Date.parse(`${dateString} ${tz}`)}function parseISOLocal(dtStr,tz){const pd=new Date(Date.parse(dtStr));if(isNaN(pd)){throw new Error("minitz: Invalid ISO8601 passed to parser.")}const stringEnd=dtStr.substring(9);if(dtStr.includes("Z")||stringEnd.includes("-")||stringEnd.includes("+")){return minitz.tp(pd.getUTCFullYear(),pd.getUTCMonth()+1,pd.getUTCDate(),pd.getUTCHours(),pd.getUTCMinutes(),pd.getUTCSeconds(),"Etc/UTC")}else{return minitz.tp(pd.getFullYear(),pd.getMonth()+1,pd.getDate(),pd.getHours(),pd.getMinutes(),pd.getSeconds(),tz)}}minitz.minitz=minitz;function CronOptions(options){if(options===void 0){options={}}delete options.name;options.legacyMode=options.legacyMode===void 0?true:options.legacyMode;options.paused=options.paused===void 0?false:options.paused;options.maxRuns=options.maxRuns===void 0?Infinity:options.maxRuns;options.catch=options.catch===void 0?false:options.catch;options.interval=options.interval===void 0?0:parseInt(options.interval,10);options.utcOffset=options.utcOffset===void 0?void 0:parseInt(options.utcOffset,10);options.unref=options.unref===void 0?false:options.unref;options.kill=false;if(options.startAt){options.startAt=new CronDate(options.startAt,options.timezone)}if(options.stopAt){options.stopAt=new CronDate(options.stopAt,options.timezone)}if(options.interval!==null){if(isNaN(options.interval)){throw new Error("CronOptions: Supplied value for interval is not a number")}else if(options.interval<0){throw new Error("CronOptions: Supplied value for interval can not be negative")}}if(options.utcOffset!==void 0){if(isNaN(options.utcOffset)){throw new Error("CronOptions: Invalid value passed for utcOffset, should be number representing minutes offset from UTC.")}else if(options.utcOffset<-870||options.utcOffset>870){throw new Error("CronOptions: utcOffset out of bounds.")}if(options.utcOffset!==void 0&&options.timezone){throw new Error("CronOptions: Combining 'utcOffset' with 'timezone' is not allowed.")}}if(options.unref!==true&&options.unref!==false){throw new Error("CronOptions: Unref should be either true, false or undefined(false).")}return options}const DaysOfMonth=[31,28,31,30,31,30,31,31,30,31,30,31];const RecursionSteps=[["month","year",0],["day","month",-1],["hour","day",0],["minute","hour",0],["second","minute",0]];function CronDate(d,tz){this.tz=tz;if(d&&d instanceof Date){if(!isNaN(d)){this.fromDate(d)}else{throw new TypeError("CronDate: Invalid date passed to CronDate constructor")}}else if(d===void 0){this.fromDate(new Date)}else if(d&&typeof d==="string"){this.fromString(d)}else if(d instanceof CronDate){this.fromCronDate(d)}else{throw new TypeError("CronDate: Invalid type ("+typeof d+") passed to CronDate constructor")}}CronDate.prototype.fromDate=function(inDate){if(this.tz!==void 0){if(typeof this.tz==="number"){this.ms=inDate.getUTCMilliseconds();this.second=inDate.getUTCSeconds();this.minute=inDate.getUTCMinutes()+this.tz;this.hour=inDate.getUTCHours();this.day=inDate.getUTCDate();this.month=inDate.getUTCMonth();this.year=inDate.getUTCFullYear();this.apply()}else{const d=minitz.toTZ(inDate,this.tz);this.ms=inDate.getMilliseconds();this.second=d.s;this.minute=d.i;this.hour=d.h;this.day=d.d;this.month=d.m-1;this.year=d.y}}else{this.ms=inDate.getMilliseconds();this.second=inDate.getSeconds();this.minute=inDate.getMinutes();this.hour=inDate.getHours();this.day=inDate.getDate();this.month=inDate.getMonth();this.year=inDate.getFullYear()}};CronDate.prototype.fromCronDate=function(d){this.tz=d.tz;this.year=d.year;this.month=d.month;this.day=d.day;this.hour=d.hour;this.minute=d.minute;this.second=d.second;this.ms=d.ms};CronDate.prototype.apply=function(){if(this.month>11||this.day>DaysOfMonth[this.month]||this.hour>59||this.minute>59||this.second>59||this.hour<0||this.minute<0||this.second<0){const d=new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms));this.ms=d.getUTCMilliseconds();this.second=d.getUTCSeconds();this.minute=d.getUTCMinutes();this.hour=d.getUTCHours();this.day=d.getUTCDate();this.month=d.getUTCMonth();this.year=d.getUTCFullYear();return true}else{return false}};CronDate.prototype.fromString=function(str){return this.fromDate(minitz.fromTZISO(str,this.tz))};CronDate.prototype.findNext=function(options,target,pattern,offset){const originalTarget=this[target];let lastDayOfMonth;if(pattern.lastDayOfMonth){if(this.month!==1){lastDayOfMonth=DaysOfMonth[this.month]}else{lastDayOfMonth=new Date(Date.UTC(this.year,this.month+1,0,0,0,0,0)).getUTCDate()}}const fDomWeekDay=!pattern.starDOW&&target=="day"?new Date(Date.UTC(this.year,this.month,1,0,0,0,0)).getUTCDay():undefined;for(let i=this[target]+offset;i<pattern[target].length;i++){let match=pattern[target][i];if(target==="day"&&pattern.lastDayOfMonth&&i-offset==lastDayOfMonth){match=true}if(target==="day"&&!pattern.starDOW){const dowMatch=pattern.dow[(fDomWeekDay+(i-offset-1))%7];if(options.legacyMode&&!pattern.starDOM){match=match||dowMatch}else{match=match&&dowMatch}}if(match){this[target]=i-offset;return originalTarget!==this[target]?2:1}}return 3};CronDate.prototype.recurse=function(pattern,options,doing){const res=this.findNext(options,RecursionSteps[doing][0],pattern,RecursionSteps[doing][2]);if(res>1){let resetLevel=doing+1;while(resetLevel<RecursionSteps.length){this[RecursionSteps[resetLevel][0]]=-RecursionSteps[resetLevel][2];resetLevel++}if(res===3){this[RecursionSteps[doing][1]]++;this[RecursionSteps[doing][0]]=-RecursionSteps[doing][2];this.apply();return this.recurse(pattern,options,0)}else if(this.apply()){return this.recurse(pattern,options,doing-1)}}doing+=1;if(doing>=RecursionSteps.length){return this}else if(this.year>=3e3){return null}else{return this.recurse(pattern,options,doing)}};CronDate.prototype.increment=function(pattern,options,hasPreviousRun){if(options.interval>1&&hasPreviousRun){this.second+=options.interval}else{this.second+=1}this.ms=0;this.apply();return this.recurse(pattern,options,0)};CronDate.prototype.getDate=function(internal){if(internal||this.tz===void 0&&this.utcOffset===void 0){return new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.ms)}else{if(typeof this.tz==="number"){return new Date(Date.UTC(this.year,this.month,this.day,this.hour,this.minute-this.tz,this.second,this.ms))}else{return minitz(this.year,this.month+1,this.day,this.hour,this.minute,this.second,this.tz)}}};CronDate.prototype.getTime=function(){return this.getDate().getTime()};function CronPattern(pattern,timezone){this.pattern=pattern;this.timezone=timezone;this.second=Array(60).fill(0);this.minute=Array(60).fill(0);this.hour=Array(24).fill(0);this.day=Array(31).fill(0);this.month=Array(12).fill(0);this.dow=Array(8).fill(0);this.lastDayOfMonth=false;this.starDOM=false;this.starDOW=false;this.parse()}CronPattern.prototype.parse=function(){if(!(typeof this.pattern==="string"||this.pattern.constructor===String)){throw new TypeError("CronPattern: Pattern has to be of type string.")}if(this.pattern.indexOf("@")>=0)this.pattern=this.handleNicknames(this.pattern).trim();const parts=this.pattern.replace(/\s+/g," ").split(" ");if(parts.length<5||parts.length>6){throw new TypeError("CronPattern: invalid configuration format ('"+this.pattern+"'), exacly five or six space separated parts required.")}if(parts.length===5){parts.unshift("0")}if(parts[3].indexOf("L")>=0){parts[3]=parts[3].replace("L","");this.lastDayOfMonth=true}if(parts[3]=="*"){this.starDOM=true}if(parts[4].length>=3)parts[4]=this.replaceAlphaMonths(parts[4]);if(parts[5].length>=3)parts[5]=this.replaceAlphaDays(parts[5]);if(parts[5]=="*"){this.starDOW=true}if(this.pattern.indexOf("?")>=0){const initDate=new CronDate(new Date,this.timezone).getDate(true);parts[0]=parts[0].replace("?",initDate.getSeconds());parts[1]=parts[1].replace("?",initDate.getMinutes());parts[2]=parts[2].replace("?",initDate.getHours());if(!this.starDOM)parts[3]=parts[3].replace("?",initDate.getDate());parts[4]=parts[4].replace("?",initDate.getMonth()+1);if(!this.starDOW)parts[5]=parts[5].replace("?",initDate.getDay())}this.throwAtIllegalCharacters(parts);this.partToArray("second",parts[0],0);this.partToArray("minute",parts[1],0);this.partToArray("hour",parts[2],0);this.partToArray("day",parts[3],-1);this.partToArray("month",parts[4],-1);this.partToArray("dow",parts[5],0);if(this.dow[7]){this.dow[0]=1}};CronPattern.prototype.partToArray=function(type,conf,valueIndexOffset){const arr=this[type];if(conf==="*")return arr.fill(1);const split=conf.split(",");if(split.length>1){for(let i=0;i<split.length;i++){this.partToArray(type,split[i],valueIndexOffset)}}else if(conf.indexOf("-")!==-1&&conf.indexOf("/")!==-1){this.handleRangeWithStepping(conf,type,valueIndexOffset)}else if(conf.indexOf("-")!==-1){this.handleRange(conf,type,valueIndexOffset)}else if(conf.indexOf("/")!==-1){this.handleStepping(conf,type,valueIndexOffset)}else if(conf!==""){this.handleNumber(conf,type,valueIndexOffset)}};CronPattern.prototype.throwAtIllegalCharacters=function(parts){const reValidCron=/[^/*0-9,-]+/;for(let i=0;i<parts.length;i++){if(reValidCron.test(parts[i])){throw new TypeError("CronPattern: configuration entry "+i+" ("+parts[i]+") contains illegal characters.")}}};CronPattern.prototype.handleNumber=function(conf,type,valueIndexOffset){const i=parseInt(conf,10)+valueIndexOffset;if(isNaN(i)){throw new TypeError("CronPattern: "+type+" is not a number: '"+conf+"'")}if(i<0||i>=this[type].length){throw new TypeError("CronPattern: "+type+" value out of range: '"+conf+"'")}this[type][i]=1};CronPattern.prototype.handleRangeWithStepping=function(conf,type,valueIndexOffset){const matches=conf.match(/^(\d+)-(\d+)\/(\d+)$/);if(matches===null)throw new TypeError("CronPattern: Syntax error, illegal range with stepping: '"+conf+"'");let[,lower,upper,steps]=matches;lower=parseInt(lower,10)+valueIndexOffset;upper=parseInt(upper,10)+valueIndexOffset;steps=parseInt(steps,10);if(isNaN(lower))throw new TypeError("CronPattern: Syntax error, illegal lower range (NaN)");if(isNaN(upper))throw new TypeError("CronPattern: Syntax error, illegal upper range (NaN)");if(isNaN(steps))throw new TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(steps===0)throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");if(steps>this[type].length)throw new TypeError("CronPattern: Syntax error, steps cannot be greater than maximum value of part ("+this[type].length+")");if(lower<0||upper>=this[type].length)throw new TypeError("CronPattern: Value out of range: '"+conf+"'");if(lower>upper)throw new TypeError("CronPattern: From value is larger than to value: '"+conf+"'");for(let i=lower;i<=upper;i+=steps){this[type][i]=1}};CronPattern.prototype.handleRange=function(conf,type,valueIndexOffset){const split=conf.split("-");if(split.length!==2){throw new TypeError("CronPattern: Syntax error, illegal range: '"+conf+"'")}const lower=parseInt(split[0],10)+valueIndexOffset,upper=parseInt(split[1],10)+valueIndexOffset;if(isNaN(lower)){throw new TypeError("CronPattern: Syntax error, illegal lower range (NaN)")}else if(isNaN(upper)){throw new TypeError("CronPattern: Syntax error, illegal upper range (NaN)")}if(lower<0||upper>=this[type].length){throw new TypeError("CronPattern: Value out of range: '"+conf+"'")}if(lower>upper){throw new TypeError("CronPattern: From value is larger than to value: '"+conf+"'")}for(let i=lower;i<=upper;i++){this[type][i]=1}};CronPattern.prototype.handleStepping=function(conf,type){const split=conf.split("/");if(split.length!==2){throw new TypeError("CronPattern: Syntax error, illegal stepping: '"+conf+"'")}let start=0;if(split[0]!=="*"){start=parseInt(split[0],10)}const steps=parseInt(split[1],10);if(isNaN(steps))throw new TypeError("CronPattern: Syntax error, illegal stepping: (NaN)");if(steps===0)throw new TypeError("CronPattern: Syntax error, illegal stepping: 0");if(steps>this[type].length)throw new TypeError("CronPattern: Syntax error, max steps for part is ("+this[type].length+")");for(let i=start;i<this[type].length;i+=steps){this[type][i]=1}};CronPattern.prototype.replaceAlphaDays=function(conf){return conf.replace(/-sun/gi,"-7").replace(/sun/gi,"0").replace(/mon/gi,"1").replace(/tue/gi,"2").replace(/wed/gi,"3").replace(/thu/gi,"4").replace(/fri/gi,"5").replace(/sat/gi,"6")};CronPattern.prototype.replaceAlphaMonths=function(conf){return conf.replace(/jan/gi,"1").replace(/feb/gi,"2").replace(/mar/gi,"3").replace(/apr/gi,"4").replace(/may/gi,"5").replace(/jun/gi,"6").replace(/jul/gi,"7").replace(/aug/gi,"8").replace(/sep/gi,"9").replace(/oct/gi,"10").replace(/nov/gi,"11").replace(/dec/gi,"12")};CronPattern.prototype.handleNicknames=function(pattern){const cleanPattern=pattern.trim().toLowerCase();if(cleanPattern==="@yearly"||cleanPattern==="@annually"){return"0 0 1 1 *"}else if(cleanPattern==="@monthly"){return"0 0 1 * *"}else if(cleanPattern==="@weekly"){return"0 0 * * 0"}else if(cleanPattern==="@daily"){return"0 0 * * *"}else if(cleanPattern==="@hourly"){return"0 * * * *"}else{return pattern}};const maxDelay=Math.pow(2,32-1)-1;const scheduledJobs=[];function isFn(v){return Object.prototype.toString.call(v)==="[object Function]"||"function"===typeof v||v instanceof Function}function unref(timer){if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer!=="undefined"){Deno.unrefTimer(timer)}else if(timer&&typeof timer.unref!=="undefined"){timer.unref()}}function Cron(pattern,fnOrOptions1,fnOrOptions2){if(!(this instanceof Cron)){return new Cron(pattern,fnOrOptions1,fnOrOptions2)}let options,func;if(isFn(fnOrOptions1)){func=fnOrOptions1}else if(typeof fnOrOptions1==="object"){options=fnOrOptions1}else if(fnOrOptions1!==void 0){throw new Error("Cron: Invalid argument passed for optionsIn. Should be one of function, or object (options).")}if(isFn(fnOrOptions2)){func=fnOrOptions2}else if(typeof fnOrOptions2==="object"){options=fnOrOptions2}else if(fnOrOptions2!==void 0){throw new Error("Cron: Invalid argument passed for funcIn. Should be one of function, or object (options).")}this.name=options?options.name:void 0;this.options=CronOptions(options);this.once=void 0;this.pattern=void 0;this.blocking=false;this.previousrun=void 0;this.runstarted=void 0;if(pattern&&(pattern instanceof Date||typeof pattern==="string"&&pattern.indexOf(":")>0)){this.once=new CronDate(pattern,this.options.timezone||this.options.utcOffset)}else{this.pattern=new CronPattern(pattern,this.options.timezone)}if(func!==void 0){this.fn=func;this.schedule()}if(this.name){const existing=scheduledJobs.find(j=>j.name===this.name);if(existing){throw new Error("Cron: Tried to initialize new named job '"+this.name+"', but name already taken.")}else{scheduledJobs.push(this)}}return this}Cron.prototype.next=function(prev){const next=this._next(prev);return next?next.getDate():null};Cron.prototype.enumerate=function(n,previous){if(n>this.options.maxRuns){n=this.options.maxRuns}const enumeration=[];let prev=previous||this.previousrun;while(n--&&(prev=this.next(prev))){enumeration.push(prev)}return enumeration};Cron.prototype.running=function(){const msLeft=this.msToNext(this.previousrun);const running=!this.options.paused&&this.fn!==void 0;return msLeft!==null&&running};Cron.prototype.busy=function(){return this.blocking};Cron.prototype.started=function(){return this.runstarted?this.runstarted.getDate():null};Cron.prototype.previous=function(){return this.previousrun?this.previousrun.getDate():null};Cron.prototype.msToNext=function(prev){const next=this._next(prev);prev=new CronDate(prev,this.options.timezone||this.options.utcOffset);if(next){return next.getTime(true)-prev.getTime(true)}else{return null}};Cron.prototype.stop=function(){this.options.kill=true;if(this.currentTimeout){clearTimeout(this.currentTimeout)}};Cron.prototype.pause=function(){return(this.options.paused=true)&&!this.options.kill};Cron.prototype.resume=function(){return!(this.options.paused=false)&&!this.options.kill};Cron.prototype.schedule=function(func,partial){if(func&&this.fn){throw new Error("Cron: It is not allowed to schedule two functions using the same Croner instance.")}else if(func){this.fn=func}let waitMs=this.msToNext(partial?partial:this.previousrun);const target=this.next(partial?partial:this.previousrun);if(waitMs===null||target===null)return this;if(waitMs>maxDelay){waitMs=maxDelay}this.currentTimeout=setTimeout(()=>this._checkTrigger(target),waitMs);if(this.currentTimeout&&this.options.unref){unref(this.currentTimeout)}return this};Cron.prototype._trigger=async function(initiationDate){this.blocking=true;this.runstarted=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);if(this.options.catch){try{await this.fn(this,this.options.context)}catch(_e){if(isFn(this.options.catch)){(inst=>inst.options.catch(_e,inst))(this)}}finally{this.blocking=false}}else{await this.fn(this,this.options.context);this.blocking=false}this.previousrun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset)};Cron.prototype.trigger=async function(){await this._trigger()};Cron.prototype._checkTrigger=function(target){const now=new Date,shouldRun=!this.options.paused&&now.getTime()>=target,isBlocked=this.blocking&&this.options.protect;if(shouldRun&&!isBlocked){this.options.maxRuns--;this._trigger();this.schedule(undefined,now)}else{if(shouldRun&&isBlocked&&isFn(this.options.protect)){(async inst=>inst.options.protect(inst))(this)}this.schedule(undefined,now)}};Cron.prototype._next=function(prev){const hasPreviousRun=prev||this.previousrun?true:false;prev=new CronDate(prev,this.options.timezone||this.options.utcOffset);if(this.options.startAt&&prev&&prev.getTime()<this.options.startAt.getTime()){prev=this.options.startAt}const nextRun=this.once||new CronDate(prev,this.options.timezone||this.options.utcOffset).increment(this.pattern,this.options,hasPreviousRun);if(this.once&&this.once.getTime()<=prev.getTime()){return null}else if(nextRun===null||this.options.maxRuns<=0||this.options.kill||this.options.stopAt&&nextRun.getTime()>=this.options.stopAt.getTime()){return null}else{return nextRun}};Cron.Cron=Cron;Cron.scheduledJobs=scheduledJobs;export{Cron,Cron as default,scheduledJobs};
@@ -1,2 +0,0 @@
1
- export default Cron;
2
- import Cron from "./croner.js";
package/types/date.d.ts DELETED
@@ -1,62 +0,0 @@
1
- /**
2
- * Converts date to CronDate
3
- * @constructor
4
- *
5
- * @param {CronDate|Date|string} [d] - Input date, if using string representation ISO 8001 (2015-11-24T19:40:00) local timezone is expected
6
- * @param {string|number} [tz] - String representation of target timezone in Europe/Stockholm format, or a number representing offset in minutes.
7
- */
8
- export function CronDate(d?: CronDate | Date | string, tz?: string | number): void;
9
- export class CronDate {
10
- /**
11
- * Converts date to CronDate
12
- * @constructor
13
- *
14
- * @param {CronDate|Date|string} [d] - Input date, if using string representation ISO 8001 (2015-11-24T19:40:00) local timezone is expected
15
- * @param {string|number} [tz] - String representation of target timezone in Europe/Stockholm format, or a number representing offset in minutes.
16
- */
17
- constructor(d?: CronDate | Date | string, tz?: string | number);
18
- /**
19
- * TimeZone
20
- * @type {string|number|undefined}
21
- */
22
- tz: string | number | undefined;
23
- private fromDate;
24
- ms: number;
25
- second: number;
26
- minute: number;
27
- hour: number;
28
- day: number;
29
- month: number;
30
- year: number;
31
- private fromCronDate;
32
- private apply;
33
- private fromString;
34
- private findNext;
35
- private recurse;
36
- /**
37
- * Increment to next run time
38
- * @public
39
- *
40
- * @param {string} pattern - The pattern used to increment current state
41
- * @param {CronOptions} options - Cron options used for incrementing
42
- * @param {boolean} [hasPreviousRun] - If this run should adhere to minimum interval
43
- * @return {CronDate|null} - Returns itthis for chaining, or null if increment wasnt possible
44
- */
45
- public increment(pattern: string, options: CronOptions, hasPreviousRun?: boolean): CronDate | null;
46
- /**
47
- * Convert current state back to a javascript Date()
48
- * @public
49
- *
50
- * @param {boolean} internal - If this is an internal call
51
- * @returns {Date}
52
- */
53
- public getDate(internal: boolean): Date;
54
- /**
55
- * Convert current state back to a javascript Date() and return UTC milliseconds
56
- * @public
57
- *
58
- * @returns {Date}
59
- */
60
- public getTime(): Date;
61
- }
62
- import { CronOptions } from "./options.js";
@@ -1,100 +0,0 @@
1
- /**
2
- * - Cron scheduler options
3
- */
4
- export type CronOptions = {
5
- /**
6
- * - Name of a job
7
- */
8
- name?: string;
9
- /**
10
- * - Job is paused
11
- */
12
- paused?: boolean;
13
- /**
14
- * - Job is about to be killed or killed
15
- */
16
- kill?: boolean;
17
- /**
18
- * - Continue exection even if a unhandled error is thrown by triggered function
19
- * - If set to a function, execute function on catching the error.
20
- */
21
- catch?: boolean | CatchCallbackFn;
22
- /**
23
- * - Abort job instantly if nothing else keeps the event loop running.
24
- */
25
- unref?: boolean;
26
- /**
27
- * - Maximum nuber of executions
28
- */
29
- maxRuns?: number;
30
- /**
31
- * - Minimum interval between executions, in seconds
32
- */
33
- interval?: number;
34
- /**
35
- * - Skip current run if job is already running
36
- */
37
- protect?: boolean | ProtectCallbackFn;
38
- /**
39
- * - When to start running
40
- */
41
- startAt?: string | Date;
42
- /**
43
- * - When to stop running
44
- */
45
- stopAt?: string | Date;
46
- /**
47
- * - Time zone in Europe/Stockholm format
48
- */
49
- timezone?: string;
50
- /**
51
- * - Offset from UTC in minutes
52
- */
53
- utcOffset?: number;
54
- /**
55
- * - Combine day-of-month and day-of-week using true = OR, false = AND. Default is true = OR.
56
- */
57
- legacyMode?: boolean;
58
- /**
59
- * - Used to pass any object to scheduled function
60
- */
61
- context?: unknown;
62
- };
63
- export type CatchCallbackFn = (e: unknown, job: Cron) => any;
64
- export type ProtectCallbackFn = (job: Cron) => any;
65
- /**
66
- * @callback CatchCallbackFn
67
- * @param {unknown} e
68
- * @param {Cron} job
69
- */
70
- /**
71
- * @callback ProtectCallbackFn
72
- * @param {Cron} job
73
- */
74
- /**
75
- * @typedef {Object} CronOptions - Cron scheduler options
76
- * @property {string} [name] - Name of a job
77
- * @property {boolean} [paused] - Job is paused
78
- * @property {boolean} [kill] - Job is about to be killed or killed
79
- * @property {boolean | CatchCallbackFn} [catch] - Continue exection even if a unhandled error is thrown by triggered function
80
- * - If set to a function, execute function on catching the error.
81
- * @property {boolean} [unref] - Abort job instantly if nothing else keeps the event loop running.
82
- * @property {number} [maxRuns] - Maximum nuber of executions
83
- * @property {number} [interval] - Minimum interval between executions, in seconds
84
- * @property {boolean | ProtectCallbackFn} [protect] - Skip current run if job is already running
85
- * @property {string | Date} [startAt] - When to start running
86
- * @property {string | Date} [stopAt] - When to stop running
87
- * @property {string} [timezone] - Time zone in Europe/Stockholm format
88
- * @property {number} [utcOffset] - Offset from UTC in minutes
89
- * @property {boolean} [legacyMode] - Combine day-of-month and day-of-week using true = OR, false = AND. Default is true = OR.
90
- * @property {?} [context] - Used to pass any object to scheduled function
91
- */
92
- /**
93
- * Internal function that validates options, and sets defaults
94
- * @private
95
- *
96
- * @param {CronOptions} options
97
- * @returns {CronOptions}
98
- */
99
- export function CronOptions(options: CronOptions): CronOptions;
100
- import { Cron } from "./croner.js";
@@ -1,72 +0,0 @@
1
- /**
2
- * Name for each part of the cron pattern
3
- */
4
- export type CronPatternPart = ("second" | "minute" | "hour" | "day" | "month" | "dow");
5
- /**
6
- * Offset, 0 or -1.
7
- *
8
- * 0 for seconds,minutes and hours as they start on 1.
9
- * -1 on days and months, as the start on 0
10
- */
11
- export type CronIndexOffset = number;
12
- /**
13
- * Name for each part of the cron pattern
14
- * @typedef {("second" | "minute" | "hour" | "day" | "month" | "dow")} CronPatternPart
15
- */
16
- /**
17
- * Offset, 0 or -1.
18
- *
19
- * 0 for seconds,minutes and hours as they start on 1.
20
- * -1 on days and months, as the start on 0
21
- *
22
- * @typedef {Number} CronIndexOffset
23
- */
24
- /**
25
- * Create a CronPattern instance from pattern string ('* * * * * *')
26
- * @constructor
27
- * @param {string} pattern - Input pattern
28
- * @param {string} timezone - Input timezone, used for '?'-substitution
29
- */
30
- export function CronPattern(pattern: string, timezone: string): void;
31
- export class CronPattern {
32
- /**
33
- * Name for each part of the cron pattern
34
- * @typedef {("second" | "minute" | "hour" | "day" | "month" | "dow")} CronPatternPart
35
- */
36
- /**
37
- * Offset, 0 or -1.
38
- *
39
- * 0 for seconds,minutes and hours as they start on 1.
40
- * -1 on days and months, as the start on 0
41
- *
42
- * @typedef {Number} CronIndexOffset
43
- */
44
- /**
45
- * Create a CronPattern instance from pattern string ('* * * * * *')
46
- * @constructor
47
- * @param {string} pattern - Input pattern
48
- * @param {string} timezone - Input timezone, used for '?'-substitution
49
- */
50
- constructor(pattern: string, timezone: string);
51
- pattern: string;
52
- timezone: string;
53
- second: any;
54
- minute: any;
55
- hour: any;
56
- day: any;
57
- month: any;
58
- dow: any;
59
- lastDayOfMonth: boolean;
60
- starDOM: boolean;
61
- starDOW: boolean;
62
- private parse;
63
- private partToArray;
64
- private throwAtIllegalCharacters;
65
- private handleNumber;
66
- private handleRangeWithStepping;
67
- private handleRange;
68
- private handleStepping;
69
- private replaceAlphaDays;
70
- private replaceAlphaMonths;
71
- private handleNicknames;
72
- }