rrule-temporal 0.1.3 → 0.1.4

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.cjs ADDED
@@ -0,0 +1,577 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ RRuleTemporal: () => RRuleTemporal
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+ var import_polyfill = require("@js-temporal/polyfill");
27
+ function parseRRuleString(input, fallbackDtstart) {
28
+ let dtstart;
29
+ let tzid = "";
30
+ let rruleLine;
31
+ if (/^DTSTART/m.test(input)) {
32
+ const [dtLine, rrLine] = input.split(/\r?\n/);
33
+ const m = dtLine?.match(/DTSTART(?:;TZID=([^:]+))?:(\d{8}T\d{6})/);
34
+ if (!m) throw new Error("Invalid DTSTART in ICS snippet");
35
+ tzid = m[1] || tzid;
36
+ const isoDate = `${m[2].slice(0, 4)}-${m[2].slice(4, 6)}-${m[2].slice(6, 8)}T${m[2].slice(9)}`;
37
+ dtstart = import_polyfill.Temporal.PlainDateTime.from(isoDate).toZonedDateTime(tzid);
38
+ rruleLine = rrLine;
39
+ } else {
40
+ if (!fallbackDtstart)
41
+ throw new Error("dtstart required when parsing RRULE alone");
42
+ dtstart = fallbackDtstart;
43
+ tzid = fallbackDtstart.timeZoneId;
44
+ rruleLine = input.replace(/^RRULE:/, "RRULE:");
45
+ }
46
+ const parts = rruleLine.replace(/^RRULE:/, "").split(";");
47
+ const opts = { dtstart, tzid };
48
+ for (const part of parts) {
49
+ const [key, val] = part.split("=");
50
+ switch (key) {
51
+ case "FREQ":
52
+ opts.freq = val;
53
+ break;
54
+ case "INTERVAL":
55
+ opts.interval = parseInt(val, 10);
56
+ break;
57
+ case "COUNT":
58
+ opts.count = parseInt(val, 10);
59
+ break;
60
+ case "UNTIL": {
61
+ if (/Z$/.test(val)) {
62
+ const iso = `${val.slice(0, 4)}-${val.slice(4, 6)}-${val.slice(6, 8)}T${val.slice(9, 15)}Z`;
63
+ opts.until = import_polyfill.Temporal.Instant.from(iso).toZonedDateTimeISO(
64
+ tzid || "UTC"
65
+ );
66
+ } else {
67
+ const iso = `${val.slice(0, 4)}-${val.slice(4, 6)}-${val.slice(6, 8)}T${val.slice(9, 15)}`;
68
+ opts.until = import_polyfill.Temporal.PlainDateTime.from(iso).toZonedDateTime(
69
+ tzid || "UTC"
70
+ );
71
+ }
72
+ break;
73
+ }
74
+ case "BYHOUR":
75
+ opts.byHour = val.split(",").map((n) => parseInt(n, 10));
76
+ break;
77
+ case "BYMINUTE":
78
+ opts.byMinute = val.split(",").map((n) => parseInt(n, 10));
79
+ break;
80
+ case "BYDAY":
81
+ opts.byDay = val.split(",");
82
+ break;
83
+ case "BYMONTH":
84
+ opts.byMonth = val.split(",").map((n) => parseInt(n, 10));
85
+ break;
86
+ }
87
+ }
88
+ return opts;
89
+ }
90
+ var RRuleTemporal = class {
91
+ tzid;
92
+ originalDtstart;
93
+ opts;
94
+ constructor(params) {
95
+ let manual;
96
+ if ("rruleString" in params) {
97
+ manual = parseRRuleString(params.rruleString);
98
+ this.tzid = manual.tzid || "UTC";
99
+ this.originalDtstart = manual.dtstart;
100
+ } else {
101
+ manual = { ...params };
102
+ if (typeof manual.dtstart === "string") {
103
+ throw new Error("Manual dtstart must be a ZonedDateTime");
104
+ }
105
+ manual.tzid = manual.tzid || manual.dtstart.timeZoneId;
106
+ this.tzid = manual.tzid;
107
+ this.originalDtstart = manual.dtstart;
108
+ }
109
+ if (!manual.freq) throw new Error("RRULE must include FREQ");
110
+ manual.interval = manual.interval ?? 1;
111
+ this.opts = manual;
112
+ }
113
+ rawAdvance(zdt) {
114
+ const { freq, interval } = this.opts;
115
+ switch (freq) {
116
+ case "DAILY":
117
+ return zdt.add({ days: interval });
118
+ case "WEEKLY":
119
+ return zdt.add({ weeks: interval });
120
+ case "MONTHLY":
121
+ return zdt.add({ months: interval });
122
+ case "YEARLY":
123
+ return zdt.add({ years: interval });
124
+ case "HOURLY":
125
+ return zdt.add({ hours: interval });
126
+ case "MINUTELY":
127
+ return zdt.add({ minutes: interval });
128
+ case "SECONDLY":
129
+ return zdt.add({ seconds: interval });
130
+ default:
131
+ throw new Error(`Unsupported FREQ: ${freq}`);
132
+ }
133
+ }
134
+ applyTimeOverride(zdt) {
135
+ const { byHour, byMinute } = this.opts;
136
+ let dt = zdt;
137
+ if (byHour) dt = dt.with({ hour: byHour[0] });
138
+ if (byMinute) dt = dt.with({ minute: byMinute[0] });
139
+ return dt;
140
+ }
141
+ computeFirst() {
142
+ let zdt = this.originalDtstart;
143
+ if (this.opts.freq === "WEEKLY" && this.opts.byDay?.length) {
144
+ const dayMap = {
145
+ MO: 1,
146
+ TU: 2,
147
+ WE: 3,
148
+ TH: 4,
149
+ FR: 5,
150
+ SA: 6,
151
+ SU: 7
152
+ };
153
+ const targetDow = dayMap[this.opts.byDay[0]];
154
+ const delta = (targetDow - zdt.dayOfWeek + 7) % 7;
155
+ zdt = zdt.add({ days: delta });
156
+ }
157
+ const { byHour, byMinute } = this.opts;
158
+ if (byHour || byMinute) {
159
+ zdt = this.applyTimeOverride(zdt);
160
+ if (import_polyfill.Temporal.Instant.compare(
161
+ zdt.toInstant(),
162
+ this.originalDtstart.toInstant()
163
+ ) < 0) {
164
+ zdt = this.applyTimeOverride(this.rawAdvance(this.originalDtstart));
165
+ }
166
+ }
167
+ return zdt;
168
+ }
169
+ // inside class RRuleTemporal:
170
+ generateWeeklyOccurrences(sample) {
171
+ const { byDay } = this.opts;
172
+ const dayMap = {
173
+ MO: 1,
174
+ TU: 2,
175
+ WE: 3,
176
+ TH: 4,
177
+ FR: 5,
178
+ SA: 6,
179
+ SU: 7
180
+ };
181
+ const tokens = byDay && byDay.length ? byDay : [Object.entries(dayMap).find(([, d]) => d === sample.dayOfWeek)[0]];
182
+ const occs = tokens.map((tok) => {
183
+ const targetDow = dayMap[tok];
184
+ const delta = (targetDow - sample.dayOfWeek + 7) % 7;
185
+ return this.applyTimeOverride(sample.add({ days: delta }));
186
+ });
187
+ return occs.sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
188
+ }
189
+ // --- NEW: constraint checks ---
190
+ // 2) Replace your matchesByDay with this:
191
+ matchesByDay(zdt) {
192
+ const { byDay } = this.opts;
193
+ if (!byDay) return true;
194
+ const dayMap = {
195
+ MO: 1,
196
+ TU: 2,
197
+ WE: 3,
198
+ TH: 4,
199
+ FR: 5,
200
+ SA: 6,
201
+ SU: 7
202
+ };
203
+ for (const token of byDay) {
204
+ const m = token.match(/^([+-]?\d)?(MO|TU|WE|TH|FR|SA|SU)$/);
205
+ if (!m) continue;
206
+ const ord = m[1] ? parseInt(m[1], 10) : 0;
207
+ const weekday = m[2];
208
+ if (!weekday) continue;
209
+ const wd = dayMap[weekday];
210
+ if (ord === 0) {
211
+ if (zdt.dayOfWeek === wd) return true;
212
+ continue;
213
+ }
214
+ const year = zdt.year;
215
+ const month = zdt.month;
216
+ let dt = zdt.with({ day: 1 });
217
+ const candidates = [];
218
+ while (dt.month === month) {
219
+ if (dt.dayOfWeek === wd) candidates.push(dt.day);
220
+ dt = dt.add({ days: 1 });
221
+ }
222
+ const idx = ord > 0 ? ord - 1 : candidates.length + ord;
223
+ if (candidates[idx] === zdt.day) return true;
224
+ }
225
+ return false;
226
+ }
227
+ matchesByMonth(zdt) {
228
+ const { byMonth } = this.opts;
229
+ if (!byMonth) return true;
230
+ return byMonth.includes(zdt.month);
231
+ }
232
+ matchesAll(zdt) {
233
+ return this.matchesByDay(zdt) && this.matchesByMonth(zdt);
234
+ }
235
+ /**
236
+ * Returns all occurrences of the rule.
237
+ * @param iterator - An optional callback iterator function that can be used to filter or modify the occurrences.
238
+ * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule.
239
+ */
240
+ all(iterator) {
241
+ if (!this.opts.count && !this.opts.until && !iterator) {
242
+ throw new Error("all() requires iterator when no COUNT/UNTIL");
243
+ }
244
+ const dates = [];
245
+ if (this.opts.freq === "MONTHLY" && this.opts.byDay) {
246
+ const start = this.originalDtstart;
247
+ let monthCursor = start.with({ day: 1 });
248
+ let matchCount2 = 0;
249
+ outer_month: while (true) {
250
+ const occs = this.generateMonthlyOccurrences(monthCursor);
251
+ for (const occ of occs) {
252
+ if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
253
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
254
+ break outer_month;
255
+ }
256
+ if (this.opts.count !== void 0 && matchCount2 >= this.opts.count) {
257
+ break outer_month;
258
+ }
259
+ if (iterator && !iterator(occ, matchCount2)) {
260
+ break outer_month;
261
+ }
262
+ dates.push(occ);
263
+ matchCount2++;
264
+ }
265
+ monthCursor = monthCursor.add({ months: this.opts.interval });
266
+ }
267
+ return dates;
268
+ }
269
+ if (this.opts.freq === "WEEKLY") {
270
+ const start = this.originalDtstart;
271
+ const dayMap = {
272
+ MO: 1,
273
+ TU: 2,
274
+ WE: 3,
275
+ TH: 4,
276
+ FR: 5,
277
+ SA: 6,
278
+ SU: 7
279
+ };
280
+ const tokens = this.opts.byDay ? [...this.opts.byDay] : [Object.entries(dayMap).find(([, d]) => d === start.dayOfWeek)[0]];
281
+ const dows = tokens.map((tok) => dayMap[tok]).filter((d) => d !== void 0).sort((a, b) => a - b);
282
+ const firstWeekDates = dows.map((dw) => {
283
+ const delta = (dw - start.dayOfWeek + 7) % 7;
284
+ return start.add({ days: delta });
285
+ });
286
+ let weekCursor = firstWeekDates.reduce(
287
+ (a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b) <= 0 ? a : b
288
+ );
289
+ let matchCount2 = 0;
290
+ outer_week: while (true) {
291
+ const baseDow = weekCursor.dayOfWeek;
292
+ const occs = dows.map((dw) => {
293
+ const delta = dw - baseDow;
294
+ return this.applyTimeOverride(weekCursor.add({ days: delta }));
295
+ }).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
296
+ for (const occ of occs) {
297
+ if (import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
298
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
299
+ break outer_week;
300
+ }
301
+ if (this.opts.count !== void 0 && matchCount2 >= this.opts.count) {
302
+ break outer_week;
303
+ }
304
+ if (iterator && !iterator(occ, matchCount2)) {
305
+ break outer_week;
306
+ }
307
+ dates.push(occ);
308
+ matchCount2++;
309
+ }
310
+ weekCursor = weekCursor.add({ weeks: this.opts.interval });
311
+ }
312
+ return dates;
313
+ }
314
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth) {
315
+ const start = this.originalDtstart;
316
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
317
+ let i = 0;
318
+ while (true) {
319
+ const year = start.year + i * this.opts.interval;
320
+ const month = months[i % months.length];
321
+ let occ = start.with({ year, month });
322
+ occ = this.applyTimeOverride(occ);
323
+ if (i === 0 && import_polyfill.Temporal.ZonedDateTime.compare(occ, start) < 0) {
324
+ i++;
325
+ continue;
326
+ }
327
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
328
+ break;
329
+ }
330
+ if (this.opts.count !== void 0 && i >= this.opts.count) {
331
+ break;
332
+ }
333
+ if (iterator && !iterator(occ, i)) {
334
+ break;
335
+ }
336
+ dates.push(occ);
337
+ i++;
338
+ }
339
+ return dates;
340
+ }
341
+ let current = this.computeFirst();
342
+ let matchCount = 0;
343
+ while (true) {
344
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
345
+ break;
346
+ }
347
+ if (this.matchesAll(current)) {
348
+ if (this.opts.count !== void 0 && matchCount >= this.opts.count) {
349
+ break;
350
+ }
351
+ if (iterator && !iterator(current, matchCount)) {
352
+ break;
353
+ }
354
+ dates.push(current);
355
+ matchCount++;
356
+ }
357
+ current = this.applyTimeOverride(this.rawAdvance(current));
358
+ }
359
+ return dates;
360
+ }
361
+ /**
362
+ * Returns all occurrences of the rule within a specified time window.
363
+ * @param after - The start date or Temporal.ZonedDateTime object.
364
+ * @param before - The end date or Temporal.ZonedDateTime object.
365
+ * @param inc - Optional boolean flag to include the end date in the results.
366
+ * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule within the specified time window.
367
+ */
368
+ between(after, before, inc = false) {
369
+ const startInst = after instanceof Date ? import_polyfill.Temporal.Instant.from(after.toISOString()) : after.toInstant();
370
+ const endInst = before instanceof Date ? import_polyfill.Temporal.Instant.from(before.toISOString()) : before.toInstant();
371
+ const results = [];
372
+ if (this.opts.freq === "MONTHLY" && this.opts.byDay) {
373
+ let monthCursor = this.computeFirst().with({ day: 1 });
374
+ outer: while (true) {
375
+ const occs = this.generateMonthlyOccurrences(monthCursor);
376
+ for (const occ of occs) {
377
+ const inst = occ.toInstant();
378
+ if (inc ? import_polyfill.Temporal.Instant.compare(inst, endInst) > 0 : import_polyfill.Temporal.Instant.compare(inst, endInst) >= 0) {
379
+ break outer;
380
+ }
381
+ if (import_polyfill.Temporal.Instant.compare(inst, startInst) >= 0) {
382
+ results.push(occ);
383
+ }
384
+ }
385
+ monthCursor = monthCursor.add({ months: this.opts.interval });
386
+ }
387
+ return results;
388
+ }
389
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth) {
390
+ const start = this.originalDtstart;
391
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
392
+ let i = 0;
393
+ outer: while (true) {
394
+ const year = start.year + i * this.opts.interval;
395
+ const month = months[i % months.length];
396
+ let occ = start.with({ year, month });
397
+ occ = this.applyTimeOverride(occ);
398
+ const inst = occ.toInstant();
399
+ if (inc ? import_polyfill.Temporal.Instant.compare(inst, endInst) > 0 : import_polyfill.Temporal.Instant.compare(inst, endInst) >= 0) {
400
+ break;
401
+ }
402
+ if (import_polyfill.Temporal.Instant.compare(inst, startInst) >= 0) {
403
+ results.push(occ);
404
+ }
405
+ i++;
406
+ }
407
+ return results;
408
+ }
409
+ if (this.opts.freq === "WEEKLY") {
410
+ const startInst2 = after instanceof Date ? import_polyfill.Temporal.Instant.from(after.toISOString()) : after.toInstant();
411
+ const endInst2 = before instanceof Date ? import_polyfill.Temporal.Instant.from(before.toISOString()) : before.toInstant();
412
+ let weekCursor = this.computeFirst();
413
+ const results2 = [];
414
+ outer: while (true) {
415
+ const occs = this.generateWeeklyOccurrences(weekCursor);
416
+ for (const occ of occs) {
417
+ const inst = occ.toInstant();
418
+ if (inc ? import_polyfill.Temporal.Instant.compare(inst, endInst2) > 0 : import_polyfill.Temporal.Instant.compare(inst, endInst2) >= 0) {
419
+ break outer;
420
+ }
421
+ if (import_polyfill.Temporal.Instant.compare(inst, startInst2) >= 0) {
422
+ results2.push(occ);
423
+ }
424
+ }
425
+ weekCursor = weekCursor.add({ weeks: this.opts.interval });
426
+ }
427
+ return results2;
428
+ }
429
+ let current = this.computeFirst();
430
+ while (true) {
431
+ const inst = current.toInstant();
432
+ if (inc) {
433
+ if (import_polyfill.Temporal.Instant.compare(inst, endInst) > 0) break;
434
+ } else {
435
+ if (import_polyfill.Temporal.Instant.compare(inst, endInst) >= 0) break;
436
+ }
437
+ if (import_polyfill.Temporal.Instant.compare(inst, startInst) >= 0 && this.matchesAll(current)) {
438
+ results.push(current);
439
+ }
440
+ current = this.applyTimeOverride(this.rawAdvance(current));
441
+ }
442
+ return results;
443
+ }
444
+ /**
445
+ * Returns the next occurrence of the rule after a specified date.
446
+ * @param after - The start date or Temporal.ZonedDateTime object.
447
+ * @param inc - Optional boolean flag to include occurrences on the start date.
448
+ * @returns The next occurrence of the rule after the specified date or null if no occurrences are found.
449
+ */
450
+ next(after = /* @__PURE__ */ new Date(), inc = false) {
451
+ const afterInst = after instanceof Date ? import_polyfill.Temporal.Instant.from(after.toISOString()) : after.toInstant();
452
+ let current = this.computeFirst();
453
+ let matchCount = 0;
454
+ while (true) {
455
+ const inst = current.toInstant();
456
+ if (this.matchesAll(current)) {
457
+ const ok = inc ? import_polyfill.Temporal.Instant.compare(inst, afterInst) >= 0 : import_polyfill.Temporal.Instant.compare(inst, afterInst) > 0;
458
+ if (ok) return current;
459
+ matchCount++;
460
+ if (this.opts.count !== void 0 && matchCount >= this.opts.count) {
461
+ return null;
462
+ }
463
+ }
464
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(current, this.opts.until) >= 0) {
465
+ return null;
466
+ }
467
+ current = this.applyTimeOverride(this.rawAdvance(current));
468
+ }
469
+ }
470
+ /**
471
+ * Returns the previous occurrence of the rule before a specified date.
472
+ * @param before - The end date or Temporal.ZonedDateTime object.
473
+ * @param inc - Optional boolean flag to include occurrences on the end date.
474
+ * @returns The previous occurrence of the rule before the specified date or null if no occurrences are found.
475
+ */
476
+ previous(before = /* @__PURE__ */ new Date(), inc = false) {
477
+ const beforeInst = before instanceof Date ? import_polyfill.Temporal.Instant.from(before.toISOString()) : before.toInstant();
478
+ let current = this.computeFirst();
479
+ let prev = null;
480
+ while (true) {
481
+ const inst = current.toInstant();
482
+ if (inc ? import_polyfill.Temporal.Instant.compare(inst, beforeInst) > 0 : import_polyfill.Temporal.Instant.compare(inst, beforeInst) >= 0) {
483
+ break;
484
+ }
485
+ if (this.matchesAll(current)) {
486
+ prev = current;
487
+ }
488
+ if (this.opts.until && import_polyfill.Temporal.ZonedDateTime.compare(current, this.opts.until) >= 0) {
489
+ break;
490
+ }
491
+ current = this.applyTimeOverride(this.rawAdvance(current));
492
+ }
493
+ return prev;
494
+ }
495
+ toString() {
496
+ const iso = this.originalDtstart.toString({ smallestUnit: "second" }).replace(/[-:]/g, "");
497
+ const dtLine = `DTSTART;TZID=${this.tzid}:${iso.slice(0, 15)}`;
498
+ const parts = [];
499
+ const { freq, interval, count, byHour, byMinute, byDay, byMonth } = this.opts;
500
+ parts.push(`FREQ=${freq}`);
501
+ if (interval !== 1) parts.push(`INTERVAL=${interval}`);
502
+ if (count !== void 0) parts.push(`COUNT=${count}`);
503
+ if (byHour) parts.push(`BYHOUR=${byHour.join(",")}`);
504
+ if (byMinute) parts.push(`BYMINUTE=${byMinute.join(",")}`);
505
+ if (byDay) parts.push(`BYDAY=${byDay.join(",")}`);
506
+ if (byMonth) parts.push(`BYMONTH=${byMonth.join(",")}`);
507
+ return [dtLine, `RRULE:${parts.join(";")}`].join("\n");
508
+ }
509
+ /**
510
+ * Given any date in a month, return all the ZonedDateTimes in that month
511
+ * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
512
+ */
513
+ generateMonthlyOccurrences(sample) {
514
+ const { byDay, byMonth, tzid } = this.opts;
515
+ if (byMonth && !byMonth.includes(sample.month)) {
516
+ return [];
517
+ }
518
+ if (!byDay || byDay.length === 0) {
519
+ return [sample];
520
+ }
521
+ const dayMap = {
522
+ MO: 1,
523
+ TU: 2,
524
+ WE: 3,
525
+ TH: 4,
526
+ FR: 5,
527
+ SA: 6,
528
+ SU: 7
529
+ };
530
+ const tokens = byDay.map((tok) => {
531
+ const m = tok.match(/^([+-]?\d)?(MO|TU|WE|TH|FR|SA|SU)$/);
532
+ if (!m) return null;
533
+ const ord = m[1] ? parseInt(m[1], 10) : 0;
534
+ const wd = dayMap[m[2]];
535
+ return { ord, wd };
536
+ }).filter((x) => x !== null);
537
+ const year = sample.year;
538
+ const month = sample.month;
539
+ let cursor = import_polyfill.Temporal.ZonedDateTime.from({
540
+ year,
541
+ month,
542
+ day: 1,
543
+ hour: sample.hour,
544
+ minute: sample.minute,
545
+ second: sample.second,
546
+ timeZone: tzid
547
+ });
548
+ const weekdayBuckets = {};
549
+ while (cursor.month === month) {
550
+ const dow = cursor.dayOfWeek;
551
+ weekdayBuckets[dow] = weekdayBuckets[dow] || [];
552
+ weekdayBuckets[dow].push(cursor.day);
553
+ cursor = cursor.add({ days: 1 });
554
+ }
555
+ const results = [];
556
+ for (const { ord, wd } of tokens) {
557
+ const days = weekdayBuckets[wd] || [];
558
+ if (!days.length) continue;
559
+ if (ord === 0) {
560
+ for (const d of days) {
561
+ results.push(sample.with({ day: d }));
562
+ }
563
+ } else {
564
+ const idx = ord > 0 ? ord - 1 : days.length + ord;
565
+ const dayNum = days[idx];
566
+ if (dayNum) {
567
+ results.push(sample.with({ day: dayNum }));
568
+ }
569
+ }
570
+ }
571
+ return results.map((zdt) => this.applyTimeOverride(zdt)).sort((a, b) => import_polyfill.Temporal.ZonedDateTime.compare(a, b));
572
+ }
573
+ };
574
+ // Annotate the CommonJS export names for ESM import in node:
575
+ 0 && (module.exports = {
576
+ RRuleTemporal
577
+ });
@@ -0,0 +1,72 @@
1
+ import { Temporal } from '@js-temporal/polyfill';
2
+
3
+ type Freq = "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY";
4
+ interface BaseOpts {
5
+ tzid?: string;
6
+ }
7
+ interface ManualOpts extends BaseOpts {
8
+ freq: Freq;
9
+ interval?: number;
10
+ count?: number;
11
+ until?: Temporal.ZonedDateTime;
12
+ byHour?: number[];
13
+ byMinute?: number[];
14
+ byDay?: string[];
15
+ byMonth?: number[];
16
+ dtstart: string | Temporal.ZonedDateTime;
17
+ }
18
+ interface IcsOpts extends BaseOpts {
19
+ rruleString: string;
20
+ }
21
+ type RRuleOpts = ManualOpts | IcsOpts;
22
+ declare class RRuleTemporal {
23
+ private tzid;
24
+ private originalDtstart;
25
+ private opts;
26
+ constructor(params: {
27
+ rruleString: string;
28
+ } | ManualOpts);
29
+ private rawAdvance;
30
+ private applyTimeOverride;
31
+ private computeFirst;
32
+ private generateWeeklyOccurrences;
33
+ private matchesByDay;
34
+ private matchesByMonth;
35
+ private matchesAll;
36
+ /**
37
+ * Returns all occurrences of the rule.
38
+ * @param iterator - An optional callback iterator function that can be used to filter or modify the occurrences.
39
+ * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule.
40
+ */
41
+ all(iterator?: (date: Temporal.ZonedDateTime, i: number) => boolean): Temporal.ZonedDateTime[];
42
+ /**
43
+ * Returns all occurrences of the rule within a specified time window.
44
+ * @param after - The start date or Temporal.ZonedDateTime object.
45
+ * @param before - The end date or Temporal.ZonedDateTime object.
46
+ * @param inc - Optional boolean flag to include the end date in the results.
47
+ * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule within the specified time window.
48
+ */
49
+ between(after: Date | Temporal.ZonedDateTime, before: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime[];
50
+ /**
51
+ * Returns the next occurrence of the rule after a specified date.
52
+ * @param after - The start date or Temporal.ZonedDateTime object.
53
+ * @param inc - Optional boolean flag to include occurrences on the start date.
54
+ * @returns The next occurrence of the rule after the specified date or null if no occurrences are found.
55
+ */
56
+ next(after?: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime | null;
57
+ /**
58
+ * Returns the previous occurrence of the rule before a specified date.
59
+ * @param before - The end date or Temporal.ZonedDateTime object.
60
+ * @param inc - Optional boolean flag to include occurrences on the end date.
61
+ * @returns The previous occurrence of the rule before the specified date or null if no occurrences are found.
62
+ */
63
+ previous(before?: Date | Temporal.ZonedDateTime, inc?: boolean): Temporal.ZonedDateTime | null;
64
+ toString(): string;
65
+ /**
66
+ * Given any date in a month, return all the ZonedDateTimes in that month
67
+ * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
68
+ */
69
+ private generateMonthlyOccurrences;
70
+ }
71
+
72
+ export { type RRuleOpts, RRuleTemporal };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { Temporal } from "@js-temporal/polyfill";
1
+ import { Temporal } from '@js-temporal/polyfill';
2
+
2
3
  type Freq = "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY";
3
4
  interface BaseOpts {
4
5
  tzid?: string;
@@ -17,8 +18,8 @@ interface ManualOpts extends BaseOpts {
17
18
  interface IcsOpts extends BaseOpts {
18
19
  rruleString: string;
19
20
  }
20
- export type RRuleOpts = ManualOpts | IcsOpts;
21
- export declare class RRuleTemporal {
21
+ type RRuleOpts = ManualOpts | IcsOpts;
22
+ declare class RRuleTemporal {
22
23
  private tzid;
23
24
  private originalDtstart;
24
25
  private opts;
@@ -67,4 +68,5 @@ export declare class RRuleTemporal {
67
68
  */
68
69
  private generateMonthlyOccurrences;
69
70
  }
70
- export {};
71
+
72
+ export { type RRuleOpts, RRuleTemporal };