@neramjs/cron 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +17 -0
- package/LICENSE +21 -0
- package/README.md +49 -2
- package/dist/cron.d.ts +41 -0
- package/dist/cron.global.js +2 -0
- package/dist/cron.js +273 -0
- package/dist/index.cjs +250 -0
- package/dist/index.d.cts +15 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +17 -0
- package/package.json +75 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.3.1 — 2026-12-06
|
|
4
|
+
|
|
5
|
+
- Add a `funding` link to GitHub Sponsors, shown on npm and by `npm fund`. No code changes.
|
|
6
|
+
|
|
7
|
+
## 0.3.0 — 2026-12-06
|
|
8
|
+
|
|
9
|
+
- First release as its own package. cron and Cron moved here from `neramjs/recur`, with the same API and the same
|
|
10
|
+
answers:
|
|
11
|
+
|
|
12
|
+
```diff
|
|
13
|
+
- import { cron } from 'neramjs/recur'
|
|
14
|
+
+ import { cron } from '@neramjs/cron'
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
The version starts at 0.3.0 to match neramjs 0.3.0, the first neramjs without `neramjs/recur`.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 neram contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,50 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @neramjs/cron
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Cron schedules in any time zone, with the right runs across daylight saving.
|
|
4
|
+
|
|
5
|
+
- five-field cron (`'0 9 * * MON-FRI'`), names and ranges, and `@daily`-style shortcuts
|
|
6
|
+
- the next run, the next 20 runs, or every run between two dates
|
|
7
|
+
- clear rules for the hour the clocks skip and the hour that happens twice
|
|
8
|
+
|
|
9
|
+
Dates and zones come from [neramjs](https://www.npmjs.com/package/neramjs). For calendar-style repeat rules (RRULE),
|
|
10
|
+
use [@neramjs/recur](https://www.npmjs.com/package/@neramjs/recur).
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm i neramjs @neramjs/cron
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
```js
|
|
17
|
+
import { cron } from '@neramjs/cron'
|
|
18
|
+
|
|
19
|
+
const job = cron('0 9 * * MON-FRI', { tz: 'Asia/Kolkata' })
|
|
20
|
+
job.after('2026-12-04 10:00', { as: 'iso' }) // '2026-12-07T03:30:00.000Z'
|
|
21
|
+
job.take(3, { from: '2026-12-04', as: 'local' }) // ['2026-12-04T09:00:00', '2026-12-07T09:00:00', ...]
|
|
22
|
+
job.between('2026-12-01', '2027-01-01', { as: 'epoch' })
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`as` picks how times come back: `'neram'` (the default), `'date'`, `'epoch'`, `'unix'`, `'iso'`, `'zoned'`,
|
|
26
|
+
`'local'`, `'record'`, or a function.
|
|
27
|
+
|
|
28
|
+
**Docs:** [Cron](https://neramjs-website.vercel.app/docs/cron/)
|
|
29
|
+
|
|
30
|
+
## Script tag
|
|
31
|
+
|
|
32
|
+
```html
|
|
33
|
+
<script src="https://cdn.jsdelivr.net/npm/neramjs/dist/neram.global.js"></script>
|
|
34
|
+
<script src="https://cdn.jsdelivr.net/npm/@neramjs/cron/dist/cron.global.js"></script>
|
|
35
|
+
<script>
|
|
36
|
+
neram.recur.cron('0 9 * * *', { tz: 'Asia/Kolkata' }).after()
|
|
37
|
+
</script>
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Load `neram.global.js` first. The cron and recur script builds both add to `neram.recur`, so a page can load either
|
|
41
|
+
or both.
|
|
42
|
+
|
|
43
|
+
## Versions
|
|
44
|
+
|
|
45
|
+
`@neramjs/cron` uses building blocks inside neramjs, so install matching versions: `@neramjs/cron` 0.3 needs
|
|
46
|
+
`neramjs` 0.3. A mismatch throws a clear error when the package loads, rather than giving wrong times.
|
|
47
|
+
|
|
48
|
+
## License
|
|
49
|
+
|
|
50
|
+
MIT
|
package/dist/cron.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type NeramInput } from 'neramjs';
|
|
2
|
+
import { Schedule } from 'neramjs/internal';
|
|
3
|
+
export interface CronOptions {
|
|
4
|
+
/** Zone the expression is read in. Default: neram's default zone (local). */
|
|
5
|
+
tz?: string;
|
|
6
|
+
/** Ignore occurrences before this. Also where all() starts (default: now). */
|
|
7
|
+
start?: NeramInput;
|
|
8
|
+
/** Last allowed occurrence (inclusive). */
|
|
9
|
+
end?: NeramInput;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A cron schedule. 5 fields (minute hour day-of-month month day-of-week) or 6 with seconds first.
|
|
13
|
+
* Supports * , - / names (JAN, MON), 7 = Sunday, @daily-style macros, and Quartz extras:
|
|
14
|
+
* L (last day), L-2, 15W (nearest weekday), LW, 5L (last Friday), 5#3 (third Friday).
|
|
15
|
+
* When both day-of-month and day-of-week are set, either may match (standard cron).
|
|
16
|
+
*
|
|
17
|
+
* Times are wall-clock times in `tz`: a time skipped by DST runs at the shifted time
|
|
18
|
+
* (02:30 → 03:30), and a time repeated by DST runs once.
|
|
19
|
+
*/
|
|
20
|
+
export declare class Cron extends Schedule {
|
|
21
|
+
#private;
|
|
22
|
+
readonly tz: string;
|
|
23
|
+
readonly allDay = false;
|
|
24
|
+
readonly expression: string;
|
|
25
|
+
readonly hasSeconds: boolean;
|
|
26
|
+
constructor(expression: string, opts?: CronOptions);
|
|
27
|
+
isInfinite(): boolean;
|
|
28
|
+
protected startMs(): number;
|
|
29
|
+
protected iterate(fromMs: number): Generator<number>;
|
|
30
|
+
toString(): string;
|
|
31
|
+
toJSON(): {
|
|
32
|
+
expression: string;
|
|
33
|
+
tz: string;
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Create a cron schedule.
|
|
38
|
+
* cron('0 9 * * MON-FRI', { tz: 'Asia/Kolkata' }).take(5, { as: 'iso' })
|
|
39
|
+
* cron('0 0 L * *', { tz: 'Europe/London' }).after()
|
|
40
|
+
*/
|
|
41
|
+
export declare function cron(expression: string, opts?: CronOptions): Cron;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! @neramjs/cron v0.3.1 | MIT | github.com/varksh05/neramjs */
|
|
2
|
+
(()=>{var X=Object.create;var v=Object.defineProperty;var G=Object.getOwnPropertyDescriptor;var Z=Object.getOwnPropertyNames;var q=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty;var K=(i,e,t)=>()=>{if(t)throw t[0];try{return i&&(e=i(i=0)),e}catch(n){throw t=[n],n}};var j=(i,e)=>()=>{try{return e||i((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},F=(i,e)=>{for(var t in e)v(i,t,{get:e[t],enumerable:!0})},A=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Z(e))!B.call(i,r)&&r!==t&&v(i,r,{get:()=>e[r],enumerable:!(n=G(e,r))||n.enumerable});return i};var y=(i,e,t)=>(t=i!=null?X(q(i)):{},A(e||!i||!i.__esModule?v(t,"default",{value:i,enumerable:!0}):t,i)),Q=i=>A(v({},"__esModule",{value:!0}),i);var E=j((re,T)=>{var S=globalThis.neram;if(typeof S!="function")throw new Error("@neramjs/cron: load neram.global.js before cron.global.js");T.exports={neram:S,Neram:S.Neram,Duration:S.Duration,duration:S.duration,isDuration:S.isDuration}});var U={};F(U,{Schedule:()=>z});function D(i,e){if(e!==void 0&&(!Number.isInteger(e)||e<0))throw new RangeError(`neram: ${i} must be a whole number of zero or more, got ${String(e)}`)}var W,O,ee,z,Y=K(()=>{"use strict";W=y(E(),1),O=y(E(),1),ee=400*366*864e5,z=class{originalOf(e){}durationOf(e){}coerce(e){let t=(0,O.neram)(e,{zone:this.tz}).valueOf();if(Number.isNaN(t))throw new RangeError(`neram: invalid date ${JSON.stringify(e)}`);return t}out(e,t){let n=(0,O.neram)(e,{zone:this.tz});if(typeof t=="function")return t(n);let r=()=>n.format(this.allDay?"YYYY-MM-DD":"YYYY-MM-DDTHH:mm:ss"),s;switch(t??"neram"){case"neram":s=n;break;case"date":s=n.toDate();break;case"epoch":s=e;break;case"unix":s=Math.floor(e/1e3);break;case"iso":s=n.toISOString();break;case"zoned":s=n.toZonedISOString();break;case"local":s=r();break;case"record":{let c={utc:n.toISOString(),local:r(),tz:n.timezone(),epoch:e,allDay:this.allDay},u=this.originalOf(e);u!==void 0&&(c.original=new Date(u).toISOString()),s=c;break}default:throw new RangeError(`neram: unknown output format "${String(t)}"`)}return s}all(e={}){if(D("limit",e.limit),e.limit===void 0&&this.isInfinite())throw new RangeError("neram: this schedule never ends; pass { limit } or use between()");let t=[];for(let n of this.iterate(this.startMs())){if(e.limit!==void 0&&t.length>=e.limit)break;t.push(this.out(n,e.as))}return t}between(e,t,n={}){D("limit",n.limit);let r=n.inclusive??!0,s=this.coerce(e),c=this.coerce(t),u=[];for(let o of this.iterate(s)){if(o>c||!r&&o===c)break;if(!(!r&&o===s)){if(n.limit!==void 0&&u.length>=n.limit)break;u.push(this.out(o,n.as))}}return u}after(e,t={}){let n=e===void 0?Date.now():this.coerce(e);for(let r of this.iterate(n))if(!(r===n&&!t.inclusive))return this.out(r,t.as);return null}before(e,t={}){let n=e===void 0?Date.now():this.coerce(e),r=Math.max(this.startMs(),n-ee),s=7*864e5;for(;;){let c=Math.max(r,n-s),u;for(let o of this.iterate(c)){if(o>n||o===n&&!t.inclusive)break;u=o}if(u!==void 0)return this.out(u,t.as);if(c<=r)return null;s*=8}}take(e,t={}){D("take(n)",e);let n=t.from===void 0?Date.now():this.coerce(t.from),r=[];if(e===0)return r;for(let s of this.iterate(n))if(s!==n&&(r.push(this.out(s,t.as)),r.length>=e))break;return r}includes(e){let t=this.coerce(e);for(let n of this.iterate(t))return n===t;return!1}instances(e,t,n){let r=(0,W.duration)(n.duration);if(!r.isValid()||r.valueOf()<0)throw new RangeError("neram: instances() needs a duration of zero or more");let s=this.coerce(e),c=this.coerce(t),u=Math.abs(r.asMilliseconds())+2*864e5,o=[];for(let a of this.iterate(s-u)){if(a>=c)break;let d=(0,O.neram)(a,{zone:this.tz}).add(this.durationOf(a)??r);d.valueOf()<=s&&a<s||o.push({start:this.out(a,n.as),end:this.out(d.valueOf(),n.as)})}return o}*[Symbol.iterator](){for(let e of this.iterate(this.startMs()))yield(0,O.neram)(e,{zone:this.tz})}}});var M=j((oe,J)=>{var L=globalThis.neram;if(typeof L!="function")throw new Error("@neramjs/cron: load neram.global.js before cron.global.js");J.exports={...L[Symbol.for("neramjs.internal")],Schedule:(Y(),Q(U)).Schedule}});var I={};F(I,{Cron:()=>k,Schedule:()=>V.Schedule,cron:()=>_});var $=y(M(),1);var R=y(E(),1),f=y(M(),1),te={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *"},H=["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"],P=["SUN","MON","TUE","WED","THU","FRI","SAT"];function N(i,e,t,n,r){let s=new Set,c=i.startsWith("*")||i==="?",u=o=>{let a=o.toUpperCase(),h=r?r.indexOf(a):-1,d=h>=0?h+(r===H?1:0):Number(o);if(!/^\d+$/.test(o)&&h<0)throw new RangeError(`neram: invalid cron ${e} "${o}"`);return d};for(let o of i.split(",")){if(!o)throw new RangeError(`neram: empty item in cron ${e}`);let[a,h]=o.split("/"),d=h===void 0?1:Number(h);if(!Number.isInteger(d)||d<1)throw new RangeError(`neram: invalid cron step "${o}"`);let m,g;if(a==="*"||a==="?")m=t,g=n;else if(a.includes("-")){let[l,w]=a.split("-");m=u(l),g=u(w)}else m=u(a),g=h===void 0?m:n;let b=l=>{if(l<t||l>n)throw new RangeError(`neram: cron ${e} value ${l} is out of range ${t}-${n}`)};if(b(m),b(g),m<=g)for(let l=m;l<=g;l+=d)s.add(l);else{let l=n-t+1,w=(g-m+l)%l;for(let p=0;p<=w;p+=d)s.add(t+(m-t+p)%l)}}return{values:s,any:c}}var k=class extends f.Schedule{tz;allDay=!1;expression;hasSeconds;#i;#a;#l;#n;#u;#t;#e={last:[],nearestWeekday:[],lastWeekday:!1};#r={nth:[],last:[]};#s;#o;constructor(e,t={}){super(),this.expression=e.trim(),this.tz=(0,f.normalizeZone)(t.tz??(0,R.neram)().timezone());let r=(te[this.expression.toLowerCase()]??this.expression).split(/\s+/);if(r.length!==5&&r.length!==6)throw new RangeError(`neram: cron needs 5 or 6 fields, got ${r.length} in "${e}"`);this.hasSeconds=r.length===6;let[s,c,u,o,a,h]=this.hasSeconds?r:["0",...r];this.#i=N(s,"second",0,59),this.#a=N(c,"minute",0,59),this.#l=N(u,"hour",0,23),this.#u=N(a,"month",1,12,H);let d=[];for(let g of o.split(",")){let b=g.toUpperCase(),l;if(b==="L")this.#e.last.push(0);else if(l=/^L-(\d+)$/.exec(b)){if(Number(l[1])>30)throw new RangeError(`neram: invalid cron day of month "${g}" (L-n needs n from 0 to 30)`);this.#e.last.push(Number(l[1]))}else if(b==="LW")this.#e.lastWeekday=!0;else if(l=/^(\d+)W$/.exec(b)){let w=Number(l[1]);if(w<1||w>31)throw new RangeError(`neram: invalid cron day of month "${g}" (nW needs n from 1 to 31)`);this.#e.nearestWeekday.push(w)}else d.push(g)}this.#n=d.length?N(d.join(","),"day of month",1,31):{values:new Set,any:!1},d.length!==o.split(",").length&&(this.#n.any=!1);let m=[];for(let g of h.split(",")){let b=g.toUpperCase(),l=p=>{let C=P.indexOf(p),x=C>=0?C:Number(p);if(!Number.isInteger(x)||x<0||x>7)throw new RangeError(`neram: invalid cron weekday "${p}"`);return x%7},w;(w=/^(\w+)#([1-5])$/.exec(b))?this.#r.nth.push([l(w[1]),Number(w[2])]):(w=/^(\w+)L$/.exec(b))?this.#r.last.push(l(w[1])):m.push(g)}this.#t=m.length?N(m.join(","),"day of week",0,7,P):{values:new Set,any:!1},m.length!==h.split(",").length&&(this.#t.any=!1),this.#t.values.delete(7)&&this.#t.values.add(0),this.#s=t.start===void 0?void 0:this.coerce(t.start),this.#o=t.end===void 0?void 0:this.coerce(t.end)}isInfinite(){return this.#o===void 0}startMs(){return this.#s??Date.now()}#c(e,t,n){let r=(Math.floor((0,f.utcFromParts)(e,t,n)/864e5)%7+11)%7,s=(0,f.daysInMonth)(e,t),c=()=>{if(this.#n.values.has(n)||this.#e.last.some(a=>n===s-a))return!0;let o=a=>{let h=Math.min(a,s),d=new Date((0,f.utcFromParts)(e,t,h)).getUTCDay();return d===6?h=h===1?3:h-1:d===0&&(h=h===s?h-2:h+1),h};if(this.#e.nearestWeekday.some(a=>n===o(a)))return!0;if(this.#e.lastWeekday){let a=s;for(;[0,6].includes(new Date((0,f.utcFromParts)(e,t,a)).getUTCDay());)a--;if(n===a)return!0}return!1},u=()=>this.#t.values.has(r)||this.#r.nth.some(([o,a])=>o===r&&Math.floor((n-1)/7)+1===a)||this.#r.last.some(o=>o===r&&n+7>s);return this.#n.any||this.#t.any?c()&&u():c()||u()}#h(e){let t=new Date(e).getUTCFullYear()+400;for(;;){let{y:n,M:r,D:s,h:c,m:u,s:o}=(0,f.wallOfMs)(e);if(n>t||n>9999)return null;if(!this.#u.values.has(r+1)){e=(0,f.utcFromParts)(n,r+1,1);continue}if(!this.#c(n,r,s)){e=(0,f.utcFromParts)(n,r,s+1);continue}if(!this.#l.values.has(c)){e=(0,f.utcFromParts)(n,r,s,c+1);continue}if(!this.#a.values.has(u)){e=(0,f.utcFromParts)(n,r,s,c,u+1);continue}if(!this.#i.values.has(o)){e=(0,f.utcFromParts)(n,r,s,c,u,o+1);continue}return e}}*iterate(e){let t=e;this.#s!==void 0&&(t=Math.max(t,this.#s)),Number.isFinite(t)||(t=Date.now());let n=this.hasSeconds?1e3:6e4,r=(0,R.neram)(t,{zone:this.tz}),[s,c,u,o,a,h,d]=r.toArray(),m=(0,f.utcFromParts)(s,c,u,o,a,this.hasSeconds?h:0);(d>0||!this.hasSeconds&&(h>0||d>0))&&(m+=n);let g=-1/0;for(;;){let b=this.#h(m);if(b===null)return;let l=(0,f.wallToEpoch)((0,f.wallOfMs)(b),this.tz);if(m=b+n,!(l<t||l<=g)){if(this.#o!==void 0&&l>this.#o)return;g=l,yield l}}}toString(){return this.expression}toJSON(){return{expression:this.expression,tz:this.tz}}};function _(i,e={}){return new k(i,e)}var V=y(M(),1);if($.INTERNAL_VERSION!==1)throw new Error(`@neramjs/cron needs a neramjs version with internals v1, but the installed neramjs has v${$.INTERNAL_VERSION}. Install matching versions of neramjs and @neramjs/cron.`);globalThis.neram.recur=Object.assign(globalThis.neram.recur||{},I);})();
|
package/dist/cron.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { neram } from 'neramjs';
|
|
2
|
+
import { daysInMonth, normalizeZone, Schedule, utcFromParts, wallOfMs, wallToEpoch } from 'neramjs/internal';
|
|
3
|
+
const MACROS = {
|
|
4
|
+
'@yearly': '0 0 1 1 *',
|
|
5
|
+
'@annually': '0 0 1 1 *',
|
|
6
|
+
'@monthly': '0 0 1 * *',
|
|
7
|
+
'@weekly': '0 0 * * 0',
|
|
8
|
+
'@daily': '0 0 * * *',
|
|
9
|
+
'@midnight': '0 0 * * *',
|
|
10
|
+
'@hourly': '0 * * * *',
|
|
11
|
+
};
|
|
12
|
+
const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
|
|
13
|
+
const DAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
|
|
14
|
+
function parseField(src, name, min, max, names) {
|
|
15
|
+
const values = new Set();
|
|
16
|
+
// Like Vixie cron, a field starting with * (including */2) counts as unrestricted.
|
|
17
|
+
const any = src.startsWith('*') || src === '?';
|
|
18
|
+
const toNum = (s) => {
|
|
19
|
+
const up = s.toUpperCase();
|
|
20
|
+
const i = names ? names.indexOf(up) : -1;
|
|
21
|
+
const n = i >= 0 ? i + (names === MONTHS ? 1 : 0) : Number(s);
|
|
22
|
+
if (!/^\d+$/.test(s) && i < 0)
|
|
23
|
+
throw new RangeError(`neram: invalid cron ${name} "${s}"`);
|
|
24
|
+
return n;
|
|
25
|
+
};
|
|
26
|
+
for (const part of src.split(',')) {
|
|
27
|
+
if (!part)
|
|
28
|
+
throw new RangeError(`neram: empty item in cron ${name}`);
|
|
29
|
+
const [range, stepStr] = part.split('/');
|
|
30
|
+
const step = stepStr === undefined ? 1 : Number(stepStr);
|
|
31
|
+
if (!Number.isInteger(step) || step < 1)
|
|
32
|
+
throw new RangeError(`neram: invalid cron step "${part}"`);
|
|
33
|
+
let lo, hi;
|
|
34
|
+
if (range === '*' || range === '?') {
|
|
35
|
+
lo = min;
|
|
36
|
+
hi = max;
|
|
37
|
+
}
|
|
38
|
+
else if (range.includes('-')) {
|
|
39
|
+
const [a, b] = range.split('-');
|
|
40
|
+
lo = toNum(a);
|
|
41
|
+
hi = toNum(b);
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
lo = toNum(range);
|
|
45
|
+
hi = stepStr === undefined ? lo : max;
|
|
46
|
+
}
|
|
47
|
+
const span = (v) => {
|
|
48
|
+
if (v < min || v > max)
|
|
49
|
+
throw new RangeError(`neram: cron ${name} value ${v} is out of range ${min}-${max}`);
|
|
50
|
+
};
|
|
51
|
+
span(lo);
|
|
52
|
+
span(hi);
|
|
53
|
+
if (lo <= hi) {
|
|
54
|
+
for (let v = lo; v <= hi; v += step)
|
|
55
|
+
values.add(v);
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
// wrap-around range such as FRI-MON or 22-2
|
|
59
|
+
const size = max - min + 1;
|
|
60
|
+
const len = (hi - lo + size) % size;
|
|
61
|
+
for (let i = 0; i <= len; i += step)
|
|
62
|
+
values.add(min + ((lo - min + i) % size));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return { values, any };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* A cron schedule. 5 fields (minute hour day-of-month month day-of-week) or 6 with seconds first.
|
|
69
|
+
* Supports * , - / names (JAN, MON), 7 = Sunday, @daily-style macros, and Quartz extras:
|
|
70
|
+
* L (last day), L-2, 15W (nearest weekday), LW, 5L (last Friday), 5#3 (third Friday).
|
|
71
|
+
* When both day-of-month and day-of-week are set, either may match (standard cron).
|
|
72
|
+
*
|
|
73
|
+
* Times are wall-clock times in `tz`: a time skipped by DST runs at the shifted time
|
|
74
|
+
* (02:30 → 03:30), and a time repeated by DST runs once.
|
|
75
|
+
*/
|
|
76
|
+
export class Cron extends Schedule {
|
|
77
|
+
tz;
|
|
78
|
+
allDay = false;
|
|
79
|
+
expression;
|
|
80
|
+
hasSeconds;
|
|
81
|
+
#sec;
|
|
82
|
+
#min;
|
|
83
|
+
#hour;
|
|
84
|
+
#dom;
|
|
85
|
+
#month;
|
|
86
|
+
#dow;
|
|
87
|
+
#domX = { last: [], nearestWeekday: [], lastWeekday: false };
|
|
88
|
+
#dowX = { nth: [], last: [] };
|
|
89
|
+
#startMs;
|
|
90
|
+
#endMs;
|
|
91
|
+
constructor(expression, opts = {}) {
|
|
92
|
+
super();
|
|
93
|
+
this.expression = expression.trim();
|
|
94
|
+
this.tz = normalizeZone(opts.tz ?? neram().timezone());
|
|
95
|
+
const expanded = MACROS[this.expression.toLowerCase()] ?? this.expression;
|
|
96
|
+
const parts = expanded.split(/\s+/);
|
|
97
|
+
if (parts.length !== 5 && parts.length !== 6) {
|
|
98
|
+
throw new RangeError(`neram: cron needs 5 or 6 fields, got ${parts.length} in "${expression}"`);
|
|
99
|
+
}
|
|
100
|
+
this.hasSeconds = parts.length === 6;
|
|
101
|
+
const [sec, min, hour, dom, month, dow] = this.hasSeconds ? parts : ['0', ...parts];
|
|
102
|
+
this.#sec = parseField(sec, 'second', 0, 59);
|
|
103
|
+
this.#min = parseField(min, 'minute', 0, 59);
|
|
104
|
+
this.#hour = parseField(hour, 'hour', 0, 23);
|
|
105
|
+
this.#month = parseField(month, 'month', 1, 12, MONTHS);
|
|
106
|
+
// Day of month: pull out L / L-n / nW / LW before the generic parser.
|
|
107
|
+
const domPlain = [];
|
|
108
|
+
for (const item of dom.split(',')) {
|
|
109
|
+
const up = item.toUpperCase();
|
|
110
|
+
let m;
|
|
111
|
+
if (up === 'L')
|
|
112
|
+
this.#domX.last.push(0);
|
|
113
|
+
else if ((m = /^L-(\d+)$/.exec(up))) {
|
|
114
|
+
if (Number(m[1]) > 30)
|
|
115
|
+
throw new RangeError(`neram: invalid cron day of month "${item}" (L-n needs n from 0 to 30)`);
|
|
116
|
+
this.#domX.last.push(Number(m[1]));
|
|
117
|
+
}
|
|
118
|
+
else if (up === 'LW')
|
|
119
|
+
this.#domX.lastWeekday = true;
|
|
120
|
+
else if ((m = /^(\d+)W$/.exec(up))) {
|
|
121
|
+
const n = Number(m[1]);
|
|
122
|
+
if (n < 1 || n > 31)
|
|
123
|
+
throw new RangeError(`neram: invalid cron day of month "${item}" (nW needs n from 1 to 31)`);
|
|
124
|
+
this.#domX.nearestWeekday.push(n);
|
|
125
|
+
}
|
|
126
|
+
else
|
|
127
|
+
domPlain.push(item);
|
|
128
|
+
}
|
|
129
|
+
this.#dom = domPlain.length ? parseField(domPlain.join(','), 'day of month', 1, 31) : { values: new Set(), any: false };
|
|
130
|
+
if (domPlain.length !== dom.split(',').length)
|
|
131
|
+
this.#dom.any = false;
|
|
132
|
+
// Day of week: 5#3, 5L, and 7 as Sunday.
|
|
133
|
+
const dowPlain = [];
|
|
134
|
+
for (const item of dow.split(',')) {
|
|
135
|
+
const up = item.toUpperCase();
|
|
136
|
+
const dayNum = (s) => {
|
|
137
|
+
const i = DAYS.indexOf(s);
|
|
138
|
+
const n = i >= 0 ? i : Number(s);
|
|
139
|
+
if (!Number.isInteger(n) || n < 0 || n > 7)
|
|
140
|
+
throw new RangeError(`neram: invalid cron weekday "${s}"`);
|
|
141
|
+
return n % 7;
|
|
142
|
+
};
|
|
143
|
+
let m;
|
|
144
|
+
if ((m = /^(\w+)#([1-5])$/.exec(up)))
|
|
145
|
+
this.#dowX.nth.push([dayNum(m[1]), Number(m[2])]);
|
|
146
|
+
else if ((m = /^(\w+)L$/.exec(up)))
|
|
147
|
+
this.#dowX.last.push(dayNum(m[1]));
|
|
148
|
+
else
|
|
149
|
+
dowPlain.push(item);
|
|
150
|
+
}
|
|
151
|
+
this.#dow = dowPlain.length ? parseField(dowPlain.join(','), 'day of week', 0, 7, DAYS) : { values: new Set(), any: false };
|
|
152
|
+
if (dowPlain.length !== dow.split(',').length)
|
|
153
|
+
this.#dow.any = false;
|
|
154
|
+
if (this.#dow.values.delete(7))
|
|
155
|
+
this.#dow.values.add(0);
|
|
156
|
+
this.#startMs = opts.start === undefined ? undefined : this.coerce(opts.start);
|
|
157
|
+
this.#endMs = opts.end === undefined ? undefined : this.coerce(opts.end);
|
|
158
|
+
}
|
|
159
|
+
isInfinite() {
|
|
160
|
+
return this.#endMs === undefined;
|
|
161
|
+
}
|
|
162
|
+
startMs() {
|
|
163
|
+
return this.#startMs ?? Date.now();
|
|
164
|
+
}
|
|
165
|
+
#dayMatches(y, M, D) {
|
|
166
|
+
const dow = (((Math.floor(utcFromParts(y, M, D) / 86400000) % 7) + 11) % 7);
|
|
167
|
+
const dim = daysInMonth(y, M);
|
|
168
|
+
const domOk = () => {
|
|
169
|
+
if (this.#dom.values.has(D))
|
|
170
|
+
return true;
|
|
171
|
+
if (this.#domX.last.some((off) => D === dim - off))
|
|
172
|
+
return true;
|
|
173
|
+
const weekdayNear = (target) => {
|
|
174
|
+
let t = Math.min(target, dim);
|
|
175
|
+
const wd = new Date(utcFromParts(y, M, t)).getUTCDay();
|
|
176
|
+
if (wd === 6)
|
|
177
|
+
t = t === 1 ? 3 : t - 1;
|
|
178
|
+
else if (wd === 0)
|
|
179
|
+
t = t === dim ? t - 2 : t + 1;
|
|
180
|
+
return t;
|
|
181
|
+
};
|
|
182
|
+
if (this.#domX.nearestWeekday.some((n) => D === weekdayNear(n)))
|
|
183
|
+
return true;
|
|
184
|
+
if (this.#domX.lastWeekday) {
|
|
185
|
+
let t = dim;
|
|
186
|
+
while ([0, 6].includes(new Date(utcFromParts(y, M, t)).getUTCDay()))
|
|
187
|
+
t--;
|
|
188
|
+
if (D === t)
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
return false;
|
|
192
|
+
};
|
|
193
|
+
const dowOk = () => this.#dow.values.has(dow) ||
|
|
194
|
+
this.#dowX.nth.some(([w, n]) => w === dow && Math.floor((D - 1) / 7) + 1 === n) ||
|
|
195
|
+
this.#dowX.last.some((w) => w === dow && D + 7 > dim);
|
|
196
|
+
// Standard cron: if either field is unrestricted both must match, otherwise either may.
|
|
197
|
+
if (this.#dom.any || this.#dow.any)
|
|
198
|
+
return domOk() && dowOk();
|
|
199
|
+
return domOk() || dowOk();
|
|
200
|
+
}
|
|
201
|
+
/** Next matching wall time (UTC-ms of the wall clock) at or after `cur`, or null. */
|
|
202
|
+
#nextWall(cur) {
|
|
203
|
+
const limitYear = new Date(cur).getUTCFullYear() + 400;
|
|
204
|
+
for (;;) {
|
|
205
|
+
const { y, M, D, h, m, s } = wallOfMs(cur);
|
|
206
|
+
if (y > limitYear || y > 9999)
|
|
207
|
+
return null;
|
|
208
|
+
if (!this.#month.values.has(M + 1)) {
|
|
209
|
+
cur = utcFromParts(y, M + 1, 1);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (!this.#dayMatches(y, M, D)) {
|
|
213
|
+
cur = utcFromParts(y, M, D + 1);
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
if (!this.#hour.values.has(h)) {
|
|
217
|
+
cur = utcFromParts(y, M, D, h + 1);
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
if (!this.#min.values.has(m)) {
|
|
221
|
+
cur = utcFromParts(y, M, D, h, m + 1);
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (!this.#sec.values.has(s)) {
|
|
225
|
+
cur = utcFromParts(y, M, D, h, m, s + 1);
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
return cur;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
*iterate(fromMs) {
|
|
232
|
+
let from = fromMs;
|
|
233
|
+
if (this.#startMs !== undefined)
|
|
234
|
+
from = Math.max(from, this.#startMs);
|
|
235
|
+
if (!Number.isFinite(from))
|
|
236
|
+
from = Date.now();
|
|
237
|
+
const unit = this.hasSeconds ? 1000 : 60000;
|
|
238
|
+
const w = neram(from, { zone: this.tz });
|
|
239
|
+
const [y, M, D, h, m, s, ms] = w.toArray();
|
|
240
|
+
// Start at the first whole unit at or after `from`.
|
|
241
|
+
let cur = utcFromParts(y, M, D, h, m, this.hasSeconds ? s : 0);
|
|
242
|
+
if (ms > 0 || (!this.hasSeconds && (s > 0 || ms > 0)))
|
|
243
|
+
cur += unit;
|
|
244
|
+
let last = -Infinity;
|
|
245
|
+
for (;;) {
|
|
246
|
+
const next = this.#nextWall(cur);
|
|
247
|
+
if (next === null)
|
|
248
|
+
return;
|
|
249
|
+
const inst = wallToEpoch(wallOfMs(next), this.tz);
|
|
250
|
+
cur = next + unit;
|
|
251
|
+
if (inst < from || inst <= last)
|
|
252
|
+
continue;
|
|
253
|
+
if (this.#endMs !== undefined && inst > this.#endMs)
|
|
254
|
+
return;
|
|
255
|
+
last = inst;
|
|
256
|
+
yield inst;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
toString() {
|
|
260
|
+
return this.expression;
|
|
261
|
+
}
|
|
262
|
+
toJSON() {
|
|
263
|
+
return { expression: this.expression, tz: this.tz };
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Create a cron schedule.
|
|
268
|
+
* cron('0 9 * * MON-FRI', { tz: 'Asia/Kolkata' }).take(5, { as: 'iso' })
|
|
269
|
+
* cron('0 0 L * *', { tz: 'Europe/London' }).after()
|
|
270
|
+
*/
|
|
271
|
+
export function cron(expression, opts = {}) {
|
|
272
|
+
return new Cron(expression, opts);
|
|
273
|
+
}
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/*! @neramjs/cron v0.3.1 | MIT | github.com/varksh05/neramjs */
|
|
2
|
+
"use strict";
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/index.ts
|
|
22
|
+
var index_exports = {};
|
|
23
|
+
__export(index_exports, {
|
|
24
|
+
Cron: () => Cron,
|
|
25
|
+
Schedule: () => import_internal3.Schedule,
|
|
26
|
+
cron: () => cron
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(index_exports);
|
|
29
|
+
var import_internal2 = require("neramjs/internal");
|
|
30
|
+
|
|
31
|
+
// src/cron.ts
|
|
32
|
+
var import_neramjs = require("neramjs");
|
|
33
|
+
var import_internal = require("neramjs/internal");
|
|
34
|
+
var MACROS = {
|
|
35
|
+
"@yearly": "0 0 1 1 *",
|
|
36
|
+
"@annually": "0 0 1 1 *",
|
|
37
|
+
"@monthly": "0 0 1 * *",
|
|
38
|
+
"@weekly": "0 0 * * 0",
|
|
39
|
+
"@daily": "0 0 * * *",
|
|
40
|
+
"@midnight": "0 0 * * *",
|
|
41
|
+
"@hourly": "0 * * * *"
|
|
42
|
+
};
|
|
43
|
+
var MONTHS = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
|
|
44
|
+
var DAYS = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
|
|
45
|
+
function parseField(src, name, min, max, names) {
|
|
46
|
+
const values = /* @__PURE__ */ new Set();
|
|
47
|
+
const any = src.startsWith("*") || src === "?";
|
|
48
|
+
const toNum = (s) => {
|
|
49
|
+
const up = s.toUpperCase();
|
|
50
|
+
const i = names ? names.indexOf(up) : -1;
|
|
51
|
+
const n = i >= 0 ? i + (names === MONTHS ? 1 : 0) : Number(s);
|
|
52
|
+
if (!/^\d+$/.test(s) && i < 0) throw new RangeError(`neram: invalid cron ${name} "${s}"`);
|
|
53
|
+
return n;
|
|
54
|
+
};
|
|
55
|
+
for (const part of src.split(",")) {
|
|
56
|
+
if (!part) throw new RangeError(`neram: empty item in cron ${name}`);
|
|
57
|
+
const [range, stepStr] = part.split("/");
|
|
58
|
+
const step = stepStr === void 0 ? 1 : Number(stepStr);
|
|
59
|
+
if (!Number.isInteger(step) || step < 1) throw new RangeError(`neram: invalid cron step "${part}"`);
|
|
60
|
+
let lo, hi;
|
|
61
|
+
if (range === "*" || range === "?") {
|
|
62
|
+
lo = min;
|
|
63
|
+
hi = max;
|
|
64
|
+
} else if (range.includes("-")) {
|
|
65
|
+
const [a, b] = range.split("-");
|
|
66
|
+
lo = toNum(a);
|
|
67
|
+
hi = toNum(b);
|
|
68
|
+
} else {
|
|
69
|
+
lo = toNum(range);
|
|
70
|
+
hi = stepStr === void 0 ? lo : max;
|
|
71
|
+
}
|
|
72
|
+
const span = (v) => {
|
|
73
|
+
if (v < min || v > max) throw new RangeError(`neram: cron ${name} value ${v} is out of range ${min}-${max}`);
|
|
74
|
+
};
|
|
75
|
+
span(lo);
|
|
76
|
+
span(hi);
|
|
77
|
+
if (lo <= hi) {
|
|
78
|
+
for (let v = lo; v <= hi; v += step) values.add(v);
|
|
79
|
+
} else {
|
|
80
|
+
const size = max - min + 1;
|
|
81
|
+
const len = (hi - lo + size) % size;
|
|
82
|
+
for (let i = 0; i <= len; i += step) values.add(min + (lo - min + i) % size);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return { values, any };
|
|
86
|
+
}
|
|
87
|
+
var Cron = class extends import_internal.Schedule {
|
|
88
|
+
tz;
|
|
89
|
+
allDay = false;
|
|
90
|
+
expression;
|
|
91
|
+
hasSeconds;
|
|
92
|
+
#sec;
|
|
93
|
+
#min;
|
|
94
|
+
#hour;
|
|
95
|
+
#dom;
|
|
96
|
+
#month;
|
|
97
|
+
#dow;
|
|
98
|
+
#domX = { last: [], nearestWeekday: [], lastWeekday: false };
|
|
99
|
+
#dowX = { nth: [], last: [] };
|
|
100
|
+
#startMs;
|
|
101
|
+
#endMs;
|
|
102
|
+
constructor(expression, opts = {}) {
|
|
103
|
+
super();
|
|
104
|
+
this.expression = expression.trim();
|
|
105
|
+
this.tz = (0, import_internal.normalizeZone)(opts.tz ?? (0, import_neramjs.neram)().timezone());
|
|
106
|
+
const expanded = MACROS[this.expression.toLowerCase()] ?? this.expression;
|
|
107
|
+
const parts = expanded.split(/\s+/);
|
|
108
|
+
if (parts.length !== 5 && parts.length !== 6) {
|
|
109
|
+
throw new RangeError(`neram: cron needs 5 or 6 fields, got ${parts.length} in "${expression}"`);
|
|
110
|
+
}
|
|
111
|
+
this.hasSeconds = parts.length === 6;
|
|
112
|
+
const [sec, min, hour, dom, month, dow] = this.hasSeconds ? parts : ["0", ...parts];
|
|
113
|
+
this.#sec = parseField(sec, "second", 0, 59);
|
|
114
|
+
this.#min = parseField(min, "minute", 0, 59);
|
|
115
|
+
this.#hour = parseField(hour, "hour", 0, 23);
|
|
116
|
+
this.#month = parseField(month, "month", 1, 12, MONTHS);
|
|
117
|
+
const domPlain = [];
|
|
118
|
+
for (const item of dom.split(",")) {
|
|
119
|
+
const up = item.toUpperCase();
|
|
120
|
+
let m;
|
|
121
|
+
if (up === "L") this.#domX.last.push(0);
|
|
122
|
+
else if (m = /^L-(\d+)$/.exec(up)) {
|
|
123
|
+
if (Number(m[1]) > 30) throw new RangeError(`neram: invalid cron day of month "${item}" (L-n needs n from 0 to 30)`);
|
|
124
|
+
this.#domX.last.push(Number(m[1]));
|
|
125
|
+
} else if (up === "LW") this.#domX.lastWeekday = true;
|
|
126
|
+
else if (m = /^(\d+)W$/.exec(up)) {
|
|
127
|
+
const n = Number(m[1]);
|
|
128
|
+
if (n < 1 || n > 31) throw new RangeError(`neram: invalid cron day of month "${item}" (nW needs n from 1 to 31)`);
|
|
129
|
+
this.#domX.nearestWeekday.push(n);
|
|
130
|
+
} else domPlain.push(item);
|
|
131
|
+
}
|
|
132
|
+
this.#dom = domPlain.length ? parseField(domPlain.join(","), "day of month", 1, 31) : { values: /* @__PURE__ */ new Set(), any: false };
|
|
133
|
+
if (domPlain.length !== dom.split(",").length) this.#dom.any = false;
|
|
134
|
+
const dowPlain = [];
|
|
135
|
+
for (const item of dow.split(",")) {
|
|
136
|
+
const up = item.toUpperCase();
|
|
137
|
+
const dayNum = (s) => {
|
|
138
|
+
const i = DAYS.indexOf(s);
|
|
139
|
+
const n = i >= 0 ? i : Number(s);
|
|
140
|
+
if (!Number.isInteger(n) || n < 0 || n > 7) throw new RangeError(`neram: invalid cron weekday "${s}"`);
|
|
141
|
+
return n % 7;
|
|
142
|
+
};
|
|
143
|
+
let m;
|
|
144
|
+
if (m = /^(\w+)#([1-5])$/.exec(up)) this.#dowX.nth.push([dayNum(m[1]), Number(m[2])]);
|
|
145
|
+
else if (m = /^(\w+)L$/.exec(up)) this.#dowX.last.push(dayNum(m[1]));
|
|
146
|
+
else dowPlain.push(item);
|
|
147
|
+
}
|
|
148
|
+
this.#dow = dowPlain.length ? parseField(dowPlain.join(","), "day of week", 0, 7, DAYS) : { values: /* @__PURE__ */ new Set(), any: false };
|
|
149
|
+
if (dowPlain.length !== dow.split(",").length) this.#dow.any = false;
|
|
150
|
+
if (this.#dow.values.delete(7)) this.#dow.values.add(0);
|
|
151
|
+
this.#startMs = opts.start === void 0 ? void 0 : this.coerce(opts.start);
|
|
152
|
+
this.#endMs = opts.end === void 0 ? void 0 : this.coerce(opts.end);
|
|
153
|
+
}
|
|
154
|
+
isInfinite() {
|
|
155
|
+
return this.#endMs === void 0;
|
|
156
|
+
}
|
|
157
|
+
startMs() {
|
|
158
|
+
return this.#startMs ?? Date.now();
|
|
159
|
+
}
|
|
160
|
+
#dayMatches(y, M, D) {
|
|
161
|
+
const dow = (Math.floor((0, import_internal.utcFromParts)(y, M, D) / 864e5) % 7 + 11) % 7;
|
|
162
|
+
const dim = (0, import_internal.daysInMonth)(y, M);
|
|
163
|
+
const domOk = () => {
|
|
164
|
+
if (this.#dom.values.has(D)) return true;
|
|
165
|
+
if (this.#domX.last.some((off) => D === dim - off)) return true;
|
|
166
|
+
const weekdayNear = (target) => {
|
|
167
|
+
let t = Math.min(target, dim);
|
|
168
|
+
const wd = new Date((0, import_internal.utcFromParts)(y, M, t)).getUTCDay();
|
|
169
|
+
if (wd === 6) t = t === 1 ? 3 : t - 1;
|
|
170
|
+
else if (wd === 0) t = t === dim ? t - 2 : t + 1;
|
|
171
|
+
return t;
|
|
172
|
+
};
|
|
173
|
+
if (this.#domX.nearestWeekday.some((n) => D === weekdayNear(n))) return true;
|
|
174
|
+
if (this.#domX.lastWeekday) {
|
|
175
|
+
let t = dim;
|
|
176
|
+
while ([0, 6].includes(new Date((0, import_internal.utcFromParts)(y, M, t)).getUTCDay())) t--;
|
|
177
|
+
if (D === t) return true;
|
|
178
|
+
}
|
|
179
|
+
return false;
|
|
180
|
+
};
|
|
181
|
+
const dowOk = () => this.#dow.values.has(dow) || this.#dowX.nth.some(([w, n]) => w === dow && Math.floor((D - 1) / 7) + 1 === n) || this.#dowX.last.some((w) => w === dow && D + 7 > dim);
|
|
182
|
+
if (this.#dom.any || this.#dow.any) return domOk() && dowOk();
|
|
183
|
+
return domOk() || dowOk();
|
|
184
|
+
}
|
|
185
|
+
/** Next matching wall time (UTC-ms of the wall clock) at or after `cur`, or null. */
|
|
186
|
+
#nextWall(cur) {
|
|
187
|
+
const limitYear = new Date(cur).getUTCFullYear() + 400;
|
|
188
|
+
for (; ; ) {
|
|
189
|
+
const { y, M, D, h, m, s } = (0, import_internal.wallOfMs)(cur);
|
|
190
|
+
if (y > limitYear || y > 9999) return null;
|
|
191
|
+
if (!this.#month.values.has(M + 1)) {
|
|
192
|
+
cur = (0, import_internal.utcFromParts)(y, M + 1, 1);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (!this.#dayMatches(y, M, D)) {
|
|
196
|
+
cur = (0, import_internal.utcFromParts)(y, M, D + 1);
|
|
197
|
+
continue;
|
|
198
|
+
}
|
|
199
|
+
if (!this.#hour.values.has(h)) {
|
|
200
|
+
cur = (0, import_internal.utcFromParts)(y, M, D, h + 1);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (!this.#min.values.has(m)) {
|
|
204
|
+
cur = (0, import_internal.utcFromParts)(y, M, D, h, m + 1);
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
if (!this.#sec.values.has(s)) {
|
|
208
|
+
cur = (0, import_internal.utcFromParts)(y, M, D, h, m, s + 1);
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
return cur;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
*iterate(fromMs) {
|
|
215
|
+
let from = fromMs;
|
|
216
|
+
if (this.#startMs !== void 0) from = Math.max(from, this.#startMs);
|
|
217
|
+
if (!Number.isFinite(from)) from = Date.now();
|
|
218
|
+
const unit = this.hasSeconds ? 1e3 : 6e4;
|
|
219
|
+
const w = (0, import_neramjs.neram)(from, { zone: this.tz });
|
|
220
|
+
const [y, M, D, h, m, s, ms] = w.toArray();
|
|
221
|
+
let cur = (0, import_internal.utcFromParts)(y, M, D, h, m, this.hasSeconds ? s : 0);
|
|
222
|
+
if (ms > 0 || !this.hasSeconds && (s > 0 || ms > 0)) cur += unit;
|
|
223
|
+
let last = -Infinity;
|
|
224
|
+
for (; ; ) {
|
|
225
|
+
const next = this.#nextWall(cur);
|
|
226
|
+
if (next === null) return;
|
|
227
|
+
const inst = (0, import_internal.wallToEpoch)((0, import_internal.wallOfMs)(next), this.tz);
|
|
228
|
+
cur = next + unit;
|
|
229
|
+
if (inst < from || inst <= last) continue;
|
|
230
|
+
if (this.#endMs !== void 0 && inst > this.#endMs) return;
|
|
231
|
+
last = inst;
|
|
232
|
+
yield inst;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
toString() {
|
|
236
|
+
return this.expression;
|
|
237
|
+
}
|
|
238
|
+
toJSON() {
|
|
239
|
+
return { expression: this.expression, tz: this.tz };
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
function cron(expression, opts = {}) {
|
|
243
|
+
return new Cron(expression, opts);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// src/index.ts
|
|
247
|
+
var import_internal3 = require("neramjs/internal");
|
|
248
|
+
if (import_internal2.INTERNAL_VERSION !== 1) {
|
|
249
|
+
throw new Error(`@neramjs/cron needs a neramjs version with internals v1, but the installed neramjs has v${import_internal2.INTERNAL_VERSION}. Install matching versions of neramjs and @neramjs/cron.`);
|
|
250
|
+
}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type * as C from './index.js' with { 'resolution-mode': 'import' }
|
|
2
|
+
|
|
3
|
+
export declare const cron: typeof C.cron
|
|
4
|
+
export declare const Cron: typeof C.Cron
|
|
5
|
+
export declare const Schedule: typeof C.Schedule
|
|
6
|
+
export type Cron = C.Cron
|
|
7
|
+
export type Schedule = C.Schedule
|
|
8
|
+
export type CronOptions = C.CronOptions
|
|
9
|
+
export type As = C.As
|
|
10
|
+
export type Formatter<T = unknown> = C.Formatter<T>
|
|
11
|
+
export type Instance<T> = C.Instance<T>
|
|
12
|
+
export type OccurrenceRecord = C.OccurrenceRecord
|
|
13
|
+
export type Out<A> = C.Out<A>
|
|
14
|
+
export type OutputFormat = C.OutputFormat
|
|
15
|
+
export type OutputMap = C.OutputMap
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @neramjs/cron: cron schedules in any time zone, with the right runs across daylight saving.
|
|
3
|
+
*
|
|
4
|
+
* ```js
|
|
5
|
+
* import { cron } from '@neramjs/cron'
|
|
6
|
+
*
|
|
7
|
+
* cron('0 9 * * MON-FRI', { tz: 'Asia/Kolkata' }).after('2026-12-04 10:00', { as: 'iso' })
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
import { INTERNAL_VERSION } from 'neramjs/internal';
|
|
11
|
+
// The neramjs internals this package builds on change shape only with INTERNAL_VERSION. Fail loudly on a mismatch
|
|
12
|
+
// rather than give wrong times.
|
|
13
|
+
if (INTERNAL_VERSION !== 1) {
|
|
14
|
+
throw new Error(`@neramjs/cron needs a neramjs version with internals v1, but the installed neramjs has v${INTERNAL_VERSION}. Install matching versions of neramjs and @neramjs/cron.`);
|
|
15
|
+
}
|
|
16
|
+
export { Cron, cron } from './cron.js';
|
|
17
|
+
export { Schedule } from 'neramjs/internal';
|
package/package.json
CHANGED
|
@@ -1,6 +1,77 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neramjs/cron",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.3.1",
|
|
4
|
+
"description": "Cron schedules in any time zone, built on neramjs: the next runs, runs between two dates, and the right times across daylight saving.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cron",
|
|
7
|
+
"crontab",
|
|
8
|
+
"schedule",
|
|
9
|
+
"scheduler",
|
|
10
|
+
"jobs",
|
|
11
|
+
"timezone",
|
|
12
|
+
"dst",
|
|
13
|
+
"neramjs"
|
|
14
|
+
],
|
|
15
|
+
"license": "MIT",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/varksh05/neramjs.git",
|
|
19
|
+
"directory": "packages/cron"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://neramjs-website.vercel.app/docs/cron/",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/varksh05/neramjs/issues"
|
|
24
|
+
},
|
|
25
|
+
"funding": {
|
|
26
|
+
"type": "github",
|
|
27
|
+
"url": "https://github.com/sponsors/varksh05"
|
|
28
|
+
},
|
|
29
|
+
"type": "module",
|
|
30
|
+
"main": "./dist/index.cjs",
|
|
31
|
+
"module": "./dist/index.js",
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"unpkg": "./dist/cron.global.js",
|
|
34
|
+
"jsdelivr": "./dist/cron.global.js",
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"import": {
|
|
38
|
+
"types": "./dist/index.d.ts",
|
|
39
|
+
"default": "./dist/index.js"
|
|
40
|
+
},
|
|
41
|
+
"require": {
|
|
42
|
+
"types": "./dist/index.d.cts",
|
|
43
|
+
"default": "./dist/index.cjs"
|
|
44
|
+
}
|
|
45
|
+
},
|
|
46
|
+
"./global": "./dist/cron.global.js",
|
|
47
|
+
"./package.json": "./package.json"
|
|
48
|
+
},
|
|
49
|
+
"publishConfig": {
|
|
50
|
+
"access": "public"
|
|
51
|
+
},
|
|
52
|
+
"files": [
|
|
53
|
+
"dist",
|
|
54
|
+
"README.md",
|
|
55
|
+
"LICENSE",
|
|
56
|
+
"CHANGELOG.md"
|
|
57
|
+
],
|
|
58
|
+
"sideEffects": false,
|
|
59
|
+
"engines": {
|
|
60
|
+
"node": ">=20.19"
|
|
61
|
+
},
|
|
62
|
+
"scripts": {
|
|
63
|
+
"build": "node scripts/build.mjs",
|
|
64
|
+
"test": "node scripts/test.mjs",
|
|
65
|
+
"test:dist": "npm run build && node scripts/test.mjs --dist",
|
|
66
|
+
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p test/types/tsconfig.json",
|
|
67
|
+
"test:package": "npm run build && node scripts/check-package.mjs",
|
|
68
|
+
"bench": "node scripts/bench.mjs",
|
|
69
|
+
"prepublishOnly": "npm run typecheck && npm run test:dist && node scripts/check-package.mjs"
|
|
70
|
+
},
|
|
71
|
+
"peerDependencies": {
|
|
72
|
+
"neramjs": "^0.3.0"
|
|
73
|
+
},
|
|
74
|
+
"devDependencies": {
|
|
75
|
+
"neramjs": "file:../.."
|
|
76
|
+
}
|
|
77
|
+
}
|