rrule-temporal 1.1.3 → 1.1.5

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,1590 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
3
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
4
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
5
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
+ var __spreadValues = (a, b) => {
7
+ for (var prop in b || (b = {}))
8
+ if (__hasOwnProp.call(b, prop))
9
+ __defNormalProp(a, prop, b[prop]);
10
+ if (__getOwnPropSymbols)
11
+ for (var prop of __getOwnPropSymbols(b)) {
12
+ if (__propIsEnum.call(b, prop))
13
+ __defNormalProp(a, prop, b[prop]);
14
+ }
15
+ return a;
16
+ };
17
+
18
+ // src/index.ts
19
+ import { Temporal } from "@js-temporal/polyfill";
20
+ function unfoldLine(foldedLine) {
21
+ return foldedLine.replace(/\r?\n[ \t]/g, "");
22
+ }
23
+ function parseIcsDateTime(dateStr, tzid, valueType) {
24
+ const isDate = valueType === "DATE" || !dateStr.includes("T");
25
+ const isoDate = `${dateStr.slice(0, 4)}-${dateStr.slice(4, 6)}-${dateStr.slice(6, 8)}`;
26
+ if (isDate) {
27
+ return Temporal.PlainDate.from(isoDate).toZonedDateTime({ timeZone: tzid });
28
+ }
29
+ if (dateStr.endsWith("Z")) {
30
+ const iso = `${isoDate}T${dateStr.slice(9, 15)}Z`;
31
+ return Temporal.Instant.from(iso).toZonedDateTimeISO(tzid || "UTC");
32
+ } else {
33
+ const iso = `${isoDate}T${dateStr.slice(9)}`;
34
+ return Temporal.PlainDateTime.from(iso).toZonedDateTime(tzid);
35
+ }
36
+ }
37
+ function parseDateLines(lines, linePrefix, defaultTzid) {
38
+ const dates = [];
39
+ const regex = new RegExp(`^${linePrefix}(?:;VALUE=([^;]+))?(?:;TZID=([^:]+))?:(.+)`, "i");
40
+ for (const line of lines) {
41
+ const match = line.match(regex);
42
+ if (match) {
43
+ const [, valueType, tzid, dateValuesStr] = match;
44
+ const timezone = tzid || defaultTzid;
45
+ const dateValues = dateValuesStr.split(",");
46
+ dates.push(...dateValues.map((dateValue) => parseIcsDateTime(dateValue, timezone, valueType)));
47
+ }
48
+ }
49
+ return dates;
50
+ }
51
+ function parseNumberArray(val, sort = false) {
52
+ const arr = val.split(",").map((n) => parseInt(n, 10));
53
+ if (sort) {
54
+ return arr.sort((a, b) => a - b);
55
+ }
56
+ return arr;
57
+ }
58
+ function parseRRuleString(input, targetTimezone) {
59
+ var _a;
60
+ const unfoldedInput = unfoldLine(input).trim();
61
+ let dtstart;
62
+ let tzid = "UTC";
63
+ let rruleLine;
64
+ let exDate = [];
65
+ let rDate = [];
66
+ if (/^DTSTART/im.test(unfoldedInput)) {
67
+ const lines = unfoldedInput.split(/\s+/);
68
+ const dtLine = lines.find((line) => line.match(/^DTSTART/i));
69
+ const rrLine = lines.find((line) => line.match(/^RRULE:/i));
70
+ const exLines = lines.filter((line) => line.match(/^EXDATE/i));
71
+ const rLines = lines.filter((line) => line.match(/^RDATE/i));
72
+ const dtMatch = dtLine.match(/DTSTART(?:;VALUE=([^;]+))?(?:;TZID=([^:]+))?:(.+)/i);
73
+ if (!dtMatch) throw new Error("Invalid DTSTART in ICS snippet");
74
+ const [, valueType, dtTzid, dtValue] = dtMatch;
75
+ tzid = (_a = dtTzid != null ? dtTzid : targetTimezone) != null ? _a : tzid;
76
+ dtstart = parseIcsDateTime(dtValue, tzid, valueType);
77
+ rruleLine = rrLine;
78
+ exDate = parseDateLines(exLines, "EXDATE", tzid);
79
+ rDate = parseDateLines(rLines, "RDATE", tzid);
80
+ } else {
81
+ throw new Error("dtstart required when parsing RRULE alone");
82
+ }
83
+ const parts = rruleLine ? rruleLine.replace(/^RRULE:/i, "").split(";") : [];
84
+ const opts = {
85
+ dtstart,
86
+ tzid,
87
+ exDate: exDate.length > 0 ? exDate : void 0,
88
+ rDate: rDate.length > 0 ? rDate : void 0
89
+ };
90
+ for (const part of parts) {
91
+ const [key, val] = part.split("=");
92
+ if (!key) continue;
93
+ switch (key.toUpperCase()) {
94
+ case "FREQ":
95
+ opts.freq = val.toUpperCase();
96
+ break;
97
+ case "INTERVAL":
98
+ opts.interval = parseInt(val, 10);
99
+ break;
100
+ case "COUNT":
101
+ opts.count = parseInt(val, 10);
102
+ break;
103
+ case "UNTIL": {
104
+ opts.until = parseIcsDateTime(val, tzid || "UTC");
105
+ if (!val.endsWith("Z") && tzid !== "UTC") {
106
+ throw new Error("UNTIL rule part MUST always be specified as a date with UTC time");
107
+ }
108
+ break;
109
+ }
110
+ case "BYHOUR":
111
+ opts.byHour = parseNumberArray(val, true);
112
+ break;
113
+ case "BYMINUTE":
114
+ opts.byMinute = parseNumberArray(val, true);
115
+ break;
116
+ case "BYSECOND":
117
+ opts.bySecond = parseNumberArray(val, true);
118
+ break;
119
+ case "BYDAY":
120
+ opts.byDay = val.split(",");
121
+ break;
122
+ case "BYMONTH":
123
+ opts.byMonth = parseNumberArray(val);
124
+ break;
125
+ case "BYMONTHDAY":
126
+ opts.byMonthDay = parseNumberArray(val);
127
+ break;
128
+ case "BYYEARDAY":
129
+ opts.byYearDay = parseNumberArray(val);
130
+ break;
131
+ case "BYWEEKNO":
132
+ opts.byWeekNo = parseNumberArray(val);
133
+ break;
134
+ case "BYSETPOS":
135
+ opts.bySetPos = parseNumberArray(val);
136
+ break;
137
+ case "WKST":
138
+ opts.wkst = val;
139
+ break;
140
+ }
141
+ }
142
+ return opts;
143
+ }
144
+ var RRuleTemporal = class _RRuleTemporal {
145
+ constructor(params) {
146
+ var _a, _b, _c, _d, _e;
147
+ let manual;
148
+ if ("rruleString" in params) {
149
+ const parsed = parseRRuleString(params.rruleString, params.tzid);
150
+ this.tzid = (_b = (_a = parsed.tzid) != null ? _a : params.tzid) != null ? _b : "UTC";
151
+ this.originalDtstart = parsed.dtstart;
152
+ manual = __spreadValues(__spreadValues({}, params), parsed);
153
+ } else {
154
+ manual = __spreadValues({}, params);
155
+ if (typeof manual.dtstart === "string") {
156
+ throw new Error("Manual dtstart must be a ZonedDateTime");
157
+ }
158
+ manual.tzid = manual.tzid || manual.dtstart.timeZoneId;
159
+ this.tzid = manual.tzid;
160
+ this.originalDtstart = manual.dtstart;
161
+ }
162
+ if (!manual.freq) throw new Error("RRULE must include FREQ");
163
+ manual.interval = (_c = manual.interval) != null ? _c : 1;
164
+ if (manual.interval <= 0) {
165
+ throw new Error("Cannot create RRule: interval must be greater than 0");
166
+ }
167
+ if (manual.until && !(manual.until instanceof Temporal.ZonedDateTime)) {
168
+ throw new Error("Manual until must be a ZonedDateTime");
169
+ }
170
+ this.opts = this.sanitizeOpts(manual);
171
+ this.maxIterations = (_d = manual.maxIterations) != null ? _d : 1e4;
172
+ this.includeDtstart = (_e = manual.includeDtstart) != null ? _e : false;
173
+ }
174
+ sanitizeNumericArray(arr, min, max, allowZero = false, sort = false) {
175
+ if (!arr) return void 0;
176
+ const sanitized = arr.filter((n) => Number.isInteger(n) && n >= min && n <= max && (allowZero || n !== 0));
177
+ if (sanitized.length === 0) return void 0;
178
+ return sort ? sanitized.sort((a, b) => a - b) : sanitized;
179
+ }
180
+ sanitizeByDay(byDay) {
181
+ const validDay = /^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/;
182
+ const days = (byDay != null ? byDay : []).filter((day) => day && typeof day === "string");
183
+ for (const day of days) {
184
+ const match = day.match(validDay);
185
+ if (!match) {
186
+ throw new Error(`Invalid BYDAY value: ${day}`);
187
+ }
188
+ const ord = match[1];
189
+ if (ord) {
190
+ const ordInt = parseInt(ord, 10);
191
+ if (ordInt === 0) {
192
+ throw new Error(`Invalid BYDAY value: ${day}`);
193
+ }
194
+ }
195
+ }
196
+ return days.length > 0 ? days : void 0;
197
+ }
198
+ sanitizeOpts(opts) {
199
+ opts.byDay = this.sanitizeByDay(opts.byDay);
200
+ opts.byMonth = this.sanitizeNumericArray(opts.byMonth, 1, 12, false, false);
201
+ opts.byMonthDay = this.sanitizeNumericArray(opts.byMonthDay, -31, 31, false, false);
202
+ opts.byYearDay = this.sanitizeNumericArray(opts.byYearDay, -366, 366, false, false);
203
+ opts.byWeekNo = this.sanitizeNumericArray(opts.byWeekNo, -53, 53, false, false);
204
+ opts.byHour = this.sanitizeNumericArray(opts.byHour, 0, 23, true, true);
205
+ opts.byMinute = this.sanitizeNumericArray(opts.byMinute, 0, 59, true, true);
206
+ opts.bySecond = this.sanitizeNumericArray(opts.bySecond, 0, 59, true, true);
207
+ if (opts.bySetPos) {
208
+ if (opts.bySetPos.some((p) => p === 0)) {
209
+ throw new Error("bySetPos may not contain 0");
210
+ }
211
+ opts.bySetPos = this.sanitizeNumericArray(opts.bySetPos, -Infinity, Infinity, false, false);
212
+ }
213
+ return opts;
214
+ }
215
+ rawAdvance(zdt) {
216
+ const { freq, interval } = this.opts;
217
+ switch (freq) {
218
+ case "DAILY":
219
+ return zdt.add({ days: interval });
220
+ case "WEEKLY":
221
+ return zdt.add({ weeks: interval });
222
+ case "MONTHLY":
223
+ return zdt.add({ months: interval });
224
+ case "YEARLY":
225
+ return zdt.add({ years: interval });
226
+ case "HOURLY": {
227
+ const originalHour = zdt.hour;
228
+ let next = zdt.add({ hours: interval });
229
+ if (next.hour === originalHour && interval === 1) {
230
+ next = next.add({ hours: interval });
231
+ }
232
+ return next;
233
+ }
234
+ case "MINUTELY":
235
+ return zdt.add({ minutes: interval });
236
+ case "SECONDLY":
237
+ return zdt.add({ seconds: interval });
238
+ default:
239
+ throw new Error(`Unsupported FREQ: ${freq}`);
240
+ }
241
+ }
242
+ /** Expand one base ZonedDateTime into all BYHOUR × BYMINUTE × BYSECOND
243
+ * combinations, keeping chronological order. If the options are not
244
+ * present the original date is returned unchanged.
245
+ */
246
+ expandByTime(base) {
247
+ var _a, _b, _c;
248
+ const hours = (_a = this.opts.byHour) != null ? _a : [base.hour];
249
+ const minutes = (_b = this.opts.byMinute) != null ? _b : [base.minute];
250
+ const seconds = (_c = this.opts.bySecond) != null ? _c : [base.second];
251
+ const out = [];
252
+ for (const h of hours) {
253
+ for (const m of minutes) {
254
+ for (const s of seconds) {
255
+ out.push(base.with({ hour: h, minute: m, second: s }));
256
+ }
257
+ }
258
+ }
259
+ return out.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
260
+ }
261
+ nextCandidateSameDate(zdt) {
262
+ const { freq, interval = 1, byHour, byMinute, bySecond } = this.opts;
263
+ if (freq === "HOURLY" && byHour && byHour.length === 1) {
264
+ return this.applyTimeOverride(zdt.add({ days: interval }));
265
+ }
266
+ if (freq === "MINUTELY" && byMinute && byMinute.length === 1) {
267
+ return this.applyTimeOverride(zdt.add({ hours: interval }));
268
+ }
269
+ if (bySecond && bySecond.length > 1) {
270
+ const idx = bySecond.indexOf(zdt.second);
271
+ if (idx !== -1 && idx < bySecond.length - 1) {
272
+ return zdt.with({ second: bySecond[idx + 1] });
273
+ }
274
+ }
275
+ if (freq === "MINUTELY" && byHour && byHour.length > 1 && !byMinute) {
276
+ const next = zdt.add({ minutes: interval });
277
+ if (byHour.includes(next.hour)) {
278
+ return next.with({ second: bySecond ? bySecond[0] : zdt.second });
279
+ }
280
+ const nextHour = byHour.find((h) => h > zdt.hour) || byHour[0];
281
+ if (nextHour && nextHour > zdt.hour) {
282
+ return zdt.with({ hour: nextHour, minute: 0, second: bySecond ? bySecond[0] : zdt.second });
283
+ }
284
+ return this.applyTimeOverride(zdt.add({ days: 1 }));
285
+ }
286
+ if (freq === "SECONDLY") {
287
+ let candidate = zdt;
288
+ if (bySecond && bySecond.length > 0) {
289
+ const nextSecondInList = bySecond.find((s) => s > candidate.second);
290
+ if (nextSecondInList !== void 0) {
291
+ return candidate.with({ second: nextSecondInList });
292
+ }
293
+ candidate = candidate.with({ second: bySecond[0] }).add({ minutes: 1 });
294
+ } else {
295
+ candidate = candidate.add({ seconds: interval });
296
+ }
297
+ if (byMinute && byMinute.length > 0) {
298
+ if (!byMinute.includes(candidate.minute) || candidate.minute === zdt.minute && candidate.second < zdt.second) {
299
+ const nextMinuteInList = byMinute.find((m) => m > candidate.minute);
300
+ if (nextMinuteInList !== void 0) {
301
+ return candidate.with({ minute: nextMinuteInList, second: bySecond ? bySecond[0] : 0 });
302
+ }
303
+ candidate = candidate.with({ minute: byMinute[0], second: bySecond ? bySecond[0] : 0 }).add({ hours: 1 });
304
+ }
305
+ }
306
+ if (byHour && byHour.length > 0) {
307
+ if (!byHour.includes(candidate.hour) || candidate.hour === zdt.hour && candidate.minute < zdt.minute) {
308
+ const nextHourInList = byHour.find((h) => h > candidate.hour);
309
+ if (nextHourInList !== void 0) {
310
+ return candidate.with({
311
+ hour: nextHourInList,
312
+ minute: byMinute ? byMinute[0] : 0,
313
+ second: bySecond ? bySecond[0] : 0
314
+ });
315
+ }
316
+ candidate = candidate.with({ hour: byHour[0], minute: byMinute ? byMinute[0] : 0, second: bySecond ? bySecond[0] : 0 }).add({ days: 1 });
317
+ }
318
+ }
319
+ return candidate;
320
+ }
321
+ if (byMinute && byMinute.length > 1) {
322
+ const idx = byMinute.indexOf(zdt.minute);
323
+ if (idx !== -1 && idx < byMinute.length - 1) {
324
+ return zdt.with({
325
+ minute: byMinute[idx + 1],
326
+ second: bySecond ? bySecond[0] : zdt.second
327
+ });
328
+ }
329
+ if (freq === "MINUTELY" && idx === byMinute.length - 1) {
330
+ if (byHour && byHour.length > 0) {
331
+ const currentHourIdx = byHour.indexOf(zdt.hour);
332
+ if (currentHourIdx !== -1 && currentHourIdx < byHour.length - 1) {
333
+ return zdt.with({
334
+ hour: byHour[currentHourIdx + 1],
335
+ minute: byMinute[0],
336
+ second: bySecond ? bySecond[0] : zdt.second
337
+ });
338
+ } else {
339
+ return this.applyTimeOverride(zdt.add({ days: 1 }));
340
+ }
341
+ }
342
+ return zdt.add({ hours: interval }).with({
343
+ minute: byMinute[0],
344
+ second: bySecond ? bySecond[0] : zdt.second
345
+ });
346
+ }
347
+ }
348
+ if (byHour && byHour.length > 1) {
349
+ const idx = byHour.indexOf(zdt.hour);
350
+ if (idx !== -1 && idx < byHour.length - 1) {
351
+ return zdt.with({
352
+ hour: byHour[idx + 1],
353
+ minute: byMinute ? byMinute[0] : zdt.minute,
354
+ second: bySecond ? bySecond[0] : zdt.second
355
+ });
356
+ }
357
+ }
358
+ if (freq === "HOURLY" && byHour && byHour.length > 1) {
359
+ return this.applyTimeOverride(zdt.add({ days: 1 }));
360
+ }
361
+ return this.applyTimeOverride(this.rawAdvance(zdt));
362
+ }
363
+ applyTimeOverride(zdt) {
364
+ const { byHour, byMinute, bySecond } = this.opts;
365
+ let dt = zdt;
366
+ if (byHour) dt = dt.with({ hour: byHour[0] });
367
+ if (byMinute) dt = dt.with({ minute: byMinute[0] });
368
+ if (bySecond) dt = dt.with({ second: bySecond[0] });
369
+ return dt;
370
+ }
371
+ computeFirst() {
372
+ var _a, _b, _c, _d;
373
+ let zdt = this.originalDtstart;
374
+ if (((_a = this.opts.byWeekNo) == null ? void 0 : _a.length) && ["DAILY", "HOURLY", "MINUTELY", "SECONDLY"].includes(this.opts.freq)) {
375
+ let targetWeek = this.opts.byWeekNo[0];
376
+ let targetYear = zdt.year;
377
+ while (targetYear <= zdt.year + 10) {
378
+ const jan1 = zdt.with({ year: targetYear, month: 1, day: 1 });
379
+ const dec31 = zdt.with({ year: targetYear, month: 12, day: 31 });
380
+ let hasTargetWeek = false;
381
+ if (targetWeek > 0) {
382
+ let maxWeek = 52;
383
+ if (jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4) {
384
+ maxWeek = 53;
385
+ }
386
+ hasTargetWeek = targetWeek <= maxWeek;
387
+ } else {
388
+ let maxWeek = 52;
389
+ if (jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4) {
390
+ maxWeek = 53;
391
+ }
392
+ hasTargetWeek = -targetWeek <= maxWeek;
393
+ }
394
+ if (hasTargetWeek) {
395
+ const firstThursday = jan1.add({ days: (4 - jan1.dayOfWeek + 7) % 7 });
396
+ let weekStart;
397
+ if (targetWeek > 0) {
398
+ weekStart = firstThursday.subtract({ days: 3 }).add({ weeks: targetWeek - 1 });
399
+ } else {
400
+ const lastWeek = jan1.dayOfWeek === 4 || dec31.dayOfWeek === 4 ? 53 : 52;
401
+ weekStart = firstThursday.subtract({ days: 3 }).add({ weeks: lastWeek + targetWeek });
402
+ }
403
+ if ((_b = this.opts.byDay) == null ? void 0 : _b.length) {
404
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
405
+ const targetDays = this.opts.byDay.map((tok) => {
406
+ var _a2;
407
+ return (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
408
+ }).filter(Boolean).map((day) => dayMap[day]).filter(Boolean);
409
+ if (targetDays.length) {
410
+ const candidates = targetDays.map((dayOfWeek) => {
411
+ const delta = (dayOfWeek - weekStart.dayOfWeek + 7) % 7;
412
+ return weekStart.add({ days: delta });
413
+ });
414
+ const firstCandidate = candidates.sort((a, b) => Temporal.ZonedDateTime.compare(a, b))[0];
415
+ if (firstCandidate && Temporal.ZonedDateTime.compare(firstCandidate, this.originalDtstart) >= 0) {
416
+ zdt = firstCandidate;
417
+ break;
418
+ }
419
+ }
420
+ } else {
421
+ if (Temporal.ZonedDateTime.compare(weekStart, this.originalDtstart) >= 0) {
422
+ zdt = weekStart;
423
+ break;
424
+ }
425
+ }
426
+ }
427
+ targetYear++;
428
+ }
429
+ }
430
+ if (((_c = this.opts.byDay) == null ? void 0 : _c.length) && !this.opts.byWeekNo) {
431
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
432
+ const hasOrdinalTokens = this.opts.byDay.some((tok) => /^[+-]?\d/.test(tok));
433
+ if (hasOrdinalTokens && this.opts.byMonth && (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY")) {
434
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
435
+ let foundFirst = false;
436
+ for (let year = zdt.year; year <= zdt.year + 10 && !foundFirst; year++) {
437
+ for (const month of months) {
438
+ if (year === zdt.year && month < zdt.month) continue;
439
+ const monthSample = zdt.with({ year, month, day: 1 });
440
+ const monthlyOccs = this.generateMonthlyOccurrences(monthSample);
441
+ for (const occ of monthlyOccs) {
442
+ if (Temporal.ZonedDateTime.compare(occ, zdt) >= 0) {
443
+ if (!occ.toPlainDate().equals(zdt.toPlainDate())) {
444
+ zdt = this.applyTimeOverride(occ.with({ hour: 0, minute: 0, second: 0 }));
445
+ } else {
446
+ zdt = occ;
447
+ }
448
+ foundFirst = true;
449
+ break;
450
+ }
451
+ }
452
+ if (foundFirst) break;
453
+ }
454
+ }
455
+ } else {
456
+ let deltas;
457
+ if (["DAILY", "HOURLY", "MINUTELY", "SECONDLY"].includes(this.opts.freq) && this.opts.byDay.every((tok) => /^[A-Z]{2}$/.test(tok))) {
458
+ deltas = this.opts.byDay.map((tok) => (dayMap[tok] - zdt.dayOfWeek + 7) % 7);
459
+ } else {
460
+ deltas = this.opts.byDay.map((tok) => {
461
+ var _a2;
462
+ const wdTok = (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
463
+ return wdTok ? (dayMap[wdTok] - zdt.dayOfWeek + 7) % 7 : null;
464
+ }).filter((d) => d !== null);
465
+ }
466
+ if (deltas.length) {
467
+ zdt = zdt.add({ days: Math.min(...deltas) });
468
+ }
469
+ }
470
+ }
471
+ const { byHour, byMinute, bySecond } = this.opts;
472
+ if (this.opts.freq === "HOURLY" && !byHour && Temporal.ZonedDateTime.compare(
473
+ zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
474
+ this.originalDtstart
475
+ ) > 0) {
476
+ zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
477
+ }
478
+ if (this.opts.freq === "MINUTELY" && !byMinute && Temporal.ZonedDateTime.compare(
479
+ zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
480
+ this.originalDtstart
481
+ ) > 0) {
482
+ zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
483
+ }
484
+ if (this.opts.freq === "SECONDLY" && ((_d = this.opts.byWeekNo) == null ? void 0 : _d.length) && !bySecond && Temporal.ZonedDateTime.compare(
485
+ zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 }),
486
+ this.originalDtstart
487
+ ) > 0) {
488
+ zdt = zdt.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
489
+ }
490
+ if (byHour || byMinute || bySecond) {
491
+ const candidates = this.expandByTime(zdt);
492
+ for (const candidate of candidates) {
493
+ if (Temporal.ZonedDateTime.compare(candidate, this.originalDtstart) >= 0) {
494
+ return candidate;
495
+ }
496
+ }
497
+ zdt = this.applyTimeOverride(this.rawAdvance(zdt));
498
+ }
499
+ return zdt;
500
+ }
501
+ // --- NEW: constraint checks ---
502
+ // 2) Replace your matchesByDay with this:
503
+ matchesByDay(zdt) {
504
+ const { byDay, freq } = this.opts;
505
+ if (!byDay) return true;
506
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
507
+ for (const token of byDay) {
508
+ const m = token.match(/^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/);
509
+ if (!m) continue;
510
+ const ord = m[1] ? parseInt(m[1], 10) : 0;
511
+ const weekday = m[2];
512
+ if (!weekday) continue;
513
+ const wd = dayMap[weekday];
514
+ if (freq === "DAILY") {
515
+ if (zdt.dayOfWeek === wd) return true;
516
+ continue;
517
+ }
518
+ if (ord === 0) {
519
+ if (zdt.dayOfWeek === wd) return true;
520
+ continue;
521
+ }
522
+ const month = zdt.month;
523
+ let dt = zdt.with({ day: 1 });
524
+ const candidates = [];
525
+ while (dt.month === month) {
526
+ if (dt.dayOfWeek === wd) candidates.push(dt.day);
527
+ dt = dt.add({ days: 1 });
528
+ }
529
+ const idx = ord > 0 ? ord - 1 : candidates.length + ord;
530
+ if (candidates[idx] === zdt.day) return true;
531
+ }
532
+ return false;
533
+ }
534
+ matchesByMonth(zdt) {
535
+ const { byMonth } = this.opts;
536
+ if (!byMonth) return true;
537
+ return byMonth.includes(zdt.month);
538
+ }
539
+ matchesNumericConstraint(value, constraints, maxPositiveValue) {
540
+ return constraints.some((c) => {
541
+ const target = c > 0 ? c : maxPositiveValue + c + 1;
542
+ return value === target;
543
+ });
544
+ }
545
+ matchesByMonthDay(zdt) {
546
+ const { byMonthDay } = this.opts;
547
+ if (!byMonthDay) return true;
548
+ const lastDay = zdt.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
549
+ return this.matchesNumericConstraint(zdt.day, byMonthDay, lastDay);
550
+ }
551
+ matchesByHour(zdt) {
552
+ const { byHour } = this.opts;
553
+ if (!byHour) return true;
554
+ if (byHour.includes(zdt.hour)) {
555
+ return true;
556
+ }
557
+ for (const h of byHour) {
558
+ const intendedTime = zdt.with({ hour: h });
559
+ if (intendedTime.hour === zdt.hour) {
560
+ return true;
561
+ }
562
+ }
563
+ return false;
564
+ }
565
+ matchesByMinute(zdt) {
566
+ const { byMinute } = this.opts;
567
+ if (!byMinute) return true;
568
+ return byMinute.includes(zdt.minute);
569
+ }
570
+ matchesBySecond(zdt) {
571
+ const { bySecond } = this.opts;
572
+ if (!bySecond) return true;
573
+ return bySecond.includes(zdt.second);
574
+ }
575
+ matchesAll(zdt) {
576
+ return this.matchesByMonth(zdt) && this.matchesByWeekNo(zdt) && this.matchesByYearDay(zdt) && this.matchesByMonthDay(zdt) && this.matchesByDay(zdt) && this.matchesByHour(zdt) && this.matchesByMinute(zdt) && this.matchesBySecond(zdt);
577
+ }
578
+ matchesByYearDay(zdt) {
579
+ const { byYearDay } = this.opts;
580
+ if (!byYearDay) return true;
581
+ const dayOfYear = zdt.dayOfYear;
582
+ const last = zdt.with({ month: 12, day: 31 }).dayOfYear;
583
+ return this.matchesNumericConstraint(dayOfYear, byYearDay, last);
584
+ }
585
+ getIsoWeekInfo(zdt) {
586
+ const thursday = zdt.add({ days: 4 - zdt.dayOfWeek });
587
+ const year = thursday.year;
588
+ const jan1 = zdt.with({ year, month: 1, day: 1 });
589
+ const firstThursday = jan1.add({ days: (4 - jan1.dayOfWeek + 7) % 7 });
590
+ const diffDays = thursday.toPlainDate().since(firstThursday.toPlainDate()).days;
591
+ const week = Math.floor(diffDays / 7) + 1;
592
+ return { week, year };
593
+ }
594
+ matchesByWeekNo(zdt) {
595
+ const { byWeekNo } = this.opts;
596
+ if (!byWeekNo) return true;
597
+ const { week, year } = this.getIsoWeekInfo(zdt);
598
+ const jan1 = zdt.with({ year, month: 1, day: 1 });
599
+ const isLeapYear = jan1.inLeapYear;
600
+ const lastWeek = jan1.dayOfWeek === 4 || isLeapYear && jan1.dayOfWeek === 3 ? 53 : 52;
601
+ return byWeekNo.some((wn) => {
602
+ if (wn > 0) {
603
+ return week === wn;
604
+ } else {
605
+ return week === lastWeek + wn + 1;
606
+ }
607
+ });
608
+ }
609
+ options() {
610
+ return this.opts;
611
+ }
612
+ addDtstartIfNeeded(dates, iterator) {
613
+ if (this.includeDtstart && !this.matchesAll(this.originalDtstart)) {
614
+ if (iterator && !iterator(this.originalDtstart, dates.length)) {
615
+ return false;
616
+ }
617
+ dates.push(this.originalDtstart);
618
+ if (this.shouldBreakForCountLimit(dates.length)) {
619
+ return false;
620
+ }
621
+ }
622
+ return true;
623
+ }
624
+ processOccurrences(occs, dates, start, iterator, extraFilters) {
625
+ let shouldBreak = false;
626
+ for (const occ of occs) {
627
+ if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
628
+ if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
629
+ shouldBreak = true;
630
+ break;
631
+ }
632
+ if (extraFilters && !extraFilters(occ)) {
633
+ continue;
634
+ }
635
+ if (iterator && !iterator(occ, dates.length)) {
636
+ shouldBreak = true;
637
+ break;
638
+ }
639
+ dates.push(occ);
640
+ if (this.shouldBreakForCountLimit(dates.length)) {
641
+ shouldBreak = true;
642
+ break;
643
+ }
644
+ }
645
+ return { shouldBreak };
646
+ }
647
+ /**
648
+ * Returns all occurrences of the rule.
649
+ * @param iterator - An optional callback iterator function that can be used to filter or modify the occurrences.
650
+ * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule.
651
+ */
652
+ _allMonthlyByDayOrMonthDay(iterator) {
653
+ const dates = [];
654
+ let iterationCount = 0;
655
+ const start = this.originalDtstart;
656
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
657
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
658
+ }
659
+ let monthCursor = start.with({ day: 1 });
660
+ while (true) {
661
+ if (++iterationCount > this.maxIterations) {
662
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
663
+ }
664
+ let occs = this.generateMonthlyOccurrences(monthCursor);
665
+ occs = this.applyBySetPos(occs);
666
+ if (monthCursor.month === start.month && occs.some((o) => Temporal.ZonedDateTime.compare(o, start) < 0) && occs.some((o) => Temporal.ZonedDateTime.compare(o, start) === 0)) {
667
+ monthCursor = monthCursor.add({ months: this.opts.interval });
668
+ continue;
669
+ }
670
+ const { shouldBreak } = this.processOccurrences(occs, dates, start, iterator);
671
+ if (shouldBreak) {
672
+ break;
673
+ }
674
+ monthCursor = monthCursor.add({ months: this.opts.interval });
675
+ }
676
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
677
+ }
678
+ _allWeekly(iterator) {
679
+ var _a;
680
+ const dates = [];
681
+ let iterationCount = 0;
682
+ const start = this.originalDtstart;
683
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
684
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
685
+ }
686
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
687
+ const tokens = this.opts.byDay ? [...this.opts.byDay] : this.opts.byMonthDay && this.opts.byMonthDay.length > 0 ? Object.keys(dayMap) : [Object.entries(dayMap).find(([, d]) => d === start.dayOfWeek)[0]];
688
+ const dows = tokens.map((tok) => dayMap[tok.slice(-2)]).filter((d) => d !== void 0).sort((a, b) => a - b);
689
+ const firstWeekDates = dows.map((dw) => {
690
+ const delta = (dw - start.dayOfWeek + 7) % 7;
691
+ return start.add({ days: delta });
692
+ });
693
+ const firstOccurrence = firstWeekDates.reduce((a, b) => Temporal.ZonedDateTime.compare(a, b) <= 0 ? a : b);
694
+ const wkstDay = (_a = dayMap[this.opts.wkst || "MO"]) != null ? _a : 1;
695
+ const firstOccWeekOffset = (firstOccurrence.dayOfWeek - wkstDay + 7) % 7;
696
+ let weekCursor = firstOccurrence.subtract({ days: firstOccWeekOffset });
697
+ while (true) {
698
+ if (++iterationCount > this.maxIterations) {
699
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
700
+ }
701
+ let occs = dows.flatMap((dw) => {
702
+ const delta = (dw - wkstDay + 7) % 7;
703
+ const sameDate = weekCursor.add({ days: delta });
704
+ return this.expandByTime(sameDate);
705
+ }).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
706
+ occs = this.applyBySetPos(occs);
707
+ const { shouldBreak } = this.processOccurrences(
708
+ occs,
709
+ dates,
710
+ start,
711
+ iterator,
712
+ (occ) => this.matchesByMonth(occ) && this.matchesByMonthDay(occ)
713
+ );
714
+ if (shouldBreak) {
715
+ break;
716
+ }
717
+ weekCursor = weekCursor.add({ weeks: this.opts.interval });
718
+ }
719
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
720
+ }
721
+ _allMonthlyByMonth(iterator) {
722
+ const dates = [];
723
+ let iterationCount = 0;
724
+ const start = this.originalDtstart;
725
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
726
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
727
+ }
728
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
729
+ let monthOffset = 0;
730
+ let startMonthIndex = months.findIndex((m) => m >= start.month);
731
+ if (startMonthIndex === -1) {
732
+ startMonthIndex = 0;
733
+ monthOffset = 1;
734
+ }
735
+ while (true) {
736
+ if (++iterationCount > this.maxIterations) {
737
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
738
+ }
739
+ const monthIndex = startMonthIndex + monthOffset;
740
+ const targetMonth = months[monthIndex % months.length];
741
+ const yearsToAdd = Math.floor(monthIndex / months.length);
742
+ const candidate = start.with({
743
+ year: start.year + yearsToAdd,
744
+ month: targetMonth
745
+ });
746
+ if (this.opts.until && Temporal.ZonedDateTime.compare(candidate, this.opts.until) > 0) {
747
+ break;
748
+ }
749
+ if (Temporal.ZonedDateTime.compare(candidate, start) >= 0) {
750
+ if (iterator && !iterator(candidate, dates.length)) {
751
+ break;
752
+ }
753
+ dates.push(candidate);
754
+ if (this.shouldBreakForCountLimit(dates.length)) {
755
+ break;
756
+ }
757
+ }
758
+ monthOffset++;
759
+ }
760
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
761
+ }
762
+ _allYearlyByMonth(iterator) {
763
+ const dates = [];
764
+ let iterationCount = 0;
765
+ const start = this.originalDtstart;
766
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
767
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
768
+ }
769
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
770
+ let yearOffset = 0;
771
+ while (true) {
772
+ if (++iterationCount > this.maxIterations) {
773
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
774
+ }
775
+ const year = start.year + yearOffset * this.opts.interval;
776
+ for (const month of months) {
777
+ let occ = start.with({ year, month });
778
+ occ = this.applyTimeOverride(occ);
779
+ if (Temporal.ZonedDateTime.compare(occ, start) < 0) {
780
+ continue;
781
+ }
782
+ if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
783
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
784
+ }
785
+ if (iterator && !iterator(occ, dates.length)) {
786
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
787
+ }
788
+ dates.push(occ);
789
+ if (this.shouldBreakForCountLimit(dates.length)) {
790
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
791
+ }
792
+ }
793
+ yearOffset++;
794
+ }
795
+ }
796
+ _allYearlyComplex(iterator) {
797
+ const dates = [];
798
+ let iterationCount = 0;
799
+ const start = this.originalDtstart;
800
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
801
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
802
+ }
803
+ let yearCursor = start.with({ month: 1, day: 1 });
804
+ while (true) {
805
+ if (++iterationCount > this.maxIterations) {
806
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
807
+ }
808
+ const occs = this.generateYearlyOccurrences(yearCursor);
809
+ const uniqueOccs = [];
810
+ if (occs.length > 0) {
811
+ uniqueOccs.push(occs[0]);
812
+ for (let i = 1; i < occs.length; i++) {
813
+ if (Temporal.ZonedDateTime.compare(occs[i], occs[i - 1]) !== 0) {
814
+ uniqueOccs.push(occs[i]);
815
+ }
816
+ }
817
+ }
818
+ const { shouldBreak } = this.processOccurrences(uniqueOccs, dates, start, iterator);
819
+ if (shouldBreak) {
820
+ break;
821
+ }
822
+ const interval = this.opts.freq === "WEEKLY" ? 1 : this.opts.interval;
823
+ yearCursor = yearCursor.add({ years: interval });
824
+ if (this.opts.freq === "WEEKLY" && this.opts.until && yearCursor.year > this.opts.until.year) {
825
+ break;
826
+ }
827
+ }
828
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
829
+ }
830
+ _allMinutelySecondlyComplex(iterator) {
831
+ const dates = [];
832
+ let iterationCount = 0;
833
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
834
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
835
+ }
836
+ let current = this.computeFirst();
837
+ while (true) {
838
+ if (++iterationCount > this.maxIterations) {
839
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
840
+ }
841
+ if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
842
+ break;
843
+ }
844
+ if (this.matchesAll(current)) {
845
+ if (iterator && !iterator(current, dates.length)) {
846
+ break;
847
+ }
848
+ dates.push(current);
849
+ if (this.shouldBreakForCountLimit(dates.length)) {
850
+ break;
851
+ }
852
+ current = this.nextCandidateSameDate(current);
853
+ } else {
854
+ current = this.findNextValidDate(current);
855
+ }
856
+ }
857
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
858
+ }
859
+ _allMonthlyByWeekNo(iterator) {
860
+ const dates = [];
861
+ let iterationCount = 0;
862
+ const start = this.originalDtstart;
863
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
864
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
865
+ }
866
+ let current = start;
867
+ const weekNos = [...this.opts.byWeekNo].sort((a, b) => a - b);
868
+ const interval = this.opts.interval;
869
+ let monthsAdvanced = 0;
870
+ let lastYearProcessed = -1;
871
+ outer_loop: while (true) {
872
+ if (this.shouldBreakForCountLimit(dates.length)) {
873
+ break;
874
+ }
875
+ if (++iterationCount > this.maxIterations) {
876
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
877
+ }
878
+ const year = current.year;
879
+ if (year !== lastYearProcessed && current.month >= start.month) {
880
+ lastYearProcessed = year;
881
+ for (const weekNo of weekNos) {
882
+ const occs = this.generateOccurrencesForWeekInYear(year, weekNo);
883
+ for (const occ of occs) {
884
+ if (Temporal.ZonedDateTime.compare(occ, start) >= 0) {
885
+ if (iterator && !iterator(occ, dates.length)) {
886
+ break outer_loop;
887
+ }
888
+ dates.push(occ);
889
+ if (this.shouldBreakForCountLimit(dates.length)) {
890
+ break outer_loop;
891
+ }
892
+ }
893
+ }
894
+ }
895
+ }
896
+ monthsAdvanced += interval;
897
+ current = start.add({ months: monthsAdvanced });
898
+ if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
899
+ break;
900
+ }
901
+ }
902
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
903
+ }
904
+ _allMonthlyByYearDay(iterator) {
905
+ const dates = [];
906
+ let iterationCount = 0;
907
+ const start = this.originalDtstart;
908
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
909
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
910
+ }
911
+ let year = start.year;
912
+ const yearDays = [...this.opts.byYearDay].sort((a, b) => a - b);
913
+ const interval = this.opts.interval;
914
+ const startMonthAbs = start.year * 12 + start.month;
915
+ outer_loop: while (true) {
916
+ if (this.shouldBreakForCountLimit(dates.length)) {
917
+ break;
918
+ }
919
+ if (++iterationCount > this.maxIterations) {
920
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
921
+ }
922
+ const yearStart = start.with({ year, month: 1, day: 1 });
923
+ const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
924
+ for (const yd of yearDays) {
925
+ const dayNum = yd > 0 ? yd : lastDayOfYear + yd + 1;
926
+ if (dayNum <= 0 || dayNum > lastDayOfYear) continue;
927
+ const baseOcc = yearStart.add({ days: dayNum - 1 });
928
+ for (const occ of this.expandByTime(baseOcc)) {
929
+ if (Temporal.ZonedDateTime.compare(occ, start) < 0) continue;
930
+ if (dates.some((d) => Temporal.ZonedDateTime.compare(d, occ) === 0)) continue;
931
+ const occMonthAbs = occ.year * 12 + occ.month;
932
+ if ((occMonthAbs - startMonthAbs) % interval !== 0) {
933
+ continue;
934
+ }
935
+ if (!this.matchesByMonth(occ)) {
936
+ continue;
937
+ }
938
+ if (this.opts.until && Temporal.ZonedDateTime.compare(occ, this.opts.until) > 0) {
939
+ break outer_loop;
940
+ }
941
+ if (iterator && !iterator(occ, dates.length)) {
942
+ break outer_loop;
943
+ }
944
+ dates.push(occ);
945
+ if (this.shouldBreakForCountLimit(dates.length)) {
946
+ break outer_loop;
947
+ }
948
+ }
949
+ }
950
+ year++;
951
+ if (this.opts.until && year > this.opts.until.year + 2) {
952
+ break;
953
+ }
954
+ if (!this.opts.until && this.opts.count) {
955
+ const yearsToScan = Math.ceil(this.opts.count / (this.opts.byYearDay.length || 1)) * interval + 5;
956
+ if (year > start.year + yearsToScan) {
957
+ break;
958
+ }
959
+ }
960
+ }
961
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
962
+ }
963
+ _allDailyMinutelyHourlyWithBySetPos(iterator) {
964
+ const dates = [];
965
+ let iterationCount = 0;
966
+ const start = this.originalDtstart;
967
+ if (!this.addDtstartIfNeeded(dates, iterator)) {
968
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
969
+ }
970
+ let cursor;
971
+ let duration;
972
+ switch (this.opts.freq) {
973
+ case "MINUTELY":
974
+ cursor = start.with({ second: 0, microsecond: 0, nanosecond: 0 });
975
+ duration = { minutes: this.opts.interval };
976
+ break;
977
+ case "HOURLY":
978
+ cursor = start.with({ minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
979
+ duration = { hours: this.opts.interval };
980
+ break;
981
+ case "DAILY":
982
+ cursor = start.with({ hour: 0, minute: 0, second: 0, microsecond: 0, nanosecond: 0 });
983
+ duration = { days: this.opts.interval };
984
+ break;
985
+ default:
986
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
987
+ }
988
+ while (true) {
989
+ if (++iterationCount > this.maxIterations) {
990
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
991
+ }
992
+ let periodOccs = this.expandByTime(cursor);
993
+ periodOccs = periodOccs.filter((occ) => this.matchesAll(occ));
994
+ periodOccs = this.applyBySetPos(periodOccs);
995
+ const { shouldBreak } = this.processOccurrences(periodOccs, dates, start, iterator);
996
+ if (shouldBreak) {
997
+ break;
998
+ }
999
+ cursor = cursor.add(duration);
1000
+ if (this.opts.until && Temporal.ZonedDateTime.compare(cursor, this.opts.until) > 0) {
1001
+ break;
1002
+ }
1003
+ }
1004
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
1005
+ }
1006
+ _allFallback(iterator) {
1007
+ const dates = [];
1008
+ let iterationCount = 0;
1009
+ let current = this.computeFirst();
1010
+ if (this.includeDtstart && Temporal.ZonedDateTime.compare(current, this.originalDtstart) > 0) {
1011
+ if (iterator && !iterator(this.originalDtstart, dates.length)) {
1012
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
1013
+ }
1014
+ dates.push(this.originalDtstart);
1015
+ if (this.shouldBreakForCountLimit(dates.length)) {
1016
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
1017
+ }
1018
+ }
1019
+ while (true) {
1020
+ if (++iterationCount > this.maxIterations) {
1021
+ throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
1022
+ }
1023
+ if (this.opts.until && Temporal.ZonedDateTime.compare(current, this.opts.until) > 0) {
1024
+ break;
1025
+ }
1026
+ if (this.matchesAll(current)) {
1027
+ if (iterator && !iterator(current, dates.length)) {
1028
+ break;
1029
+ }
1030
+ dates.push(current);
1031
+ if (this.shouldBreakForCountLimit(dates.length)) {
1032
+ break;
1033
+ }
1034
+ }
1035
+ current = this.nextCandidateSameDate(current);
1036
+ }
1037
+ return this.applyCountLimitAndMergeRDates(dates, iterator);
1038
+ }
1039
+ /**
1040
+ * Returns all occurrences of the rule.
1041
+ * @param iterator - An optional callback iterator function that can be used to filter or modify the occurrences.
1042
+ * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule.
1043
+ */
1044
+ all(iterator) {
1045
+ if (this.opts.byWeekNo && this.opts.byYearDay) {
1046
+ const yearStart = this.originalDtstart.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 });
1047
+ const yearDays = this.opts.byYearDay.map((yd) => {
1048
+ const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
1049
+ return yd > 0 ? yd : lastDayOfYear + yd + 1;
1050
+ });
1051
+ let possibleDate = false;
1052
+ for (const yd of yearDays) {
1053
+ const date = yearStart.add({ days: yd - 1 });
1054
+ if (this.matchesByWeekNo(date)) {
1055
+ possibleDate = true;
1056
+ break;
1057
+ }
1058
+ }
1059
+ if (!possibleDate) {
1060
+ return [];
1061
+ }
1062
+ }
1063
+ if (!this.opts.count && !this.opts.until && !iterator) {
1064
+ throw new Error("all() requires iterator when no COUNT/UNTIL");
1065
+ }
1066
+ if (this.opts.freq === "MONTHLY" && (this.opts.byDay || this.opts.byMonthDay) && !this.opts.byWeekNo) {
1067
+ return this._allMonthlyByDayOrMonthDay(iterator);
1068
+ }
1069
+ if (this.opts.freq === "WEEKLY" && !(this.opts.byYearDay && this.opts.byYearDay.length > 0) && !(this.opts.byWeekNo && this.opts.byWeekNo.length > 0)) {
1070
+ return this._allWeekly(iterator);
1071
+ }
1072
+ if (this.opts.freq === "MONTHLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay) {
1073
+ return this._allMonthlyByMonth(iterator);
1074
+ }
1075
+ if (this.opts.freq === "YEARLY" && this.opts.byMonth && !this.opts.byDay && !this.opts.byMonthDay && !this.opts.byYearDay && !this.opts.byWeekNo) {
1076
+ return this._allYearlyByMonth(iterator);
1077
+ }
1078
+ if (this.opts.freq === "YEARLY" && (this.opts.byDay || this.opts.byMonthDay || this.opts.byYearDay || this.opts.byWeekNo) || this.opts.freq === "WEEKLY" && this.opts.byYearDay && this.opts.byYearDay.length > 0 || this.opts.freq === "WEEKLY" && this.opts.byWeekNo && this.opts.byWeekNo.length > 0) {
1079
+ return this._allYearlyComplex(iterator);
1080
+ }
1081
+ if ((this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") && (this.opts.byMonth || this.opts.byWeekNo || this.opts.byYearDay || this.opts.byMonthDay || this.opts.byDay)) {
1082
+ return this._allMinutelySecondlyComplex(iterator);
1083
+ }
1084
+ if (this.opts.freq === "MONTHLY" && this.opts.byWeekNo && this.opts.byWeekNo.length > 0) {
1085
+ return this._allMonthlyByWeekNo(iterator);
1086
+ }
1087
+ if (this.opts.freq === "MONTHLY" && this.opts.byYearDay && this.opts.byYearDay.length > 0 && !this.opts.byDay && !this.opts.byMonthDay) {
1088
+ return this._allMonthlyByYearDay(iterator);
1089
+ }
1090
+ if ((this.opts.freq === "MINUTELY" || this.opts.freq === "HOURLY" || this.opts.freq === "DAILY") && this.opts.bySetPos) {
1091
+ return this._allDailyMinutelyHourlyWithBySetPos(iterator);
1092
+ }
1093
+ return this._allFallback(iterator);
1094
+ }
1095
+ /**
1096
+ * Converts rDate entries to ZonedDateTime and merges with existing dates.
1097
+ * @param dates - Array of dates to merge with
1098
+ * @returns Merged and deduplicated array of dates
1099
+ */
1100
+ mergeAndDeduplicateRDates(dates) {
1101
+ if (this.opts.rDate) {
1102
+ dates.push(...this.opts.rDate);
1103
+ }
1104
+ dates.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1105
+ const dedup = [];
1106
+ for (const d of dates) {
1107
+ if (dedup.length === 0 || Temporal.ZonedDateTime.compare(d, dedup[dedup.length - 1]) !== 0) {
1108
+ dedup.push(d);
1109
+ }
1110
+ }
1111
+ return dedup;
1112
+ }
1113
+ /**
1114
+ * Excludes exDate entries from the given array of dates.
1115
+ * @param dates - Array of dates to filter
1116
+ * @returns Filtered array with exDate entries removed
1117
+ */
1118
+ excludeExDates(dates) {
1119
+ if (!this.opts.exDate || this.opts.exDate.length === 0) return dates;
1120
+ return dates.filter((date) => {
1121
+ return !this.opts.exDate.some((exDate) => Temporal.ZonedDateTime.compare(date, exDate) === 0);
1122
+ });
1123
+ }
1124
+ /**
1125
+ * Applies count limit and merges rDates with the rule-generated dates.
1126
+ * @param dates - Array of dates generated by the rule
1127
+ * @param iterator - Optional iterator function
1128
+ * @returns Final array of dates after merging and applying count limit
1129
+ */
1130
+ applyCountLimitAndMergeRDates(dates, iterator) {
1131
+ const merged = this.mergeAndDeduplicateRDates(dates);
1132
+ const excluded = this.excludeExDates(merged);
1133
+ if (this.opts.count !== void 0) {
1134
+ let finalCount = 0;
1135
+ const finalDates = [];
1136
+ for (const d of excluded) {
1137
+ if (finalCount >= this.opts.count) break;
1138
+ if (iterator && !iterator(d, finalCount)) break;
1139
+ finalDates.push(d);
1140
+ finalCount++;
1141
+ }
1142
+ return finalDates;
1143
+ }
1144
+ return excluded;
1145
+ }
1146
+ /**
1147
+ * Checks if the count limit should break the loop based on rDate presence.
1148
+ * @param matchCount - Current number of matches
1149
+ * @returns true if the loop should break
1150
+ */
1151
+ shouldBreakForCountLimit(matchCount) {
1152
+ if (this.opts.count === void 0) return false;
1153
+ if (!this.opts.rDate) {
1154
+ return matchCount >= this.opts.count;
1155
+ }
1156
+ const rDateCount = this.opts.rDate.length;
1157
+ const targetRuleCount = Math.max(this.opts.count - rDateCount, 0);
1158
+ const safetyMargin = Math.min(targetRuleCount, 10);
1159
+ return matchCount >= targetRuleCount + safetyMargin;
1160
+ }
1161
+ /**
1162
+ * Returns all occurrences of the rule within a specified time window.
1163
+ * @param after - The start date or Temporal.ZonedDateTime object.
1164
+ * @param before - The end date or Temporal.ZonedDateTime object.
1165
+ * @param inc - Optional boolean flag to include the end date in the results.
1166
+ * @returns An array of Temporal.ZonedDateTime objects representing all occurrences of the rule within the specified time window.
1167
+ */
1168
+ between(after, before, inc = false) {
1169
+ const startInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
1170
+ const endInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
1171
+ const beforeZdt = Temporal.Instant.from(endInst).toZonedDateTimeISO(this.tzid);
1172
+ const tempOpts = __spreadValues({}, this.opts);
1173
+ if (!tempOpts.until || Temporal.ZonedDateTime.compare(beforeZdt, tempOpts.until) < 0) {
1174
+ tempOpts.until = beforeZdt;
1175
+ }
1176
+ delete tempOpts.count;
1177
+ const tempRule = new _RRuleTemporal(tempOpts);
1178
+ const allDates = tempRule.all();
1179
+ return allDates.filter((date) => {
1180
+ const inst = date.toInstant();
1181
+ const afterStart = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
1182
+ const beforeEnd = inc ? Temporal.Instant.compare(inst, endInst) <= 0 : Temporal.Instant.compare(inst, endInst) < 0;
1183
+ return afterStart && beforeEnd;
1184
+ });
1185
+ }
1186
+ /**
1187
+ * Returns the next occurrence of the rule after a specified date.
1188
+ * @param after - The start date or Temporal.ZonedDateTime object.
1189
+ * @param inc - Optional boolean flag to include occurrences on the start date.
1190
+ * @returns The next occurrence of the rule after the specified date or null if no occurrences are found.
1191
+ */
1192
+ next(after = /* @__PURE__ */ new Date(), inc = false) {
1193
+ const afterInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : after.toInstant();
1194
+ let result = null;
1195
+ this.all((occ) => {
1196
+ const inst = occ.toInstant();
1197
+ const ok = inc ? Temporal.Instant.compare(inst, afterInst) >= 0 : Temporal.Instant.compare(inst, afterInst) > 0;
1198
+ if (ok) {
1199
+ result = occ;
1200
+ return false;
1201
+ }
1202
+ return true;
1203
+ });
1204
+ return result;
1205
+ }
1206
+ /**
1207
+ * Returns the previous occurrence of the rule before a specified date.
1208
+ * @param before - The end date or Temporal.ZonedDateTime object.
1209
+ * @param inc - Optional boolean flag to include occurrences on the end date.
1210
+ * @returns The previous occurrence of the rule before the specified date or null if no occurrences are found.
1211
+ */
1212
+ previous(before = /* @__PURE__ */ new Date(), inc = false) {
1213
+ const beforeInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : before.toInstant();
1214
+ let prev = null;
1215
+ this.all((occ) => {
1216
+ const inst = occ.toInstant();
1217
+ const beyond = inc ? Temporal.Instant.compare(inst, beforeInst) > 0 : Temporal.Instant.compare(inst, beforeInst) >= 0;
1218
+ if (beyond) return false;
1219
+ prev = occ;
1220
+ return true;
1221
+ });
1222
+ return prev;
1223
+ }
1224
+ toString() {
1225
+ const iso = this.originalDtstart.toString({ smallestUnit: "second" }).replace(/[-:]/g, "");
1226
+ const dtLine = `DTSTART;TZID=${this.tzid}:${iso.slice(0, 15)}`;
1227
+ const rule = [];
1228
+ const {
1229
+ freq,
1230
+ interval,
1231
+ count,
1232
+ until,
1233
+ byHour,
1234
+ byMinute,
1235
+ bySecond,
1236
+ byDay,
1237
+ byMonth,
1238
+ byMonthDay,
1239
+ bySetPos,
1240
+ byWeekNo,
1241
+ byYearDay,
1242
+ wkst,
1243
+ rDate,
1244
+ exDate
1245
+ } = this.opts;
1246
+ rule.push(`FREQ=${freq}`);
1247
+ if (interval !== 1) rule.push(`INTERVAL=${interval}`);
1248
+ if (count !== void 0) rule.push(`COUNT=${count}`);
1249
+ if (until) {
1250
+ rule.push(`UNTIL=${this.formatIcsDateTime(until)}`);
1251
+ }
1252
+ if (byHour) rule.push(`BYHOUR=${byHour.join(",")}`);
1253
+ if (byMinute) rule.push(`BYMINUTE=${byMinute.join(",")}`);
1254
+ if (bySecond) rule.push(`BYSECOND=${bySecond.join(",")}`);
1255
+ if (byDay) rule.push(`BYDAY=${byDay.join(",")}`);
1256
+ if (byMonth) rule.push(`BYMONTH=${byMonth.join(",")}`);
1257
+ if (byMonthDay) rule.push(`BYMONTHDAY=${byMonthDay.join(",")}`);
1258
+ if (bySetPos) rule.push(`BYSETPOS=${bySetPos.join(",")}`);
1259
+ if (byWeekNo) rule.push(`BYWEEKNO=${byWeekNo.join(",")}`);
1260
+ if (byYearDay) rule.push(`BYYEARDAY=${byYearDay.join(",")}`);
1261
+ if (wkst) rule.push(`WKST=${wkst}`);
1262
+ const lines = [dtLine, `RRULE:${rule.join(";")}`];
1263
+ if (rDate) {
1264
+ lines.push(`RDATE:${this.joinDates(rDate)}`);
1265
+ }
1266
+ if (exDate) {
1267
+ lines.push(`EXDATE:${this.joinDates(exDate)}`);
1268
+ }
1269
+ return lines.join("\n");
1270
+ }
1271
+ formatIcsDateTime(date) {
1272
+ return date.toInstant().toString().replace(/[-:]/g, "").slice(0, 15) + "Z";
1273
+ }
1274
+ joinDates(dates) {
1275
+ return dates.map((d) => this.formatIcsDateTime(d));
1276
+ }
1277
+ /**
1278
+ * Given any date in a month, return all the ZonedDateTimes in that month
1279
+ * matching your opts.byDay and opts.byMonth (or the single "same day" if no BYDAY).
1280
+ */
1281
+ generateMonthlyOccurrences(sample) {
1282
+ var _a;
1283
+ const { byDay, byMonth, byMonthDay } = this.opts;
1284
+ if (byMonth && !byMonth.includes(sample.month)) return [];
1285
+ const lastDay = sample.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
1286
+ let byMonthDayHits = [];
1287
+ if (byMonthDay && byMonthDay.length > 0) {
1288
+ byMonthDayHits = byMonthDay.map((d) => d > 0 ? d : lastDay + d + 1).filter((d) => d >= 1 && d <= lastDay);
1289
+ }
1290
+ if (!byDay && byMonthDay && byMonthDay.length > 0) {
1291
+ if (byMonthDayHits.length === 0) {
1292
+ return [];
1293
+ }
1294
+ const dates = byMonthDayHits.map((d) => sample.with({ day: d }));
1295
+ return dates.flatMap((z) => this.expandByTime(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1296
+ }
1297
+ if (!byDay) {
1298
+ return this.expandByTime(sample);
1299
+ }
1300
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1301
+ const tokens = byDay.map((tok) => {
1302
+ const m = tok.match(/^([+-]?\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/);
1303
+ if (!m) return null;
1304
+ return { ord: m[1] ? parseInt(m[1], 10) : 0, wd: dayMap[m[2]] };
1305
+ }).filter((x) => x !== null);
1306
+ const buckets = {};
1307
+ let cursor = sample.with({ day: 1 });
1308
+ while (cursor.month === sample.month) {
1309
+ const dow = cursor.dayOfWeek;
1310
+ (buckets[dow] || (buckets[dow] = [])).push(cursor.day);
1311
+ cursor = cursor.add({ days: 1 });
1312
+ }
1313
+ const byDayHits = [];
1314
+ for (const { ord, wd } of tokens) {
1315
+ const list = (_a = buckets[wd]) != null ? _a : [];
1316
+ if (!list.length) continue;
1317
+ if (ord === 0) {
1318
+ for (const d of list) byDayHits.push(d);
1319
+ } else {
1320
+ const idx = ord > 0 ? ord - 1 : list.length + ord;
1321
+ const dayN = list[idx];
1322
+ if (dayN) byDayHits.push(dayN);
1323
+ }
1324
+ }
1325
+ let finalDays = byDayHits;
1326
+ if (byMonthDay && byMonthDay.length > 0) {
1327
+ if (byMonthDayHits.length === 0) {
1328
+ return [];
1329
+ }
1330
+ finalDays = finalDays.filter((d) => byMonthDayHits.includes(d));
1331
+ }
1332
+ const hits = finalDays.map((d) => sample.with({ day: d }));
1333
+ return hits.flatMap((z) => this.expandByTime(z)).sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1334
+ }
1335
+ /**
1336
+ * Given any date in a year, return all ZonedDateTimes in that year matching
1337
+ * the BYDAY/BYMONTHDAY/BYMONTH constraints. Months default to DTSTART's month
1338
+ * if BYMONTH is not specified.
1339
+ */
1340
+ generateYearlyOccurrences(sample) {
1341
+ const months = this.opts.byMonth ? [...this.opts.byMonth].sort((a, b) => a - b) : this.opts.byMonthDay || this.opts.byDay ? [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] : [this.originalDtstart.month];
1342
+ let occs = [];
1343
+ const hasOrdinalByDay = this.opts.byDay && this.opts.byDay.some((t) => /^[+-]?\d/.test(t));
1344
+ if (hasOrdinalByDay && !this.opts.byMonth) {
1345
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1346
+ for (const tok of this.opts.byDay) {
1347
+ const m = tok.match(/^([+-]?\d{1,2})(MO|TU|WE|TH|FR|SA|SU)$/);
1348
+ if (!m) continue;
1349
+ const ord = parseInt(m[1], 10);
1350
+ const wd = dayMap[m[2]];
1351
+ let dt;
1352
+ if (ord > 0) {
1353
+ const jan1 = sample.with({ month: 1, day: 1 });
1354
+ const delta = (wd - jan1.dayOfWeek + 7) % 7;
1355
+ dt = jan1.add({ days: delta + 7 * (ord - 1) });
1356
+ } else {
1357
+ const dec31 = sample.with({ month: 12, day: 31 });
1358
+ const delta = (dec31.dayOfWeek - wd + 7) % 7;
1359
+ dt = dec31.subtract({ days: delta + 7 * (-ord - 1) });
1360
+ }
1361
+ occs.push(...this.expandByTime(dt));
1362
+ }
1363
+ } else if (!this.opts.byYearDay && !this.opts.byWeekNo) {
1364
+ occs = months.flatMap((m) => {
1365
+ const monthSample = sample.with({ month: m, day: 1 });
1366
+ return this.generateMonthlyOccurrences(monthSample);
1367
+ });
1368
+ }
1369
+ if (this.opts.byYearDay) {
1370
+ const last = sample.with({ month: 12, day: 31 }).dayOfYear;
1371
+ for (const d of this.opts.byYearDay) {
1372
+ const dayNum = d > 0 ? d : last + d + 1;
1373
+ if (dayNum <= 0 || dayNum > last) continue;
1374
+ const dt = this.opts.freq === "MINUTELY" ? sample.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 }) : sample.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1375
+ if (!this.opts.byMonth || this.opts.byMonth.includes(dt.month)) {
1376
+ occs.push(...this.expandByTime(dt));
1377
+ }
1378
+ }
1379
+ }
1380
+ if (this.opts.byWeekNo) {
1381
+ const { lastWeek, firstWeekStart, tokens } = this.isoWeekByDay(sample);
1382
+ for (const weekNo of this.opts.byWeekNo) {
1383
+ if (weekNo > 0 && weekNo > lastWeek || weekNo < 0 && -weekNo > lastWeek) {
1384
+ continue;
1385
+ }
1386
+ const weekIndex = weekNo > 0 ? weekNo - 1 : lastWeek + weekNo;
1387
+ const weekStart = firstWeekStart.add({ weeks: weekIndex });
1388
+ occs.push(...this.addByDay(tokens, weekStart));
1389
+ }
1390
+ }
1391
+ occs = occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1392
+ occs = this.applyBySetPos(occs);
1393
+ return occs;
1394
+ }
1395
+ addByDay(tokens, weekStart) {
1396
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1397
+ const wkst = dayMap[this.opts.wkst || "MO"];
1398
+ const entries = [];
1399
+ for (const tok of tokens) {
1400
+ if (!tok) continue;
1401
+ const targetDow = dayMap[tok];
1402
+ const inst = weekStart.add({ days: (targetDow - wkst + 7) % 7 });
1403
+ if (!this.opts.byMonth || this.opts.byMonth.includes(inst.month)) {
1404
+ entries.push(...this.expandByTime(inst));
1405
+ }
1406
+ }
1407
+ return entries;
1408
+ }
1409
+ /**
1410
+ * Helper to find the next valid value from a sorted array
1411
+ */
1412
+ findNextValidValue(currentValue, validValues, compare) {
1413
+ return validValues.find((v) => compare(v, currentValue) > 0) || null;
1414
+ }
1415
+ /**
1416
+ * Efficiently find the next valid date for MINUTELY and SECONDLY frequency by jumping over
1417
+ * large gaps when BYXXX constraints don't match.
1418
+ */
1419
+ findNextValidDate(current) {
1420
+ if (this.opts.byWeekNo && this.opts.byYearDay) {
1421
+ const yearStart = current.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 });
1422
+ const yearDays = this.opts.byYearDay.map((yd) => {
1423
+ const lastDayOfYear = yearStart.with({ month: 12, day: 31 }).dayOfYear;
1424
+ return yd > 0 ? yd : lastDayOfYear + yd + 1;
1425
+ });
1426
+ for (const yd of yearDays) {
1427
+ const date = yearStart.add({ days: yd - 1 });
1428
+ if (this.matchesByWeekNo(date)) {
1429
+ break;
1430
+ }
1431
+ }
1432
+ }
1433
+ if (this.opts.byMonth && !this.opts.byMonth.includes(current.month)) {
1434
+ const months = [...this.opts.byMonth].sort((a, b) => a - b);
1435
+ const nextMonth = this.findNextValidValue(current.month, months, (a, b) => a - b);
1436
+ if (nextMonth) {
1437
+ current = current.with({ month: nextMonth, day: 1, hour: 0, minute: 0, second: 0 });
1438
+ } else {
1439
+ current = current.add({ years: 1 }).with({ month: months[0], day: 1, hour: 0, minute: 0, second: 0 });
1440
+ }
1441
+ current = this.applyTimeOverride(current);
1442
+ return current;
1443
+ }
1444
+ if (this.opts.byWeekNo && !this.matchesByWeekNo(current)) {
1445
+ current = current.add({ weeks: 1 }).with({ hour: 0, minute: 0, second: 0 });
1446
+ current = this.applyTimeOverride(current);
1447
+ return current;
1448
+ }
1449
+ if (this.opts.byYearDay && !this.matchesByYearDay(current)) {
1450
+ const yearDays = [...this.opts.byYearDay].sort((a, b) => a - b);
1451
+ const currentYearDay = current.dayOfYear;
1452
+ const lastDayOfYear = current.with({ month: 12, day: 31 }).dayOfYear;
1453
+ let nextYearDay = yearDays.find((d) => {
1454
+ const dayNum = d > 0 ? d : lastDayOfYear + d + 1;
1455
+ return dayNum > currentYearDay;
1456
+ });
1457
+ if (nextYearDay) {
1458
+ const dayNum = nextYearDay > 0 ? nextYearDay : lastDayOfYear + nextYearDay + 1;
1459
+ if (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") {
1460
+ current = current.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 });
1461
+ } else {
1462
+ current = current.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1463
+ }
1464
+ } else {
1465
+ const nextYear = current.add({ years: 1 });
1466
+ const nextYearLastDay = nextYear.with({ month: 12, day: 31 }).dayOfYear;
1467
+ const firstYearDay = yearDays[0];
1468
+ if (firstYearDay !== void 0) {
1469
+ const dayNum = firstYearDay > 0 ? firstYearDay : nextYearLastDay + firstYearDay + 1;
1470
+ if (this.opts.freq === "MINUTELY" || this.opts.freq === "SECONDLY") {
1471
+ current = nextYear.with({ month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }).add({ days: dayNum - 1 });
1472
+ } else {
1473
+ current = nextYear.with({ month: 1, day: 1 }).add({ days: dayNum - 1 });
1474
+ }
1475
+ }
1476
+ }
1477
+ current = this.applyTimeOverride(current);
1478
+ return current;
1479
+ }
1480
+ if (this.opts.byMonthDay && !this.matchesByMonthDay(current)) {
1481
+ const monthDays = [...this.opts.byMonthDay].sort((a, b) => a - b);
1482
+ const lastDayOfMonth = current.with({ day: 1 }).add({ months: 1 }).subtract({ days: 1 }).day;
1483
+ const currentDay = current.day;
1484
+ const validDays = monthDays.map((d) => d > 0 ? d : lastDayOfMonth + d + 1).filter((d) => d > 0 && d <= lastDayOfMonth).sort((a, b) => a - b);
1485
+ const nextDay = this.findNextValidValue(currentDay, validDays, (a, b) => a - b);
1486
+ if (nextDay) {
1487
+ current = current.with({ day: nextDay, hour: 0, minute: 0, second: 0 });
1488
+ } else {
1489
+ const nextMonth = current.add({ months: 1 }).with({ day: 1 });
1490
+ const nextMonthLastDay = nextMonth.add({ months: 1 }).subtract({ days: 1 }).day;
1491
+ const firstMonthDay = monthDays[0];
1492
+ if (firstMonthDay !== void 0) {
1493
+ const dayNum = firstMonthDay > 0 ? firstMonthDay : nextMonthLastDay + firstMonthDay + 1;
1494
+ current = nextMonth.with({
1495
+ day: Math.max(1, Math.min(dayNum, nextMonthLastDay)),
1496
+ hour: 0,
1497
+ minute: 0,
1498
+ second: 0
1499
+ });
1500
+ } else {
1501
+ current = current.add({ months: 1 }).with({ day: 1, hour: 0, minute: 0, second: 0 });
1502
+ }
1503
+ }
1504
+ current = this.applyTimeOverride(current);
1505
+ return current;
1506
+ }
1507
+ if (this.opts.byDay && !this.matchesByDay(current)) {
1508
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1509
+ const targetDays = this.opts.byDay.map((tok) => {
1510
+ var _a;
1511
+ return (_a = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a[1];
1512
+ }).filter(Boolean).map((day) => dayMap[day]).filter(Boolean);
1513
+ const nextDayOfWeek = this.findNextValidValue(current.dayOfWeek, targetDays.sort(), (a, b) => a - b);
1514
+ if (nextDayOfWeek) {
1515
+ const delta = (nextDayOfWeek - current.dayOfWeek + 7) % 7;
1516
+ current = current.add({ days: delta }).with({ hour: 0, minute: 0, second: 0 });
1517
+ } else {
1518
+ const delta = (targetDays[0] - current.dayOfWeek + 7) % 7;
1519
+ current = current.add({ days: delta + 7 }).with({ hour: 0, minute: 0, second: 0 });
1520
+ }
1521
+ current = this.applyTimeOverride(current);
1522
+ return current;
1523
+ }
1524
+ switch (this.opts.freq) {
1525
+ case "SECONDLY":
1526
+ case "MINUTELY":
1527
+ current = current.add({ days: 1 }).with({ hour: 0, minute: 0, second: 0 });
1528
+ break;
1529
+ case "HOURLY":
1530
+ current = current.add({ days: 1 }).with({ hour: 0, minute: 0, second: 0 });
1531
+ break;
1532
+ case "DAILY":
1533
+ case "WEEKLY":
1534
+ current = current.add({ months: 1 }).with({ day: 1, hour: 0, minute: 0, second: 0 });
1535
+ break;
1536
+ case "MONTHLY":
1537
+ case "YEARLY":
1538
+ current = current.add({ years: 1 }).with({ month: 1, day: 1, hour: 0, minute: 0, second: 0 });
1539
+ break;
1540
+ }
1541
+ return this.applyTimeOverride(current);
1542
+ }
1543
+ applyBySetPos(list) {
1544
+ const { bySetPos } = this.opts;
1545
+ if (!bySetPos || !bySetPos.length) return list;
1546
+ const sorted = [...list].sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1547
+ const out = [];
1548
+ const len = sorted.length;
1549
+ for (const pos of bySetPos) {
1550
+ const idx = pos > 0 ? pos - 1 : len + pos;
1551
+ if (idx >= 0 && idx < len) out.push(sorted[idx]);
1552
+ }
1553
+ return out.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1554
+ }
1555
+ isoWeekByDay(sample) {
1556
+ var _a;
1557
+ const dayMap = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };
1558
+ const wkst = dayMap[this.opts.wkst || "MO"];
1559
+ const jan1 = sample.with({ month: 1, day: 1 });
1560
+ const jan4 = sample.with({ month: 1, day: 4 });
1561
+ const delta = (jan4.dayOfWeek - wkst + 7) % 7;
1562
+ const firstWeekStart = jan4.subtract({ days: delta });
1563
+ const isLeapYear = jan1.inLeapYear;
1564
+ const lastWeek = jan1.dayOfWeek === 4 || isLeapYear && jan1.dayOfWeek === 3 ? 53 : 52;
1565
+ const tokens = ((_a = this.opts.byDay) == null ? void 0 : _a.length) ? this.opts.byDay.map((tok) => {
1566
+ var _a2;
1567
+ return (_a2 = tok.match(/(MO|TU|WE|TH|FR|SA|SU)$/)) == null ? void 0 : _a2[1];
1568
+ }) : [Object.entries(dayMap).find(([, d]) => d === this.originalDtstart.dayOfWeek)[0]];
1569
+ return { lastWeek, firstWeekStart, tokens };
1570
+ }
1571
+ /**
1572
+ * Generate occurrences for a specific week number in a given year
1573
+ */
1574
+ generateOccurrencesForWeekInYear(year, weekNo) {
1575
+ const occs = [];
1576
+ const sample = this.originalDtstart.with({ year, month: 1, day: 1 });
1577
+ const { lastWeek, firstWeekStart, tokens } = this.isoWeekByDay(sample);
1578
+ if (weekNo > 0 && weekNo > lastWeek || weekNo < 0 && -weekNo > lastWeek) {
1579
+ return occs;
1580
+ }
1581
+ const weekIndex = weekNo > 0 ? weekNo - 1 : lastWeek + weekNo;
1582
+ const weekStart = firstWeekStart.add({ weeks: weekIndex });
1583
+ occs.push(...this.addByDay(tokens, weekStart));
1584
+ return occs.sort((a, b) => Temporal.ZonedDateTime.compare(a, b));
1585
+ }
1586
+ };
1587
+
1588
+ export {
1589
+ RRuleTemporal
1590
+ };