rrule-temporal 0.1.6 → 0.2.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.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Temporal } from '@js-temporal/polyfill';
2
2
 
3
+ type DateFormatter = (year: number, month: string, day: number) => string;
3
4
  type Freq = "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY";
4
5
  interface BaseOpts {
5
6
  tzid?: string;
@@ -13,12 +14,13 @@ interface ManualOpts extends BaseOpts {
13
14
  byMinute?: number[];
14
15
  byDay?: string[];
15
16
  byMonth?: number[];
17
+ byMonthDay?: number[];
16
18
  dtstart: Temporal.ZonedDateTime;
17
19
  }
18
20
  interface IcsOpts extends BaseOpts {
19
21
  rruleString: string;
20
22
  }
21
- type RRuleOpts = ManualOpts | IcsOpts;
23
+ type RRuleOptions = ManualOpts | IcsOpts;
22
24
  declare class RRuleTemporal {
23
25
  private tzid;
24
26
  private originalDtstart;
@@ -38,6 +40,7 @@ declare class RRuleTemporal {
38
40
  private generateWeeklyOccurrences;
39
41
  private matchesByDay;
40
42
  private matchesByMonth;
43
+ private matchesByMonthDay;
41
44
  private matchesAll;
42
45
  options(): ManualOpts;
43
46
  /**
@@ -69,11 +72,21 @@ declare class RRuleTemporal {
69
72
  */
70
73
  previous(before?: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime | null;
71
74
  toString(): string;
75
+ /**
76
+ * Convert this rule to a human readable English description.
77
+ */
78
+ toText(formatter?: DateFormatter): string;
72
79
  /**
73
80
  * Given any date in a month, return all the ZonedDateTimes in that month
74
81
  * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
75
82
  */
76
83
  private generateMonthlyOccurrences;
84
+ /**
85
+ * Given any date in a year, return all ZonedDateTimes in that year matching
86
+ * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
87
+ * if BYMONTH is not specified.
88
+ */
89
+ private generateYearlyOccurrences;
77
90
  }
78
91
 
79
- export { type RRuleOpts, RRuleTemporal };
92
+ export { type DateFormatter, type RRuleOptions, RRuleTemporal };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Temporal } from '@js-temporal/polyfill';
2
2
 
3
+ type DateFormatter = (year: number, month: string, day: number) => string;
3
4
  type Freq = "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY";
4
5
  interface BaseOpts {
5
6
  tzid?: string;
@@ -13,12 +14,13 @@ interface ManualOpts extends BaseOpts {
13
14
  byMinute?: number[];
14
15
  byDay?: string[];
15
16
  byMonth?: number[];
17
+ byMonthDay?: number[];
16
18
  dtstart: Temporal.ZonedDateTime;
17
19
  }
18
20
  interface IcsOpts extends BaseOpts {
19
21
  rruleString: string;
20
22
  }
21
- type RRuleOpts = ManualOpts | IcsOpts;
23
+ type RRuleOptions = ManualOpts | IcsOpts;
22
24
  declare class RRuleTemporal {
23
25
  private tzid;
24
26
  private originalDtstart;
@@ -38,6 +40,7 @@ declare class RRuleTemporal {
38
40
  private generateWeeklyOccurrences;
39
41
  private matchesByDay;
40
42
  private matchesByMonth;
43
+ private matchesByMonthDay;
41
44
  private matchesAll;
42
45
  options(): ManualOpts;
43
46
  /**
@@ -69,11 +72,21 @@ declare class RRuleTemporal {
69
72
  */
70
73
  previous(before?: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime | null;
71
74
  toString(): string;
75
+ /**
76
+ * Convert this rule to a human readable English description.
77
+ */
78
+ toText(formatter?: DateFormatter): string;
72
79
  /**
73
80
  * Given any date in a month, return all the ZonedDateTimes in that month
74
81
  * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
75
82
  */
76
83
  private generateMonthlyOccurrences;
84
+ /**
85
+ * Given any date in a year, return all ZonedDateTimes in that year matching
86
+ * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
87
+ * if BYMONTH is not specified.
88
+ */
89
+ private generateYearlyOccurrences;
77
90
  }
78
91
 
79
- export { type RRuleOpts, RRuleTemporal };
92
+ export { type DateFormatter, type RRuleOptions, RRuleTemporal };
package/dist/index.js CHANGED
@@ -1,5 +1,59 @@
1
1
  // src/index.ts
2
2
  import { Temporal } from "@js-temporal/polyfill";
3
+ var WEEKDAY_NAMES = [
4
+ "Monday",
5
+ "Tuesday",
6
+ "Wednesday",
7
+ "Thursday",
8
+ "Friday",
9
+ "Saturday",
10
+ "Sunday"
11
+ ];
12
+ var MONTH_NAMES = [
13
+ "January",
14
+ "February",
15
+ "March",
16
+ "April",
17
+ "May",
18
+ "June",
19
+ "July",
20
+ "August",
21
+ "September",
22
+ "October",
23
+ "November",
24
+ "December"
25
+ ];
26
+ var defaultDateFormatter = (year, month, day) => `${month} ${day}, ${year}`;
27
+ function ordinal(n) {
28
+ const abs = Math.abs(n);
29
+ const suffix = abs % 10 === 1 && abs % 100 !== 11 ? "st" : abs % 10 === 2 && abs % 100 !== 12 ? "nd" : abs % 10 === 3 && abs % 100 !== 13 ? "rd" : "th";
30
+ return n < 0 ? `last` : `${abs}${suffix}`;
31
+ }
32
+ function list(arr, mapFn = (x) => `${x}`, final = "and") {
33
+ const mapped = arr.map(mapFn);
34
+ if (mapped.length === 1) return mapped[0];
35
+ return mapped.slice(0, -1).join(", ") + ` ${final} ` + mapped[mapped.length - 1];
36
+ }
37
+ function formatByDayToken(tok) {
38
+ if (typeof tok === "number") return tok.toString();
39
+ const m = tok.match(/^([+-]?\d+)?(MO|TU|WE|TH|FR|SA|SU)$/);
40
+ if (!m) return tok;
41
+ const ord = m[1] ? parseInt(m[1], 10) : 0;
42
+ const weekdayMap = {
43
+ MO: 0,
44
+ TU: 1,
45
+ WE: 2,
46
+ TH: 3,
47
+ FR: 4,
48
+ SA: 5,
49
+ SU: 6
50
+ };
51
+ const idx = weekdayMap[m[2]];
52
+ const name = WEEKDAY_NAMES[idx];
53
+ if (ord === 0) return name;
54
+ if (ord === -1) return `last ${name}`;
55
+ return `${ordinal(ord)} ${name}`;
56
+ }
3
57
  function parseRRuleString(input, fallbackDtstart) {
4
58
  let dtstart;
5
59
  let tzid = "UTC";
@@ -59,10 +113,30 @@ function parseRRuleString(input, fallbackDtstart) {
59
113
  case "BYMONTH":
60
114
  opts.byMonth = val.split(",").map((n) => parseInt(n, 10));
61
115
  break;
116
+ case "BYMONTHDAY":
117
+ opts.byMonthDay = val.split(",").map((n) => parseInt(n, 10));
118
+ break;
62
119
  }
63
120
  }
64
121
  return opts;
65
122
  }
123
+ function formatTime(hour, minute = 0) {
124
+ const hr12 = (hour + 11) % 12 + 1;
125
+ const ampm = hour < 12 ? "AM" : "PM";
126
+ if (minute) {
127
+ return `${hr12}:${String(minute).padStart(2, "0")} ${ampm}`;
128
+ }
129
+ return `${hr12} ${ampm}`;
130
+ }
131
+ function tzAbbreviation(zdt) {
132
+ const parts = new Intl.DateTimeFormat("en-US", {
133
+ timeZone: zdt.timeZoneId,
134
+ timeZoneName: "short",
135
+ hour: "numeric"
136
+ }).formatToParts(new Date(zdt.epochMilliseconds));
137
+ const tzPart = parts.find((p) => p.type === "timeZoneName");
138
+ return tzPart?.value || zdt.timeZoneId;
139
+ }
66
140
  var RRuleTemporal = class {
67
141
  tzid;
68
142
  originalDtstart;
@@ -215,7 +289,6 @@ var RRuleTemporal = class {
215
289
  if (zdt.dayOfWeek === wd) return true;
216
290
  continue;
217
291
  }
218
- const year = zdt.year;
219
292
  const month = zdt.month;
220
293
  let dt = zdt.with({ day: 1 });
221
294
  const candidates = [];
@@ -233,8 +306,16 @@ var RRuleTemporal = class {
233
306
  if (!byMonth) return true;
234
307
  return byMonth.includes(zdt.month);
235
308
  }
309
+ matchesByMonthDay(zdt) {
310
+ const { byMonthDay } = this.opts;
311
+ if (!byMonthDay) return true;
312
+ const lastDay = zdt.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
313
+ return byMonthDay.some(
314
+ (d) => d > 0 ? zdt.day === d : zdt.day === lastDay + d + 1
315
+ );
316
+ }
236
317
  matchesAll(zdt) {
237
- return this.matchesByDay(zdt) && this.matchesByMonth(zdt);
318
+ return this.matchesByDay(zdt) && this.matchesByMonth(zdt) && this.matchesByMonthDay(zdt);
238
319
  }
239
320
  options() {
240
321
  return this.opts;
@@ -249,7 +330,7 @@ var RRuleTemporal = class {
249
330
  throw new Error("all() requires iterator when no COUNT/UNTIL");
250
331
  }
251
332
  const dates = [];
252
- if (this.opts.freq === "MONTHLY" && this.opts.byDay) {
333
+ if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
253
334
  const start = this.originalDtstart;
254
335
  let monthCursor = start.with({ day: 1 });
255
336
  let matchCount2 = 0;
@@ -323,7 +404,7 @@ var RRuleTemporal = class {
323
404
  }
324
405
  return dates;
325
406
  }
326
- if (this.opts.freq === "YEARLY" && this.opts.byMonth) {
407
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay) {
327
408
  const start = this.originalDtstart;
328
409
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
329
410
  let i = 0;
@@ -350,6 +431,30 @@ var RRuleTemporal = class {
350
431
  }
351
432
  return dates;
352
433
  }
434
+ if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay)) {
435
+ const start = this.originalDtstart;
436
+ let yearCursor = start.with({ month: 1, day: 1 });
437
+ let matchCount2 = 0;
438
+ outer_year: while (true) {
439
+ const occs = this.generateYearlyOccurrences(yearCursor);
440
+ for (const occ of occs) {
441
+ if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
442
+ if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
443
+ break outer_year;
444
+ }
445
+ if (this.opts.count !== void 0 && matchCount2 >= this.opts.count) {
446
+ break outer_year;
447
+ }
448
+ if (iterator && !iterator(occ, matchCount2)) {
449
+ break outer_year;
450
+ }
451
+ dates.push(occ);
452
+ matchCount2++;
453
+ }
454
+ yearCursor = yearCursor.add({ years: this.opts.interval });
455
+ }
456
+ return dates;
457
+ }
353
458
  let current = this.computeFirst();
354
459
  let matchCount = 0;
355
460
  while (true) {
@@ -381,7 +486,7 @@ var RRuleTemporal = class {
381
486
  const startInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
382
487
  const endInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
383
488
  const results = [];
384
- if (this.opts.freq === "MONTHLY" && this.opts.byDay) {
489
+ if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay)) {
385
490
  let monthCursor = this.computeFirst().with({ day: 1 });
386
491
  outer: while (true) {
387
492
  const occs = this.generateMonthlyOccurrences(monthCursor);
@@ -398,7 +503,7 @@ var RRuleTemporal = class {
398
503
  }
399
504
  return results;
400
505
  }
401
- if (this.opts.freq === "YEARLY" && this.opts.byMonth) {
506
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay) {
402
507
  const start = this.originalDtstart;
403
508
  const months = [...this.opts.byMonth].sort((a, b) => a - b);
404
509
  let i = 0;
@@ -418,6 +523,24 @@ var RRuleTemporal = class {
418
523
  }
419
524
  return results;
420
525
  }
526
+ if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay)) {
527
+ const start = this.originalDtstart;
528
+ let yearCursor = start.with({ month: 1, day: 1 });
529
+ outer_year: while (true) {
530
+ const occs = this.generateYearlyOccurrences(yearCursor);
531
+ for (const occ of occs) {
532
+ const inst = occ.toInstant();
533
+ if (inc ? Temporal.Instant.compare(inst, endInst) > 0 : Temporal.Instant.compare(inst, endInst) >= 0) {
534
+ break outer_year;
535
+ }
536
+ if (Temporal.Instant.compare(inst, startInst) >= 0) {
537
+ results.push(occ);
538
+ }
539
+ }
540
+ yearCursor = yearCursor.add({ years: this.opts.interval });
541
+ }
542
+ return results;
543
+ }
421
544
  if (this.opts.freq === "WEEKLY") {
422
545
  const startInst2 = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
423
546
  const endInst2 = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
@@ -508,24 +631,123 @@ var RRuleTemporal = class {
508
631
  const iso = this.originalDtstart.toString({ smallestUnit: "second" }).replace(/[-:]/g, "");
509
632
  const dtLine = `DTSTART;TZID=${this.tzid}:${iso.slice(0, 15)}`;
510
633
  const parts = [];
511
- const { freq, interval, count, byHour, byMinute, byDay, byMonth } = this.opts;
634
+ const {
635
+ freq,
636
+ interval,
637
+ count,
638
+ until,
639
+ byHour,
640
+ byMinute,
641
+ byDay,
642
+ byMonth,
643
+ byMonthDay
644
+ } = this.opts;
512
645
  parts.push(`FREQ=${freq}`);
513
646
  if (interval !== 1) parts.push(`INTERVAL=${interval}`);
514
647
  if (count !== void 0) parts.push(`COUNT=${count}`);
648
+ if (until) {
649
+ const u = until.toInstant().toString().replace(/[-:]/g, "");
650
+ parts.push(`UNTIL=${u.slice(0, 15)}Z`);
651
+ }
515
652
  if (byHour) parts.push(`BYHOUR=${byHour.join(",")}`);
516
653
  if (byMinute) parts.push(`BYMINUTE=${byMinute.join(",")}`);
517
654
  if (byDay) parts.push(`BYDAY=${byDay.join(",")}`);
518
655
  if (byMonth) parts.push(`BYMONTH=${byMonth.join(",")}`);
656
+ if (byMonthDay) parts.push(`BYMONTHDAY=${byMonthDay.join(",")}`);
519
657
  return [dtLine, `RRULE:${parts.join(";")}`].join("\n");
520
658
  }
659
+ /**
660
+ * Convert this rule to a human readable English description.
661
+ */
662
+ toText(formatter = defaultDateFormatter) {
663
+ const {
664
+ freq,
665
+ interval = 1,
666
+ count,
667
+ until,
668
+ byDay,
669
+ byHour,
670
+ byMinute,
671
+ byMonth,
672
+ byMonthDay
673
+ } = this.opts;
674
+ const parts = ["every"];
675
+ const base = {
676
+ YEARLY: "year",
677
+ MONTHLY: "month",
678
+ WEEKLY: "week",
679
+ DAILY: "day",
680
+ HOURLY: "hour",
681
+ MINUTELY: "minute",
682
+ SECONDLY: "second"
683
+ }[freq];
684
+ const daysNormalized = byDay?.map((d) => d.toUpperCase());
685
+ const isWeekdays = daysNormalized && daysNormalized.length === 5 && ["MO", "TU", "WE", "TH", "FR"].every((d) => daysNormalized.includes(d));
686
+ const isEveryday = daysNormalized && daysNormalized.length === 7 && ["MO", "TU", "WE", "TH", "FR", "SA", "SU"].every(
687
+ (d) => daysNormalized.includes(d)
688
+ );
689
+ if (freq === "WEEKLY" && interval === 1 && isWeekdays) {
690
+ parts.push("weekday");
691
+ } else if (freq === "WEEKLY" && interval === 1 && isEveryday) {
692
+ parts.push("day");
693
+ } else {
694
+ if (interval !== 1) {
695
+ parts.push(interval.toString(), base + "s");
696
+ } else {
697
+ parts.push(base);
698
+ }
699
+ }
700
+ if (freq === "WEEKLY" && byDay && !isWeekdays && !isEveryday) {
701
+ parts.push("on", list(byDay, formatByDayToken));
702
+ } else if (byDay && freq !== "WEEKLY") {
703
+ parts.push("on", list(byDay, formatByDayToken));
704
+ }
705
+ if (byMonth) {
706
+ parts.push(
707
+ "in",
708
+ list(byMonth, (m) => MONTH_NAMES[m - 1])
709
+ );
710
+ }
711
+ if (byMonthDay) {
712
+ parts.push(
713
+ "on the",
714
+ list(byMonthDay, (d) => ordinal(d)),
715
+ "day of the month"
716
+ );
717
+ }
718
+ if (byHour) {
719
+ const minutes = byMinute ?? [0];
720
+ const times = byHour.flatMap((h) => minutes.map((m) => formatTime(h, m)));
721
+ parts.push("at", list(times));
722
+ parts.push(tzAbbreviation(this.originalDtstart));
723
+ }
724
+ if (until) {
725
+ parts.push(
726
+ "until",
727
+ formatter(until.year, MONTH_NAMES[until.month - 1], until.day)
728
+ );
729
+ } else if (count !== void 0) {
730
+ parts.push("for", count.toString(), count === 1 ? "time" : "times");
731
+ }
732
+ return parts.join(" ");
733
+ }
521
734
  /**
522
735
  * Given any date in a month, return all the ZonedDateTimes in that month
523
736
  * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
524
737
  */
525
738
  generateMonthlyOccurrences(sample) {
526
- const { byDay, byMonth, tzid } = this.opts;
739
+ const { byDay, byMonth, byMonthDay } = this.opts;
527
740
  if (byMonth && !byMonth.includes(sample.month)) return [];
528
- if (!byDay || byDay.length === 0) {
741
+ const lastDay = sample.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
742
+ let byMonthDayHits = [];
743
+ if (byMonthDay && byMonthDay.length > 0) {
744
+ byMonthDayHits = byMonthDay.map((d) => d > 0 ? d : lastDay + d + 1).filter((d) => d >= 1 && d <= lastDay);
745
+ }
746
+ if (!byDay && byMonthDayHits.length) {
747
+ const dates = byMonthDayHits.map((d) => sample.with({ day: d }));
748
+ return dates.flatMap((z) => this.expandByHourMinute(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
749
+ }
750
+ if (!byDay) {
529
751
  return this.expandByHourMinute(sample);
530
752
  }
531
753
  const dayMap = {
@@ -549,20 +771,38 @@ var RRuleTemporal = class {
549
771
  (buckets[dow] ||= []).push(cursor.day);
550
772
  cursor = cursor.add({ days: 1 });
551
773
  }
552
- const hits = [];
774
+ const byDayHits = [];
553
775
  for (const { ord, wd } of tokens) {
554
- const list = buckets[wd] ?? [];
555
- if (!list.length) continue;
776
+ const list2 = buckets[wd] ?? [];
777
+ if (!list2.length) continue;
556
778
  if (ord === 0) {
557
- for (const d of list) hits.push(sample.with({ day: d }));
779
+ for (const d of list2) byDayHits.push(d);
558
780
  } else {
559
- const idx = ord > 0 ? ord - 1 : list.length + ord;
560
- const dayN = list[idx];
561
- if (dayN) hits.push(sample.with({ day: dayN }));
781
+ const idx = ord > 0 ? ord - 1 : list2.length + ord;
782
+ const dayN = list2[idx];
783
+ if (dayN) byDayHits.push(dayN);
562
784
  }
563
785
  }
786
+ let finalDays = byDayHits;
787
+ if (byMonthDayHits.length) {
788
+ finalDays = finalDays.filter((d) => byMonthDayHits.includes(d));
789
+ }
790
+ const hits = finalDays.map((d) => sample.with({ day: d }));
564
791
  return hits.flatMap((z) => this.expandByHourMinute(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
565
792
  }
793
+ /**
794
+ * Given any date in a year, return all ZonedDateTimes in that year matching
795
+ * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
796
+ * if BYMONTH is not specified.
797
+ */
798
+ generateYearlyOccurrences(sample) {
799
+ const months = this.opts.byMonth ? [...this.opts.byMonth].sort((a, b) => a - b) : [this.originalDtstart.month];
800
+ const occs = months.flatMap((m) => {
801
+ const monthSample = sample.with({ month: m, day: 1 });
802
+ return this.generateMonthlyOccurrences(monthSample);
803
+ });
804
+ return occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
805
+ }
566
806
  };
567
807
  export {
568
808
  RRuleTemporal
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "rrule-temporal",
3
- "version": "0.1.6",
3
+ "version": "0.2.0",
4
4
  "description": "Recurrence rule processing using Temporal PlainDate/PlainDateTime",
5
5
  "types": "dist/index.d.ts",
6
6
  "type": "module",
7
7
  "exports": {
8
8
  ".": {
9
9
  "types": "./dist/index.d.ts",
10
- "import": "./dist/index.mjs",
10
+ "import": "./dist/index.js",
11
11
  "require": "./dist/index.cjs"
12
12
  }
13
13
  },
@@ -33,7 +33,7 @@
33
33
  "bugs": {
34
34
  "url": "https://github.com/ggaabe/rrule-temporal/issues"
35
35
  },
36
- "homepage": "https://github.com/ggaabe/rrule-temporal#readme",
36
+ "homepage": "https://github.io/ggaabe/rrule-temporal",
37
37
  "files": [
38
38
  "dist"
39
39
  ],
@@ -1 +0,0 @@
1
- export {};