Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev 9.0 #261

Merged
merged 10 commits into from
Oct 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions deno.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@hexagon/croner",
"version": "9.0.0-dev.2",
"version": "9.0.0-dev.4",
"exports": "./src/croner.ts",
"lint": {
"include": ["src", "build"]
Expand All @@ -10,10 +10,11 @@
"lineWidth": 100
},
"tasks": {
"pre-commit": "deno fmt --check && deno lint && deno check src/croner.ts && deno test",
"pre-commit": "deno fmt --check && deno lint && deno check src/croner.ts",
"test": "deno test",
"build:clean": "deno run --allow-read --allow-write build/clean.ts",
"build:npm": "deno run --allow-read --allow-write build/npm.ts",
"build": "deno task build:clean && deno task pre-commit && deno run --allow-read --allow-write --allow-env --allow-run build/esbuild.ts && deno task build:npm",
"build": "deno task build:clean && deno task pre-commit && deno run --allow-read --allow-write --allow-env --allow-run build/esbuild.ts && deno task build:npm && deno task test",
"check-deps": "deno run -A jsr:@check/deps"
},
"imports": {
Expand Down
23 changes: 15 additions & 8 deletions src/croner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ class Cron {
* @param prev - Date to start from
* @returns Next run time
*/
public nextRun(prev?: CronDate | Date | string): Date | null {
public nextRun(prev?: CronDate | Date | string | null): Date | null {
const next = this._next(prev);
return next ? next.getDate(false) : null;
}
Expand All @@ -190,7 +190,7 @@ class Cron {
* @param previous - Date to start from
* @returns - Next n run times
*/
public nextRuns(n: number, previous: Date | string): Date[] {
public nextRuns(n: number, previous?: Date | string): Date[] {
if (this._states.maxRuns !== undefined && n > this._states.maxRuns) {
n = this._states.maxRuns;
}
Expand Down Expand Up @@ -277,7 +277,7 @@ class Cron {
const next = this._next(prev);

if (next) {
if (prev instanceof CronDate) {
if (prev instanceof CronDate || prev instanceof Date) {
return (next.getTime() - prev.getTime());
} else {
return (next.getTime() - new CronDate(prev).getTime());
Expand Down Expand Up @@ -421,6 +421,13 @@ class Cron {
await this._trigger();
}

/**
* Returns number of runs left, undefined = unlimited
*/
public runsLeft(): number | undefined {
return this._states.maxRuns;
}

/**
* Called when it's time to trigger.
* Checks if all conditions are currently met,
Expand Down Expand Up @@ -452,7 +459,7 @@ class Cron {
/**
* Internal version of next. Cron needs millseconds internally, hence _next.
*/
private _next(previousRun?: CronDate | Date | string) {
private _next(previousRun?: CronDate | Date | string | null) {
let hasPreviousRun = (previousRun || this._states.currentRun) ? true : false;

// If no previous run, and startAt and interval is set, calculate when the last run should have been
Expand Down Expand Up @@ -506,21 +513,21 @@ class Cron {
* Should only be called from the _next function.
*/
private _calculatePreviousRun(
prev: CronDate | Date | string | undefined,
prev: CronDate | Date | string | undefined | null,
hasPreviousRun: boolean,
): [CronDate | undefined, boolean] {
const now = new CronDate(undefined, this.options.timezone || this.options.utcOffset);
let newPrev: CronDate | undefined | null = prev as CronDate;
if ((this.options.startAt as CronDate).getTime() <= now.getTime()) {
newPrev = this.options.startAt as CronDate;
let prevTimePlusInterval = (prev as CronDate).getTime() + this.options.interval! * 1000;
let prevTimePlusInterval = (newPrev as CronDate).getTime() + this.options.interval! * 1000;
while (prevTimePlusInterval <= now.getTime()) {
newPrev = new CronDate(prev, this.options.timezone || this.options.utcOffset).increment(
newPrev = new CronDate(newPrev, this.options.timezone || this.options.utcOffset).increment(
this._states.pattern,
this.options,
true,
);
prevTimePlusInterval = (prev as CronDate).getTime() + this.options.interval! * 1000;
prevTimePlusInterval = (newPrev as CronDate).getTime() + this.options.interval! * 1000;
}
hasPreviousRun = true;
}
Expand Down
9 changes: 5 additions & 4 deletions src/date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,8 @@ class CronDate {
* Current full year, in local time or target timezone specified by `this.tz`
*/
year!: number;
constructor(d?: CronDate | Date | string, tz?: string | number) {

constructor(d?: CronDate | Date | string | null, tz?: string | number) {
/**
* TimeZone
* @type {string|number|undefined}
Expand Down Expand Up @@ -248,7 +249,7 @@ class CronDate {
private fromString(str: string) {
if (typeof this.tz === "number") {
// Parse without timezone
const inDate = minitz.fromTZISO(str, "UTC");
const inDate = minitz.fromTZISO(str);
this.ms = inDate.getUTCMilliseconds();
this.second = inDate.getUTCSeconds();
this.minute = inDate.getUTCMinutes();
Expand All @@ -257,8 +258,8 @@ class CronDate {
this.month = inDate.getUTCMonth();
this.year = inDate.getUTCFullYear();
this.apply();
} else if (this.tz === undefined) {
return this.fromDate(minitz.fromTZISO(str, this.tz === undefined ? "UTC" : this.tz));
} else {
return this.fromDate(minitz.fromTZISO(str, this.tz));
}
}

Expand Down
12 changes: 6 additions & 6 deletions src/helpers/minitz.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

minitz - MIT License - Hexagon <[email protected]>

Version 4.0.6
Version 5.0.0

------------------------------------------------------------------------------------

Expand Down Expand Up @@ -35,7 +35,7 @@ interface TimePoint {
h: number; // 0-24
i: number; // 0-60 Minute
s: number; // 0-60
tz: string; // Time zone in IANA database format 'Europe/Stockholm'
tz?: string; // Time zone in IANA database format 'Europe/Stockholm'
}

/**
Expand Down Expand Up @@ -83,7 +83,7 @@ function minitz(
* skipped, going from 23:59:59 to 01:00:00. Setting this flag makes the library throw an exception instead.
* @return {date} - Normal date object
*/
minitz.fromTZISO = (localTimeStr: string, tz: string, throwOnInvalid?: boolean) => {
minitz.fromTZISO = (localTimeStr: string, tz?: string, throwOnInvalid?: boolean) => {
return minitz.fromTZ(parseISOLocal(localTimeStr, tz), throwOnInvalid);
};

Expand Down Expand Up @@ -211,7 +211,7 @@ minitz.toTZ = function (d: Date, tzStr: string) {
*
* @returns {TimePoint}
*/
minitz.tp = (y: number, m: number, d: number, h: number, i: number, s: number, tz: string) => {
minitz.tp = (y: number, m: number, d: number, h: number, i: number, s: number, tz?: string) => {
return { y, m, d, h, i, s, tz: tz };
};

Expand All @@ -225,7 +225,7 @@ minitz.tp = (y: number, m: number, d: number, h: number, i: number, s: number, t
*
* @returns {number} - Offset in ms between UTC and timeZone
*/
function getTimezoneOffset(timeZone: string, date = new Date()) {
function getTimezoneOffset(timeZone?: string, date = new Date()) {
// Get timezone
const tz =
date.toLocaleString("en-US", { timeZone: timeZone, timeZoneName: "shortOffset" }).split(" ")
Expand All @@ -249,7 +249,7 @@ function getTimezoneOffset(timeZone: string, date = new Date()) {
* with all components, e.g. 2015-11-24T19:40:00
* @returns {TimePoint} - TimePoint instance from parsing the string
*/
function parseISOLocal(dtStr: string, tz: string) {
function parseISOLocal(dtStr: string, tz?: string) {
// Parse date using built in Date.parse
const pd = new Date(Date.parse(dtStr));

Expand Down
18 changes: 13 additions & 5 deletions src/pattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class CronPattern {
this.dayOfWeek = Array(7).fill(0); // 0-7 Where 0 = Sunday and 7=Sunday; Value is a bitmask

this.lastDayOfMonth = false;

this.starDOM = false; // Asterisk used for dayOfMonth
this.starDOW = false; // Asterisk used for dayOfWeek

Expand All @@ -67,7 +68,8 @@ class CronPattern {

private parse(): void {
// Sanity check
if (!(typeof this.pattern === "string")) {
//@ts-ignore string check
if (!(typeof this.pattern === "string" || this.pattern instanceof String)) {
throw new TypeError("CronPattern: Pattern has to be of type string.");
}

Expand Down Expand Up @@ -398,6 +400,11 @@ class CronPattern {
throw new TypeError("CronPattern: Syntax error, illegal stepping: '" + conf + "'");
}

// Inject missing asterisk (/3 insted of */3)
if (split[0] === "") {
split[0] = "*";
}

let start = 0;
if (split[0] !== "*") {
start = parseInt(split[0], 10) + valueIndexOffset;
Expand Down Expand Up @@ -494,13 +501,14 @@ class CronPattern {
private setNthWeekdayOfMonth(index: number, nthWeekday: number | string) {
if (typeof nthWeekday !== "number" && nthWeekday === "L") {
this["dayOfWeek"][index] = this["dayOfWeek"][index] | LAST_OCCURRENCE;
} else if (typeof nthWeekday === "number" && nthWeekday < 6 && nthWeekday > 0) {
this["dayOfWeek"][index] = this["dayOfWeek"][index] | OCCURRENCE_BITMASKS[nthWeekday - 1];
} else if (typeof nthWeekday === "number" && nthWeekday === ANY_OCCURRENCE) {
} else if (nthWeekday === ANY_OCCURRENCE) {
this["dayOfWeek"][index] = ANY_OCCURRENCE;
} else if (nthWeekday as number < 6 && nthWeekday as number > 0) {
this["dayOfWeek"][index] = this["dayOfWeek"][index] |
OCCURRENCE_BITMASKS[nthWeekday as number - 1];
} else {
throw new TypeError(
`CronPattern: nth weekday of of range, should be 1-5 or L. Value: ${nthWeekday}`,
`CronPattern: nth weekday out of range, should be 1-5 or L. Value: ${nthWeekday}, Type: ${typeof nthWeekday}`,
);
}
}
Expand Down
6 changes: 6 additions & 0 deletions test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { Cron as oldCron } from "@hexagon/croner";
import { Cron as newCron } from "./src/croner.ts";
let nextRunsNew = new newCron("@hourly").nextRuns(3, "2022-02-16T23:59:00");
console.log(nextRunsNew[0].getHours());
let nextRunsOld = new newCron("@hourly").nextRuns(3, "2022-02-16T23:59:00");
console.log(nextRunsOld[0].getHours());
Loading
Loading