Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

croner

Package Overview
Dependencies
Maintainers
1
Versions
228
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

croner - npm Package Compare versions

Comparing version 6.0.0-dev.1 to 6.0.0-dev.2

dist/croner.min.cjs

2

dist/croner.min.js

@@ -1,1 +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;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||pattern.lastWeekdayOfMonth){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){let dowMatch=pattern.dayOfWeek[(fDomWeekDay+(i-offset-1))%7];if(dowMatch&&pattern.lastWeekdayOfMonth){dowMatch=dowMatch&&i-offset>lastDayOfMonth-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){this.second+=options.interval>1&&hasPreviousRun?options.interval:1;this.ms=0;this.apply();return this.recurse(pattern,options,0)};CronDate.prototype.getDate=function(internal){if(internal||this.tz===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.dayOfWeek=Array(8).fill(0);this.lastDayOfMonth=false;this.lastWeekdayOfMonth=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[5].indexOf("L")>=0){parts[5]=parts[5].replace("L","");this.lastWeekdayOfMonth=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("dayOfWeek",parts[5],0);if(this.dayOfWeek[7]){this.dayOfWeek[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}};function isFunction(v){return Object.prototype.toString.call(v)==="[object Function]"||"function"===typeof v||v instanceof Function}function unrefTimer(timer){if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer!=="undefined"){Deno.unrefTimer(timer)}else if(timer&&typeof timer.unref!=="undefined"){timer.unref()}}const maxDelay=Math.pow(2,32-1)-1;const scheduledJobs=[];function Cron(pattern,fnOrOptions1,fnOrOptions2){if(!(this instanceof Cron)){return new Cron(pattern,fnOrOptions1,fnOrOptions2)}let options,func;if(isFunction(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(isFunction(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._states={kill:false,blocking:false,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:options?options.maxRuns:void 0,paused:options?options.paused:false};this.pattern=void 0;if(pattern&&(pattern instanceof Date||typeof pattern==="string"&&pattern.indexOf(":")>0)){this._states.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._states.maxRuns){n=this._states.maxRuns}const enumeration=[];let prev=previous||this._states.previousRun;while(n--&&(prev=this.next(prev))){enumeration.push(prev)}return enumeration};Cron.prototype.running=function(){const msLeft=this.msToNext(this._states.previousRun);const running=!this._states.paused&&this.fn!==void 0;return msLeft!==null&&running};Cron.prototype.busy=function(){return this._states.blocking};Cron.prototype.started=function(){return this._states.currentRun?this._states.currentRun.getDate():null};Cron.prototype.previous=function(){return this._states.previousRun?this._states.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._states.kill=true;if(this._states.currentTimeout){clearTimeout(this._states.currentTimeout)}};Cron.prototype.pause=function(){this._states.paused=true;return!this._states.kill};Cron.prototype.resume=function(){this._states.paused=false;return!this._states.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._states.previousRun);const target=this.next(partial?partial:this._states.previousRun);if(waitMs===null||target===null)return this;if(waitMs>maxDelay){waitMs=maxDelay}this._states.currentTimeout=setTimeout(()=>this._checkTrigger(target),waitMs);if(this._states.currentTimeout&&this.options.unref){unrefTimer(this._states.currentTimeout)}return this};Cron.prototype._trigger=async function(initiationDate){this._states.blocking=true;this._states.currentRun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);if(this.options.catch){try{await this.fn(this,this.options.context)}catch(_e){if(isFunction(this.options.catch)){setTimeout(()=>this.options.catch(_e,this),0)}}}else{await this.fn(this,this.options.context)}this._states.previousRun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);this._states.blocking=false};Cron.prototype.trigger=async function(){await this._trigger()};Cron.prototype._checkTrigger=function(target){const now=new Date,shouldRun=!this._states.paused&&now.getTime()>=target,isBlocked=this.blocking&&this.options.protect;if(shouldRun&&!isBlocked){this._states.maxRuns--;this._trigger()}else{if(shouldRun&&isBlocked&&isFunction(this.options.protect)){setTimeout(()=>this.options.protect(this),0)}}this.schedule(undefined,now)};Cron.prototype._next=function(prev){const hasPreviousRun=prev||this._states.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._states.once||new CronDate(prev,this.options.timezone||this.options.utcOffset).increment(this.pattern,this.options,hasPreviousRun);if(this._states.once&&this._states.once.getTime()<=prev.getTime()){return null}else if(nextRun===null||this._states.maxRuns<=0||this._states.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};
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;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||pattern.lastWeekdayOfMonth){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){let dowMatch=pattern.dayOfWeek[(fDomWeekDay+(i-offset-1))%7];if(dowMatch&&pattern.lastWeekdayOfMonth){dowMatch=dowMatch&&i-offset>lastDayOfMonth-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){this.second+=options.interval>1&&hasPreviousRun?options.interval:1;this.ms=0;this.apply();return this.recurse(pattern,options,0)};CronDate.prototype.getDate=function(internal){if(internal||this.tz===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.dayOfWeek=Array(8).fill(0);this.lastDayOfMonth=false;this.lastWeekdayOfMonth=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[5].indexOf("L")>=0){parts[5]=parts[5].replace("L","");this.lastWeekdayOfMonth=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("dayOfWeek",parts[5],0);if(this.dayOfWeek[7]){this.dayOfWeek[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}};function isFunction(v){return Object.prototype.toString.call(v)==="[object Function]"||"function"===typeof v||v instanceof Function}function unrefTimer(timer){if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer!=="undefined"){Deno.unrefTimer(timer)}else if(timer&&typeof timer.unref!=="undefined"){timer.unref()}}const maxDelay=Math.pow(2,32-1)-1;const scheduledJobs=[];function Cron(pattern,fnOrOptions1,fnOrOptions2){if(!(this instanceof Cron)){return new Cron(pattern,fnOrOptions1,fnOrOptions2)}let options,func;if(isFunction(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(isFunction(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._states={kill:false,blocking:false,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:options?options.maxRuns:void 0,paused:options?options.paused:false,pattern:void 0};if(pattern&&(pattern instanceof Date||typeof pattern==="string"&&pattern.indexOf(":")>0)){this._states.once=new CronDate(pattern,this.options.timezone||this.options.utcOffset)}else{this._states.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.nextRun=function(prev){const next=this._next(prev);return next?next.getDate():null};Cron.prototype.nextRuns=function(n,previous){if(n>this._states.maxRuns){n=this._states.maxRuns}const enumeration=[];let prev=previous||this._states.previousRun;while(n--&&(prev=this.nextRun(prev))){enumeration.push(prev)}return enumeration};Cron.prototype.getPattern=function(){return this._states.pattern?this._states.pattern.pattern:void 0};Cron.prototype.isRunning=function(){const msLeft=this.msToNext(this._states.previousRun);const running=!this._states.paused&&this.fn!==void 0;return msLeft!==null&&running};Cron.prototype.isBusy=function(){return this._states.blocking};Cron.prototype.currentRun=function(){return this._states.currentRun?this._states.currentRun.getDate():null};Cron.prototype.previousRun=function(){return this._states.previousRun?this._states.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._states.kill=true;if(this._states.currentTimeout){clearTimeout(this._states.currentTimeout)}};Cron.prototype.pause=function(){this._states.paused=true;return!this._states.kill};Cron.prototype.resume=function(){this._states.paused=false;return!this._states.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._states.previousRun);const target=this.nextRun(partial?partial:this._states.previousRun);if(waitMs===null||target===null)return this;if(waitMs>maxDelay){waitMs=maxDelay}this._states.currentTimeout=setTimeout(()=>this._checkTrigger(target),waitMs);if(this._states.currentTimeout&&this.options.unref){unrefTimer(this._states.currentTimeout)}return this};Cron.prototype._trigger=async function(initiationDate){this._states.blocking=true;this._states.currentRun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);if(this.options.catch){try{await this.fn(this,this.options.context)}catch(_e){if(isFunction(this.options.catch)){setTimeout(()=>this.options.catch(_e,this),0)}}}else{await this.fn(this,this.options.context)}this._states.previousRun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);this._states.blocking=false};Cron.prototype.trigger=async function(){await this._trigger()};Cron.prototype._checkTrigger=function(target){const now=new Date,shouldRun=!this._states.paused&&now.getTime()>=target,isBlocked=this.blocking&&this.options.protect;if(shouldRun&&!isBlocked){this._states.maxRuns--;this._trigger()}else{if(shouldRun&&isBlocked&&isFunction(this.options.protect)){setTimeout(()=>this.options.protect(this),0)}}this.schedule(undefined,now)};Cron.prototype._next=function(prev){const hasPreviousRun=prev||this._states.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._states.once||new CronDate(prev,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,hasPreviousRun);if(this._states.once&&this._states.once.getTime()<=prev.getTime()){return null}else if(nextRun===null||this._states.maxRuns<=0||this._states.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,1 +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;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||pattern.lastWeekdayOfMonth){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){let dowMatch=pattern.dayOfWeek[(fDomWeekDay+(i-offset-1))%7];if(dowMatch&&pattern.lastWeekdayOfMonth){dowMatch=dowMatch&&i-offset>lastDayOfMonth-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){this.second+=options.interval>1&&hasPreviousRun?options.interval:1;this.ms=0;this.apply();return this.recurse(pattern,options,0)};CronDate.prototype.getDate=function(internal){if(internal||this.tz===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.dayOfWeek=Array(8).fill(0);this.lastDayOfMonth=false;this.lastWeekdayOfMonth=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[5].indexOf("L")>=0){parts[5]=parts[5].replace("L","");this.lastWeekdayOfMonth=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("dayOfWeek",parts[5],0);if(this.dayOfWeek[7]){this.dayOfWeek[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}};function isFunction(v){return Object.prototype.toString.call(v)==="[object Function]"||"function"===typeof v||v instanceof Function}function unrefTimer(timer){if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer!=="undefined"){Deno.unrefTimer(timer)}else if(timer&&typeof timer.unref!=="undefined"){timer.unref()}}const maxDelay=Math.pow(2,32-1)-1;const scheduledJobs=[];function Cron(pattern,fnOrOptions1,fnOrOptions2){if(!(this instanceof Cron)){return new Cron(pattern,fnOrOptions1,fnOrOptions2)}let options,func;if(isFunction(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(isFunction(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._states={kill:false,blocking:false,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:options?options.maxRuns:void 0,paused:options?options.paused:false};this.pattern=void 0;if(pattern&&(pattern instanceof Date||typeof pattern==="string"&&pattern.indexOf(":")>0)){this._states.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._states.maxRuns){n=this._states.maxRuns}const enumeration=[];let prev=previous||this._states.previousRun;while(n--&&(prev=this.next(prev))){enumeration.push(prev)}return enumeration};Cron.prototype.running=function(){const msLeft=this.msToNext(this._states.previousRun);const running=!this._states.paused&&this.fn!==void 0;return msLeft!==null&&running};Cron.prototype.busy=function(){return this._states.blocking};Cron.prototype.started=function(){return this._states.currentRun?this._states.currentRun.getDate():null};Cron.prototype.previous=function(){return this._states.previousRun?this._states.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._states.kill=true;if(this._states.currentTimeout){clearTimeout(this._states.currentTimeout)}};Cron.prototype.pause=function(){this._states.paused=true;return!this._states.kill};Cron.prototype.resume=function(){this._states.paused=false;return!this._states.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._states.previousRun);const target=this.next(partial?partial:this._states.previousRun);if(waitMs===null||target===null)return this;if(waitMs>maxDelay){waitMs=maxDelay}this._states.currentTimeout=setTimeout(()=>this._checkTrigger(target),waitMs);if(this._states.currentTimeout&&this.options.unref){unrefTimer(this._states.currentTimeout)}return this};Cron.prototype._trigger=async function(initiationDate){this._states.blocking=true;this._states.currentRun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);if(this.options.catch){try{await this.fn(this,this.options.context)}catch(_e){if(isFunction(this.options.catch)){setTimeout(()=>this.options.catch(_e,this),0)}}}else{await this.fn(this,this.options.context)}this._states.previousRun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);this._states.blocking=false};Cron.prototype.trigger=async function(){await this._trigger()};Cron.prototype._checkTrigger=function(target){const now=new Date,shouldRun=!this._states.paused&&now.getTime()>=target,isBlocked=this.blocking&&this.options.protect;if(shouldRun&&!isBlocked){this._states.maxRuns--;this._trigger()}else{if(shouldRun&&isBlocked&&isFunction(this.options.protect)){setTimeout(()=>this.options.protect(this),0)}}this.schedule(undefined,now)};Cron.prototype._next=function(prev){const hasPreviousRun=prev||this._states.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._states.once||new CronDate(prev,this.options.timezone||this.options.utcOffset).increment(this.pattern,this.options,hasPreviousRun);if(this._states.once&&this._states.once.getTime()<=prev.getTime()){return null}else if(nextRun===null||this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&nextRun.getTime()>=this.options.stopAt.getTime()){return null}else{return nextRun}};Cron.Cron=Cron;Cron.scheduledJobs=scheduledJobs;return Cron});
(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;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||pattern.lastWeekdayOfMonth){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){let dowMatch=pattern.dayOfWeek[(fDomWeekDay+(i-offset-1))%7];if(dowMatch&&pattern.lastWeekdayOfMonth){dowMatch=dowMatch&&i-offset>lastDayOfMonth-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){this.second+=options.interval>1&&hasPreviousRun?options.interval:1;this.ms=0;this.apply();return this.recurse(pattern,options,0)};CronDate.prototype.getDate=function(internal){if(internal||this.tz===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.dayOfWeek=Array(8).fill(0);this.lastDayOfMonth=false;this.lastWeekdayOfMonth=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[5].indexOf("L")>=0){parts[5]=parts[5].replace("L","");this.lastWeekdayOfMonth=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("dayOfWeek",parts[5],0);if(this.dayOfWeek[7]){this.dayOfWeek[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}};function isFunction(v){return Object.prototype.toString.call(v)==="[object Function]"||"function"===typeof v||v instanceof Function}function unrefTimer(timer){if(typeof Deno!=="undefined"&&typeof Deno.unrefTimer!=="undefined"){Deno.unrefTimer(timer)}else if(timer&&typeof timer.unref!=="undefined"){timer.unref()}}const maxDelay=Math.pow(2,32-1)-1;const scheduledJobs=[];function Cron(pattern,fnOrOptions1,fnOrOptions2){if(!(this instanceof Cron)){return new Cron(pattern,fnOrOptions1,fnOrOptions2)}let options,func;if(isFunction(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(isFunction(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._states={kill:false,blocking:false,previousRun:void 0,currentRun:void 0,once:void 0,currentTimeout:void 0,maxRuns:options?options.maxRuns:void 0,paused:options?options.paused:false,pattern:void 0};if(pattern&&(pattern instanceof Date||typeof pattern==="string"&&pattern.indexOf(":")>0)){this._states.once=new CronDate(pattern,this.options.timezone||this.options.utcOffset)}else{this._states.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.nextRun=function(prev){const next=this._next(prev);return next?next.getDate():null};Cron.prototype.nextRuns=function(n,previous){if(n>this._states.maxRuns){n=this._states.maxRuns}const enumeration=[];let prev=previous||this._states.previousRun;while(n--&&(prev=this.nextRun(prev))){enumeration.push(prev)}return enumeration};Cron.prototype.getPattern=function(){return this._states.pattern?this._states.pattern.pattern:void 0};Cron.prototype.isRunning=function(){const msLeft=this.msToNext(this._states.previousRun);const running=!this._states.paused&&this.fn!==void 0;return msLeft!==null&&running};Cron.prototype.isBusy=function(){return this._states.blocking};Cron.prototype.currentRun=function(){return this._states.currentRun?this._states.currentRun.getDate():null};Cron.prototype.previousRun=function(){return this._states.previousRun?this._states.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._states.kill=true;if(this._states.currentTimeout){clearTimeout(this._states.currentTimeout)}};Cron.prototype.pause=function(){this._states.paused=true;return!this._states.kill};Cron.prototype.resume=function(){this._states.paused=false;return!this._states.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._states.previousRun);const target=this.nextRun(partial?partial:this._states.previousRun);if(waitMs===null||target===null)return this;if(waitMs>maxDelay){waitMs=maxDelay}this._states.currentTimeout=setTimeout(()=>this._checkTrigger(target),waitMs);if(this._states.currentTimeout&&this.options.unref){unrefTimer(this._states.currentTimeout)}return this};Cron.prototype._trigger=async function(initiationDate){this._states.blocking=true;this._states.currentRun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);if(this.options.catch){try{await this.fn(this,this.options.context)}catch(_e){if(isFunction(this.options.catch)){setTimeout(()=>this.options.catch(_e,this),0)}}}else{await this.fn(this,this.options.context)}this._states.previousRun=new CronDate(initiationDate,this.options.timezone||this.options.utcOffset);this._states.blocking=false};Cron.prototype.trigger=async function(){await this._trigger()};Cron.prototype._checkTrigger=function(target){const now=new Date,shouldRun=!this._states.paused&&now.getTime()>=target,isBlocked=this.blocking&&this.options.protect;if(shouldRun&&!isBlocked){this._states.maxRuns--;this._trigger()}else{if(shouldRun&&isBlocked&&isFunction(this.options.protect)){setTimeout(()=>this.options.protect(this),0)}}this.schedule(undefined,now)};Cron.prototype._next=function(prev){const hasPreviousRun=prev||this._states.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._states.once||new CronDate(prev,this.options.timezone||this.options.utcOffset).increment(this._states.pattern,this.options,hasPreviousRun);if(this._states.once&&this._states.once.getTime()<=prev.getTime()){return null}else if(nextRun===null||this._states.maxRuns<=0||this._states.kill||this.options.stopAt&&nextRun.getTime()>=this.options.stopAt.getTime()){return null}else{return nextRun}};Cron.Cron=Cron;Cron.scheduledJobs=scheduledJobs;return Cron});
{
"name": "croner",
"version": "6.0.0-dev.1",
"version": "6.0.0-dev.2",
"description": "Trigger functions and/or evaluate cron expressions in JavaScript. No dependencies. Most features. All environments.",

@@ -21,4 +21,4 @@ "author": "Hexagon <github.com/hexagon>",

"files": [
"dist/*.js",
"dist/*.cjs",
"dist/*.min.js",
"dist/*.min.cjs",
"types/*"

@@ -53,10 +53,10 @@ ],

"build:dist": "rollup -c ./rollup.config.js",
"build:minify": "uglifyjs dist/croner.umd.js --source-map -o dist/croner.umd.min.js && uglifyjs dist/croner.js --source-map -o dist/croner.min.js",
"build:minify": "uglifyjs dist/croner.umd.js --source-map -o dist/croner.umd.min.js && uglifyjs dist/croner.js --source-map -o dist/croner.min.js && uglifyjs dist/croner.cjs --source-map -o dist/croner.min.cjs",
"build:typings": "tsc && tsc --build tsconfig.cjs.json",
"build:docs": "((rm -rf docs/* || rd /S /Q docs) && jsdoc -c .jsdoc.json) || jsdoc -c .jsdoc.json"
"build:docs": "((rm -rf dist-docs/* || rd /S /Q dist-docs) && jsdoc -c .jsdoc.json) || jsdoc -c .jsdoc.json"
},
"type": "module",
"main": "./dist/croner.cjs",
"browser": "./dist/croner.umd.js",
"module": "./dist/croner.js",
"main": "./dist/croner.min.cjs",
"browser": "./dist/croner.umd.min.js",
"module": "./dist/croner.min.js",
"types": "./types/croner.d.ts",

@@ -68,7 +68,7 @@ "exports": {

"types": "./types/croner.d.ts",
"default": "./dist/croner.js"
"default": "./dist/croner.min.js"
},
"require": {
"types": "./types/croner.d.cts",
"default": "./dist/croner.cjs"
"default": "./dist/croner.min.cjs"
},

@@ -82,3 +82,2 @@ "browser": "./dist/croner.umd.js"

"jsdoc": "^4.0.0",
"jsdoc-chameleon-template": "^1.0.2",
"minitz": "^4.0.0",

@@ -90,3 +89,6 @@ "rollup": "3.17.1",

},
"license": "MIT"
"license": "MIT",
"dependencies": {
"taffydb": "^2.7.3"
}
}

@@ -15,3 +15,3 @@ <p align="center">

* Target different [time zones](docs/EXAMPLES.md#time-zone).
* Built in [Overrun protection](docs/EXAMPLES.md#overrun-protection) with callback
* Built in [overrun protection](docs/EXAMPLES.md#overrun-protection) with callback
* Built in [error handling](docs/EXAMPLES.md#error-handling) with callback

@@ -114,13 +114,12 @@ * Includes [TypeScript](https://www.typescriptlang.org/) typings.

If you are migrating from a different library such as `cron` or `node-cron`, or upgrading from a older version of croner, see [MIGRATION.md](docs/MIGRATION.md).
> **Note**
> If you are migrating from a different library such as `cron` or `node-cron`, or upgrading from a older version of croner, see [MIGRATION.md](docs/MIGRATION.md).
### Node.js
Install croner using your favorite package manager or CDN. then include it in you project:
```npm install croner --save```
Using Node.js or Bun
JavaScript
```javascript
// ESM Import ...
import Cron from "croner";
import { Cron } from "croner";

@@ -131,60 +130,10 @@ // ... or CommonJS Require

TypeScript
Using Deno
Notes for TypeScript:
* If using strict eslint rules, specifically new-cap combined with no-new, you need to import and use lowercase `cron` instead of `{ Cron }`.
```typescript
import { Cron } from "croner";
const job : Cron = new Cron("* * * * * *", () => {
console.log("This will run every second.");
});
```
### Bun
```bun add croner```
> **Note** If you encounter problems during installation, try using `bun add croner --backend=copyfile`.
```javascript
import Cron from "croner";
```
### Deno
JavaScript
```javascript
import Cron from "https://deno.land/x/croner@6.0.0-dev.0/dist/croner.js";
Cron("* * * * * *", () => {
console.log("This will run every second.");
});
```
TypeScript
```typescript
import { Cron } from "https://deno.land/x/croner@6.0.0-dev.0/dist/croner.js";
const _scheduler : Cron = new Cron("* * * * * *", () => {
console.log("This will run every second.");
});
```
### Browser
In a webpage using the UMD-module
#### Manual
* Download the latest [zipball](https://github.com/Hexagon/croner/archive/refs/heads/master.zip).
* Unpack the zip file.
* Grab ```croner.umd.min.js``` (UMD and standalone) or ```croner.min.js``` (ES-module) from the [dist/](/dist) folder.
#### CDN
To use as a [UMD](https://github.com/umdjs/umd)-module (stand alone, [RequireJS](https://requirejs.org/) etc.)
```html

@@ -194,18 +143,6 @@ <script src="https://cdn.jsdelivr.net/npm/croner@6/dist/croner.umd.min.js"></script>

To use as an [ES-module](https://developer.mozilla.org/en-USdocs/Web/JavaScript/Guide/Modules)
```html
<script type="module">
import Cron from "https://cdn.jsdelivr.net/npm/croner@6/dist/croner.min.js";
// ... see usage section ...
</script>
```
## Documentation
Full documentation available at [hexagon.github.io/croner](https://hexagon.github.io/croner/Cron.html).
> **Note**: If you are using version `5.x` or earlier, pay special attention to the changelog in [MIGRATION.md](docs/MIGRATION.md).
The short version:
### Signature

@@ -217,3 +154,3 @@

* [options](#options) (optional)
* scheduled function (optional)
* scheduleds function (optional)

@@ -225,13 +162,24 @@ ```javascript

job.schedule((/* optional */ job, /* optional */ context) => {});
```
// States
job.next( /*optional*/ previousRun ); // Get a Date object representing next run
job.enumerate(10, /*optional*/ startFrom ); // Get a array of Dates, containing next n runs according to pattern
job.msToNext( /*optional*/ previousRun ); // Milliseconds left to next execution
job.running(); // Scheduler is running (not paused or stopped)
job.busy(); // Returns boolean showing if a triggered function is currenly working
job.started(); // Date object showing when current (or last) run were started
job.previous( ); // Date object showing when previous job were started
The job will be sceduled to run at next matching time unless you supply option `{ paused: true }`. The `Cron(...)` constructor will return a Cron instance, later called `job`, which have a couple of methods and properties listed below.
// Job control
#### Status
```javascript
job.nextRun( /*optional*/ startFromDate ); // Get a Date object representing next run
job.nextRuns(10, /*optional*/ startFromDate ); // Get a array of Dates, containing next n runs according to pattern
job.msToNext( /*optional*/ startFromDate ); // Milliseconds left to next execution
job.currentRun(); // Date object showing when current (or last) run were started
job.previousRun( ); // Date object showing when previous job were started
job.isRunning(); // Indicates if there is a scheduled job (true or false)
job.isBusy(); // Indicates if a job is currenctly doing work (true or false)
job.getPattern(); // Returns the original pattern string
```
#### Control functions
```javascript
job.trigger(); // Force a trigger instantly

@@ -243,2 +191,8 @@ job.pause(); // Pause trigger

#### Properties
```javascript
job.name // Optional job name, populated if a name were passed to options
```
#### Options

@@ -321,4 +275,8 @@

This branch contains the latest stable code, released on npm's default channel (`latest`).
This branch contains the latest stable code, released on npm's default channel `latest`. You can install the latest stable revision by running the command below.
```
npm install croner --save
```
### Dev branch

@@ -334,4 +292,7 @@

A list of fixes and features currently released in the `dev` branch (but not in `master`) is available [here](https://github.com/Hexagon/croner/issues?q=is%3Aopen+is%3Aissue+label%3Areleased-in-dev)
> **Warning**
> Expect breaking changes if you do not pin to a specific version.
A list of fixes and features currently released in the `dev` branch is available [here](https://github.com/Hexagon/croner/issues?q=is%3Aopen+is%3Aissue+label%3Areleased-in-dev)
### Contributing

@@ -338,0 +299,0 @@

@@ -141,3 +141,2 @@ export type TimePoint = {

private _states;
pattern: CronPattern;
fn: Function | CronOptions;

@@ -150,3 +149,3 @@ /**

*/
next(prev?: CronDate | Date | string): Date | null;
nextRun(prev?: CronDate | Date | string): Date | null;
/**

@@ -159,4 +158,10 @@ * Find next n runs, based on supplied date. Strips milliseconds.

*/
enumerate(n: number, previous?: Date | string): Date[];
nextRuns(n: number, previous?: Date | string): Date[];
/**
* Return the original pattern, it there was one
*
* @returns {string|undefined} - Original pattern
*/
getPattern(): string | undefined;
/**
* Indicates wether or not the cron job is active, e.g. awaiting next trigger

@@ -167,3 +172,3 @@ * @public

*/
public running(): boolean;
public isRunning(): boolean;
/**

@@ -175,3 +180,3 @@ * Indicates wether or not the cron job is currently working

*/
public busy(): boolean;
public isBusy(): boolean;
/**

@@ -183,3 +188,3 @@ * Return current/previous run start time

*/
public started(): Date | null;
public currentRun(): Date | null;
/**

@@ -191,3 +196,3 @@ * Return previous run start time

*/
public previous(): Date | null;
public previousRun(): Date | null;
/**

@@ -288,64 +293,2 @@ * Returns number of milliseconds to next run

/**
* Name for each part of the cron pattern
* @typedef {("second" | "minute" | "hour" | "day" | "month" | "dayOfWeek")} CronPatternPart
*/
/**
* Offset, 0 or -1.
*
* 0 offset is used for seconds,minutes and hours as they start on 1.
* -1 on days and months, as they start on 0
*
* @typedef {Number} CronIndexOffset
*/
/**
* Create a CronPattern instance from pattern string ('* * * * * *')
* @constructor
* @param {string} pattern - Input pattern
* @param {string} timezone - Input timezone, used for '?'-substitution
*/
declare function CronPattern(pattern: string, timezone: string): void;
declare class CronPattern {
/**
* Name for each part of the cron pattern
* @typedef {("second" | "minute" | "hour" | "day" | "month" | "dayOfWeek")} CronPatternPart
*/
/**
* Offset, 0 or -1.
*
* 0 offset is used for seconds,minutes and hours as they start on 1.
* -1 on days and months, as they start on 0
*
* @typedef {Number} CronIndexOffset
*/
/**
* Create a CronPattern instance from pattern string ('* * * * * *')
* @constructor
* @param {string} pattern - Input pattern
* @param {string} timezone - Input timezone, used for '?'-substitution
*/
constructor(pattern: string, timezone: string);
pattern: string;
timezone: string;
second: any;
minute: any;
hour: any;
day: any;
month: any;
dayOfWeek: any;
lastDayOfMonth: boolean;
lastWeekdayOfMonth: boolean;
starDOM: boolean;
starDOW: boolean;
private parse;
private partToArray;
private throwAtIllegalCharacters;
private handleNumber;
private handleRangeWithStepping;
private handleRange;
private handleStepping;
private replaceAlphaDays;
private replaceAlphaMonths;
private handleNicknames;
}
/**
* Converts date to CronDate

@@ -352,0 +295,0 @@ * @constructor

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc