neramjs 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,275 @@
1
+ import { daysInMonth } from '../calendar.js';
2
+ import { neram } from '../neram.js';
3
+ import { normalizeZone, utcFromParts, wallOfMs, wallToEpoch } from '../zone.js';
4
+ import { Schedule } from './schedule.js';
5
+ const MACROS = {
6
+ '@yearly': '0 0 1 1 *',
7
+ '@annually': '0 0 1 1 *',
8
+ '@monthly': '0 0 1 * *',
9
+ '@weekly': '0 0 * * 0',
10
+ '@daily': '0 0 * * *',
11
+ '@midnight': '0 0 * * *',
12
+ '@hourly': '0 * * * *',
13
+ };
14
+ const MONTHS = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
15
+ const DAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];
16
+ function parseField(src, name, min, max, names) {
17
+ const values = new Set();
18
+ // Like Vixie cron, a field starting with * (including */2) counts as unrestricted.
19
+ const any = src.startsWith('*') || src === '?';
20
+ const toNum = (s) => {
21
+ const up = s.toUpperCase();
22
+ const i = names ? names.indexOf(up) : -1;
23
+ const n = i >= 0 ? i + (names === MONTHS ? 1 : 0) : Number(s);
24
+ if (!/^\d+$/.test(s) && i < 0)
25
+ throw new RangeError(`neram: invalid cron ${name} "${s}"`);
26
+ return n;
27
+ };
28
+ for (const part of src.split(',')) {
29
+ if (!part)
30
+ throw new RangeError(`neram: empty item in cron ${name}`);
31
+ const [range, stepStr] = part.split('/');
32
+ const step = stepStr === undefined ? 1 : Number(stepStr);
33
+ if (!Number.isInteger(step) || step < 1)
34
+ throw new RangeError(`neram: invalid cron step "${part}"`);
35
+ let lo, hi;
36
+ if (range === '*' || range === '?') {
37
+ lo = min;
38
+ hi = max;
39
+ }
40
+ else if (range.includes('-')) {
41
+ const [a, b] = range.split('-');
42
+ lo = toNum(a);
43
+ hi = toNum(b);
44
+ }
45
+ else {
46
+ lo = toNum(range);
47
+ hi = stepStr === undefined ? lo : max;
48
+ }
49
+ const span = (v) => {
50
+ if (v < min || v > max)
51
+ throw new RangeError(`neram: cron ${name} value ${v} is out of range ${min}-${max}`);
52
+ };
53
+ span(lo);
54
+ span(hi);
55
+ if (lo <= hi) {
56
+ for (let v = lo; v <= hi; v += step)
57
+ values.add(v);
58
+ }
59
+ else {
60
+ // wrap-around range such as FRI-MON or 22-2
61
+ const size = max - min + 1;
62
+ const len = (hi - lo + size) % size;
63
+ for (let i = 0; i <= len; i += step)
64
+ values.add(min + ((lo - min + i) % size));
65
+ }
66
+ }
67
+ return { values, any };
68
+ }
69
+ /**
70
+ * A cron schedule. 5 fields (minute hour day-of-month month day-of-week) or 6 with seconds first.
71
+ * Supports * , - / names (JAN, MON), 7 = Sunday, @daily-style macros, and Quartz extras:
72
+ * L (last day), L-2, 15W (nearest weekday), LW, 5L (last Friday), 5#3 (third Friday).
73
+ * When both day-of-month and day-of-week are set, either may match (standard cron).
74
+ *
75
+ * Times are wall-clock times in `tz`: a time skipped by DST runs at the shifted time
76
+ * (02:30 → 03:30), and a time repeated by DST runs once.
77
+ */
78
+ export class Cron extends Schedule {
79
+ tz;
80
+ allDay = false;
81
+ expression;
82
+ hasSeconds;
83
+ #sec;
84
+ #min;
85
+ #hour;
86
+ #dom;
87
+ #month;
88
+ #dow;
89
+ #domX = { last: [], nearestWeekday: [], lastWeekday: false };
90
+ #dowX = { nth: [], last: [] };
91
+ #startMs;
92
+ #endMs;
93
+ constructor(expression, opts = {}) {
94
+ super();
95
+ this.expression = expression.trim();
96
+ this.tz = normalizeZone(opts.tz ?? neram().timezone());
97
+ const expanded = MACROS[this.expression.toLowerCase()] ?? this.expression;
98
+ const parts = expanded.split(/\s+/);
99
+ if (parts.length !== 5 && parts.length !== 6) {
100
+ throw new RangeError(`neram: cron needs 5 or 6 fields, got ${parts.length} in "${expression}"`);
101
+ }
102
+ this.hasSeconds = parts.length === 6;
103
+ const [sec, min, hour, dom, month, dow] = this.hasSeconds ? parts : ['0', ...parts];
104
+ this.#sec = parseField(sec, 'second', 0, 59);
105
+ this.#min = parseField(min, 'minute', 0, 59);
106
+ this.#hour = parseField(hour, 'hour', 0, 23);
107
+ this.#month = parseField(month, 'month', 1, 12, MONTHS);
108
+ // Day of month: pull out L / L-n / nW / LW before the generic parser.
109
+ const domPlain = [];
110
+ for (const item of dom.split(',')) {
111
+ const up = item.toUpperCase();
112
+ let m;
113
+ if (up === 'L')
114
+ this.#domX.last.push(0);
115
+ else if ((m = /^L-(\d+)$/.exec(up))) {
116
+ if (Number(m[1]) > 30)
117
+ throw new RangeError(`neram: invalid cron day of month "${item}" (L-n needs n from 0 to 30)`);
118
+ this.#domX.last.push(Number(m[1]));
119
+ }
120
+ else if (up === 'LW')
121
+ this.#domX.lastWeekday = true;
122
+ else if ((m = /^(\d+)W$/.exec(up))) {
123
+ const n = Number(m[1]);
124
+ if (n < 1 || n > 31)
125
+ throw new RangeError(`neram: invalid cron day of month "${item}" (nW needs n from 1 to 31)`);
126
+ this.#domX.nearestWeekday.push(n);
127
+ }
128
+ else
129
+ domPlain.push(item);
130
+ }
131
+ this.#dom = domPlain.length ? parseField(domPlain.join(','), 'day of month', 1, 31) : { values: new Set(), any: false };
132
+ if (domPlain.length !== dom.split(',').length)
133
+ this.#dom.any = false;
134
+ // Day of week: 5#3, 5L, and 7 as Sunday.
135
+ const dowPlain = [];
136
+ for (const item of dow.split(',')) {
137
+ const up = item.toUpperCase();
138
+ const dayNum = (s) => {
139
+ const i = DAYS.indexOf(s);
140
+ const n = i >= 0 ? i : Number(s);
141
+ if (!Number.isInteger(n) || n < 0 || n > 7)
142
+ throw new RangeError(`neram: invalid cron weekday "${s}"`);
143
+ return n % 7;
144
+ };
145
+ let m;
146
+ if ((m = /^(\w+)#([1-5])$/.exec(up)))
147
+ this.#dowX.nth.push([dayNum(m[1]), Number(m[2])]);
148
+ else if ((m = /^(\w+)L$/.exec(up)))
149
+ this.#dowX.last.push(dayNum(m[1]));
150
+ else
151
+ dowPlain.push(item);
152
+ }
153
+ this.#dow = dowPlain.length ? parseField(dowPlain.join(','), 'day of week', 0, 7, DAYS) : { values: new Set(), any: false };
154
+ if (dowPlain.length !== dow.split(',').length)
155
+ this.#dow.any = false;
156
+ if (this.#dow.values.delete(7))
157
+ this.#dow.values.add(0);
158
+ this.#startMs = opts.start === undefined ? undefined : this.coerce(opts.start);
159
+ this.#endMs = opts.end === undefined ? undefined : this.coerce(opts.end);
160
+ }
161
+ isInfinite() {
162
+ return this.#endMs === undefined;
163
+ }
164
+ startMs() {
165
+ return this.#startMs ?? Date.now();
166
+ }
167
+ #dayMatches(y, M, D) {
168
+ const dow = (((Math.floor(utcFromParts(y, M, D) / 86400000) % 7) + 11) % 7);
169
+ const dim = daysInMonth(y, M);
170
+ const domOk = () => {
171
+ if (this.#dom.values.has(D))
172
+ return true;
173
+ if (this.#domX.last.some((off) => D === dim - off))
174
+ return true;
175
+ const weekdayNear = (target) => {
176
+ let t = Math.min(target, dim);
177
+ const wd = new Date(utcFromParts(y, M, t)).getUTCDay();
178
+ if (wd === 6)
179
+ t = t === 1 ? 3 : t - 1;
180
+ else if (wd === 0)
181
+ t = t === dim ? t - 2 : t + 1;
182
+ return t;
183
+ };
184
+ if (this.#domX.nearestWeekday.some((n) => D === weekdayNear(n)))
185
+ return true;
186
+ if (this.#domX.lastWeekday) {
187
+ let t = dim;
188
+ while ([0, 6].includes(new Date(utcFromParts(y, M, t)).getUTCDay()))
189
+ t--;
190
+ if (D === t)
191
+ return true;
192
+ }
193
+ return false;
194
+ };
195
+ const dowOk = () => this.#dow.values.has(dow) ||
196
+ this.#dowX.nth.some(([w, n]) => w === dow && Math.floor((D - 1) / 7) + 1 === n) ||
197
+ this.#dowX.last.some((w) => w === dow && D + 7 > dim);
198
+ // Standard cron: if either field is unrestricted both must match, otherwise either may.
199
+ if (this.#dom.any || this.#dow.any)
200
+ return domOk() && dowOk();
201
+ return domOk() || dowOk();
202
+ }
203
+ /** Next matching wall time (UTC-ms of the wall clock) at or after `cur`, or null. */
204
+ #nextWall(cur) {
205
+ const limitYear = new Date(cur).getUTCFullYear() + 400;
206
+ for (;;) {
207
+ const { y, M, D, h, m, s } = wallOfMs(cur);
208
+ if (y > limitYear || y > 9999)
209
+ return null;
210
+ if (!this.#month.values.has(M + 1)) {
211
+ cur = utcFromParts(y, M + 1, 1);
212
+ continue;
213
+ }
214
+ if (!this.#dayMatches(y, M, D)) {
215
+ cur = utcFromParts(y, M, D + 1);
216
+ continue;
217
+ }
218
+ if (!this.#hour.values.has(h)) {
219
+ cur = utcFromParts(y, M, D, h + 1);
220
+ continue;
221
+ }
222
+ if (!this.#min.values.has(m)) {
223
+ cur = utcFromParts(y, M, D, h, m + 1);
224
+ continue;
225
+ }
226
+ if (!this.#sec.values.has(s)) {
227
+ cur = utcFromParts(y, M, D, h, m, s + 1);
228
+ continue;
229
+ }
230
+ return cur;
231
+ }
232
+ }
233
+ *iterate(fromMs) {
234
+ let from = fromMs;
235
+ if (this.#startMs !== undefined)
236
+ from = Math.max(from, this.#startMs);
237
+ if (!Number.isFinite(from))
238
+ from = Date.now();
239
+ const unit = this.hasSeconds ? 1000 : 60000;
240
+ const w = neram(from, { zone: this.tz });
241
+ const [y, M, D, h, m, s, ms] = w.toArray();
242
+ // Start at the first whole unit at or after `from`.
243
+ let cur = utcFromParts(y, M, D, h, m, this.hasSeconds ? s : 0);
244
+ if (ms > 0 || (!this.hasSeconds && (s > 0 || ms > 0)))
245
+ cur += unit;
246
+ let last = -Infinity;
247
+ for (;;) {
248
+ const next = this.#nextWall(cur);
249
+ if (next === null)
250
+ return;
251
+ const inst = wallToEpoch(wallOfMs(next), this.tz);
252
+ cur = next + unit;
253
+ if (inst < from || inst <= last)
254
+ continue;
255
+ if (this.#endMs !== undefined && inst > this.#endMs)
256
+ return;
257
+ last = inst;
258
+ yield inst;
259
+ }
260
+ }
261
+ toString() {
262
+ return this.expression;
263
+ }
264
+ toJSON() {
265
+ return { expression: this.expression, tz: this.tz };
266
+ }
267
+ }
268
+ /**
269
+ * Create a cron schedule.
270
+ * cron('0 9 * * MON-FRI', { tz: 'Asia/Kolkata' }).take(5, { as: 'iso' })
271
+ * cron('0 0 L * *', { tz: 'Europe/London' }).after()
272
+ */
273
+ export function cron(expression, opts = {}) {
274
+ return new Cron(expression, opts);
275
+ }
@@ -0,0 +1,2 @@
1
+ 'use strict'
2
+ module.exports = require('../cjs/neram.cjs').recur
@@ -0,0 +1,24 @@
1
+ import type * as R from './index.js' with { 'resolution-mode': 'import' }
2
+
3
+ export declare const rrule: typeof R.rrule
4
+ export declare const parseRRule: typeof R.parseRRule
5
+ export declare const cron: typeof R.cron
6
+ export declare const RRule: typeof R.RRule
7
+ export declare const Cron: typeof R.Cron
8
+ export declare const Schedule: typeof R.Schedule
9
+ export type RRule = R.RRule
10
+ export type Cron = R.Cron
11
+ export type Schedule = R.Schedule
12
+ export type ByDay = R.ByDay
13
+ export type Frequency = R.Frequency
14
+ export type RRuleJSON = R.RRuleJSON
15
+ export type RRuleOptions = R.RRuleOptions
16
+ export type Weekday = R.Weekday
17
+ export type CronOptions = R.CronOptions
18
+ export type As = R.As
19
+ export type Formatter<T = unknown> = R.Formatter<T>
20
+ export type Instance<T> = R.Instance<T>
21
+ export type OccurrenceRecord = R.OccurrenceRecord
22
+ export type Out<A> = R.Out<A>
23
+ export type OutputFormat = R.OutputFormat
24
+ export type OutputMap = R.OutputMap
@@ -0,0 +1,6 @@
1
+ export { RRule, rrule, parseRRule } from './rrule.ts';
2
+ export type { ByDay, Frequency, RRuleJSON, RRuleOptions, Weekday } from './rrule.ts';
3
+ export { Cron, cron } from './cron.ts';
4
+ export type { CronOptions } from './cron.ts';
5
+ export { Schedule } from './schedule.ts';
6
+ export type { As, Formatter, Instance, OccurrenceRecord, Out, OutputFormat, OutputMap } from './schedule.ts';
@@ -0,0 +1,3 @@
1
+ export { RRule, rrule, parseRRule } from './rrule.js';
2
+ export { Cron, cron } from './cron.js';
3
+ export { Schedule } from './schedule.js';
@@ -0,0 +1,108 @@
1
+ import { Neram, type NeramInput } from '../neram.ts';
2
+ import { Schedule } from './schedule.ts';
3
+ export type Frequency = 'yearly' | 'monthly' | 'weekly' | 'daily' | 'hourly' | 'minutely' | 'secondly';
4
+ export type Weekday = 'MO' | 'TU' | 'WE' | 'TH' | 'FR' | 'SA' | 'SU';
5
+ /** "MO", "1MO" (first Monday), "-1FR" (last Friday), or { day: 'FR', n: -1 }. */
6
+ export type ByDay = Weekday | `${'' | '+' | '-'}${number}${Weekday}` | {
7
+ day: Weekday;
8
+ n?: number;
9
+ };
10
+ type OneOrMany<T> = T | T[];
11
+ export interface RRuleOptions {
12
+ freq: Frequency | Uppercase<Frequency>;
13
+ /** First occurrence. A string without an offset is a wall time in `tz`. */
14
+ dtstart: NeramInput;
15
+ /**
16
+ * Zone the rule repeats in, so "9:00 every Monday" stays 9:00 across DST.
17
+ * Default: the dtstart's zone if it is a Neram, otherwise neram's default zone.
18
+ */
19
+ tz?: string;
20
+ /** Date-only events: occurrences are calendar days. */
21
+ allDay?: boolean;
22
+ interval?: number;
23
+ count?: number;
24
+ /** Last allowed occurrence (inclusive). A date-only string means the end of that day. */
25
+ until?: NeramInput;
26
+ /** First day of the week for WEEKLY rules and BYWEEKNO. Default MO (RFC 5545). */
27
+ wkst?: Weekday;
28
+ /** 1-12, as in RFC 5545 (not 0-11) */
29
+ byMonth?: OneOrMany<number>;
30
+ byWeekNo?: OneOrMany<number>;
31
+ byYearDay?: OneOrMany<number>;
32
+ byMonthDay?: OneOrMany<number>;
33
+ byDay?: OneOrMany<ByDay>;
34
+ byHour?: OneOrMany<number>;
35
+ byMinute?: OneOrMany<number>;
36
+ bySecond?: OneOrMany<number>;
37
+ bySetPos?: OneOrMany<number>;
38
+ /** Extra occurrences (RDATE). */
39
+ rdate?: NeramInput[];
40
+ /** Cancelled occurrences (EXDATE). All-day rules match by date; timed rules by exact instant. */
41
+ exdate?: NeramInput[];
42
+ }
43
+ /** The rule as plain JSON: dates are RFC 9557 strings, ready to store. */
44
+ export interface RRuleJSON {
45
+ freq: Frequency;
46
+ dtstart: string;
47
+ tz: string;
48
+ allDay?: boolean;
49
+ interval?: number;
50
+ count?: number;
51
+ until?: string;
52
+ wkst?: Weekday;
53
+ byMonth?: number[];
54
+ byWeekNo?: number[];
55
+ byYearDay?: number[];
56
+ byMonthDay?: number[];
57
+ byDay?: string[];
58
+ byHour?: number[];
59
+ byMinute?: number[];
60
+ bySecond?: number[];
61
+ bySetPos?: number[];
62
+ rdate?: string[];
63
+ exdate?: string[];
64
+ }
65
+ export declare class RRule extends Schedule {
66
+ #private;
67
+ readonly tz: string;
68
+ readonly allDay: boolean;
69
+ constructor(opts: RRuleOptions);
70
+ isInfinite(): boolean;
71
+ protected startMs(): number;
72
+ get freq(): Frequency;
73
+ /** The first occurrence's start, in the rule's zone. */
74
+ get dtstart(): Neram;
75
+ /** RRULE ∪ RDATE − EXDATE, ascending. */
76
+ protected iterate(fromMs: number): Generator<number>;
77
+ /** The RRULE line alone: "FREQ=WEEKLY;BYDAY=MO,WE;COUNT=10" */
78
+ rruleString(): string;
79
+ /**
80
+ * RFC 5545 text — store this in your database and load it back with rrule(text).
81
+ * DTSTART;TZID=Asia/Kolkata:20261207T090000
82
+ * RRULE:FREQ=WEEKLY;BYDAY=MO,WE
83
+ * EXDATE;TZID=Asia/Kolkata:20261209T090000
84
+ */
85
+ toString(): string;
86
+ /** Plain-object form with zoned ISO strings; rrule(json) restores it. */
87
+ toJSON(): RRuleJSON;
88
+ /** A copy with some options changed: rule.with({ exdate: [...] }) */
89
+ with(changes: Partial<RRuleOptions>): RRule;
90
+ /**
91
+ * Plain-English description: "every 2 weeks on Monday and Wednesday at 9:00 AM, 10 times".
92
+ * Weekday, month and time names follow `locale`; the sentence itself is English.
93
+ */
94
+ toText(locale?: string): string;
95
+ }
96
+ /**
97
+ * Parse RFC 5545 text into options. Accepts a full block (DTSTART / RRULE / RDATE / EXDATE lines)
98
+ * or a bare "FREQ=…" / "RRULE:FREQ=…" line, in which case pass dtstart in `defaults`.
99
+ */
100
+ export declare function parseRRule(text: string, defaults?: Partial<RRuleOptions>): RRuleOptions;
101
+ /**
102
+ * Create a recurrence rule from options, RFC 5545 text, or a stored toJSON() object.
103
+ * rrule({ freq: 'weekly', byDay: ['MO', 'WE'], dtstart: '2026-12-07 09:00', tz: 'Asia/Kolkata' })
104
+ * rrule('DTSTART;TZID=Asia/Kolkata:20261207T090000\nRRULE:FREQ=WEEKLY;BYDAY=MO,WE')
105
+ * rrule('FREQ=DAILY;COUNT=5', { dtstart: '2026-12-07 09:00', tz: 'UTC' })
106
+ */
107
+ export declare function rrule(input: string | RRuleOptions | RRuleJSON, defaults?: Partial<RRuleOptions>): RRule;
108
+ export {};