rrule-temporal 2.0.3 → 2.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.
@@ -4605,6 +4605,45 @@ const NS_PER_MINUTE = BigInt(60) * NS_PER_SECOND;
4605
4605
  const NS_PER_HOUR = BigInt(60) * NS_PER_MINUTE;
4606
4606
  const NS_PER_DAY = BigInt(24) * NS_PER_HOUR;
4607
4607
  const NS_PER_WEEK = BigInt(7) * NS_PER_DAY;
4608
+ const TEMPORAL_MAX_EPOCH_MILLISECONDS = 864e13;
4609
+ function gcd(left, right) {
4610
+ let a = Math.abs(left);
4611
+ let b = Math.abs(right);
4612
+ while (b !== 0) {
4613
+ const next = a % b;
4614
+ a = b;
4615
+ b = next;
4616
+ }
4617
+ return a;
4618
+ }
4619
+ function weekdayMask(days) {
4620
+ let mask = 0;
4621
+ for (const day of days ?? []) mask |= 1 << day - 1;
4622
+ return mask;
4623
+ }
4624
+ function includesIsoWeekday(mask, day) {
4625
+ return mask === 0 || (mask & 1 << day - 1) !== 0;
4626
+ }
4627
+ function floorDivBigInt(dividend, divisor) {
4628
+ const quotient = dividend / divisor;
4629
+ return dividend % divisor < 0n ? quotient - 1n : quotient;
4630
+ }
4631
+ function ceilDivBigInt(dividend, divisor) {
4632
+ return -floorDivBigInt(-dividend, divisor);
4633
+ }
4634
+ function isSafeTemporalEpochMilliseconds(value) {
4635
+ return Number.isSafeInteger(value) && value >= -TEMPORAL_MAX_EPOCH_MILLISECONDS && value <= TEMPORAL_MAX_EPOCH_MILLISECONDS;
4636
+ }
4637
+ /** Proleptic Gregorian day number where 1970-01-01 is zero. */
4638
+ function gregorianEpochDay(year, month, day) {
4639
+ const adjustedYear = year - (month <= 2 ? 1 : 0);
4640
+ const era = Math.floor(adjustedYear / 400);
4641
+ const yearOfEra = adjustedYear - era * 400;
4642
+ const adjustedMonth = month + (month > 2 ? -3 : 9);
4643
+ const dayOfYear = Math.floor((153 * adjustedMonth + 2) / 5) + day - 1;
4644
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYear;
4645
+ return era * 146097 + dayOfEra - 719468;
4646
+ }
4608
4647
  function isoDayOfWeekOfEpochDay(epochDay) {
4609
4648
  return ((epochDay + 3) % 7 + 7) % 7 + 1;
4610
4649
  }
@@ -4912,16 +4951,22 @@ var RRuleTemporal = class RRuleTemporal {
4912
4951
  static normalizeToPolyfill(zdt) {
4913
4952
  return normalizeZonedDateTime(zdt, "Date");
4914
4953
  }
4915
- static toInternalIterator(iterator) {
4916
- return iterator;
4954
+ toInternalIterator(iterator) {
4955
+ if (!iterator) return void 0;
4956
+ return (date, i) => iterator(this.toPublicDate(date), i);
4917
4957
  }
4918
- static toPublicDate(date) {
4919
- return date;
4958
+ toPublicDate(date) {
4959
+ if (!date) return null;
4960
+ const outputConstructor = this.outputTemporal?.ZonedDateTime;
4961
+ if (!outputConstructor || outputConstructor === Temporal.ZonedDateTime) return date;
4962
+ return outputConstructor.from(date.toString());
4920
4963
  }
4921
- static toPublicDates(dates) {
4922
- return dates;
4964
+ toPublicDates(dates) {
4965
+ if (!this.outputTemporal || this.outputTemporal.ZonedDateTime === Temporal.ZonedDateTime) return dates;
4966
+ return dates.map((date) => this.outputTemporal.ZonedDateTime.from(date.toString()));
4923
4967
  }
4924
4968
  constructor(params) {
4969
+ this.outputTemporal = params.temporal;
4925
4970
  let manual;
4926
4971
  if (isIcsOpts(params)) {
4927
4972
  const parsed = parseRRuleString(params.rruleString, params.tzid, params.dtstart, params.strict ?? false);
@@ -4940,6 +4985,7 @@ var RRuleTemporal = class RRuleTemporal {
4940
4985
  maxIterations: params.maxIterations,
4941
4986
  includeDtstart: params.includeDtstart,
4942
4987
  cache: params.cache,
4988
+ temporal: params.temporal,
4943
4989
  tzid: this.tzid
4944
4990
  };
4945
4991
  } else {
@@ -5441,7 +5487,15 @@ var RRuleTemporal = class RRuleTemporal {
5441
5487
  });
5442
5488
  }
5443
5489
  options() {
5444
- return this.cloneOptions();
5490
+ const { dtstart, until, rDate, exDate, temporal: _temporal, ...rest } = this.cloneOptions();
5491
+ return {
5492
+ ...rest,
5493
+ ...this.outputTemporal ? { temporal: this.outputTemporal } : {},
5494
+ dtstart: this.toPublicDate(dtstart),
5495
+ until: until ? this.toPublicDate(until) : void 0,
5496
+ rDate: rDate ? this.toPublicDates(rDate) : void 0,
5497
+ exDate: exDate ? this.toPublicDates(exDate) : void 0
5498
+ };
5445
5499
  }
5446
5500
  cloneOptions() {
5447
5501
  const { byHour, byMinute, bySecond, byDay, byMonth, byMonthDay, byYearDay, byWeekNo, bySetPos, rDate, exDate, ...rest } = this.opts;
@@ -5537,6 +5591,341 @@ var RRuleTemporal = class RRuleTemporal {
5537
5591
  for (const hour of hours) for (const minute of minutes) for (const second of seconds) offsets.push(((hour * 60 + minute) * 60 + second) * MS_PER_SECOND + baseMilliseconds);
5538
5592
  return offsets;
5539
5593
  }
5594
+ createNumericQueryPlan(kind, maximumCount, select, directLowerBound) {
5595
+ const first = select(0);
5596
+ const last = select(maximumCount - 1);
5597
+ if (!first || !last || !isSafeTemporalEpochMilliseconds(first.epochMilliseconds) || !isSafeTemporalEpochMilliseconds(last.epochMilliseconds) || first.epochMilliseconds > last.epochMilliseconds) return null;
5598
+ const findLowerBound = (targetEpochNanoseconds, strict, high) => {
5599
+ if (directLowerBound) return Math.max(0, Math.min(high, directLowerBound(targetEpochNanoseconds, strict)));
5600
+ let low = 0;
5601
+ let upper = high;
5602
+ while (low < upper) {
5603
+ const middle = low + Math.floor((upper - low) / 2);
5604
+ const candidate = select(middle);
5605
+ if (!candidate) {
5606
+ upper = middle;
5607
+ continue;
5608
+ }
5609
+ const candidateEpochNanoseconds = BigInt(candidate.epochMilliseconds) * NS_PER_MILLISECOND;
5610
+ if (strict ? candidateEpochNanoseconds > targetEpochNanoseconds : candidateEpochNanoseconds >= targetEpochNanoseconds) upper = middle;
5611
+ else low = middle + 1;
5612
+ }
5613
+ return low;
5614
+ };
5615
+ const untilEpochNanoseconds = this.opts.until?.epochNanoseconds;
5616
+ const count = untilEpochNanoseconds === void 0 ? maximumCount : findLowerBound(untilEpochNanoseconds, true, maximumCount);
5617
+ return {
5618
+ kind,
5619
+ count,
5620
+ maximumCount,
5621
+ select: (index) => {
5622
+ if (!Number.isSafeInteger(index) || index < 0 || index >= maximumCount) return null;
5623
+ return select(index);
5624
+ },
5625
+ lowerBound: (targetEpochNanoseconds, strict) => findLowerBound(targetEpochNanoseconds, strict, count)
5626
+ };
5627
+ }
5628
+ buildFixedStepNumericQueryPlan(maximumCount) {
5629
+ let unitMilliseconds;
5630
+ switch (this.opts.freq) {
5631
+ case "HOURLY":
5632
+ unitMilliseconds = MS_PER_HOUR;
5633
+ break;
5634
+ case "MINUTELY":
5635
+ unitMilliseconds = MS_PER_MINUTE;
5636
+ break;
5637
+ case "SECONDLY":
5638
+ unitMilliseconds = MS_PER_SECOND;
5639
+ break;
5640
+ default: return null;
5641
+ }
5642
+ if (![
5643
+ "UTC",
5644
+ "Etc/UTC",
5645
+ "Etc/GMT"
5646
+ ].includes(this.tzid) && !/^[-+]\d{2}:?\d{2}(?::?\d{2})?$/.test(this.tzid) && this.opts.freq === "HOURLY" && this.opts.interval === 1) return null;
5647
+ const startMilliseconds = this.originalDtstart.epochMilliseconds;
5648
+ const stepMilliseconds = unitMilliseconds * this.opts.interval;
5649
+ if (!Number.isSafeInteger(stepMilliseconds) || stepMilliseconds <= 0) return null;
5650
+ const select = (index) => {
5651
+ const epochMilliseconds = startMilliseconds + index * stepMilliseconds;
5652
+ if (!isSafeTemporalEpochMilliseconds(epochMilliseconds)) return null;
5653
+ return {
5654
+ epochMilliseconds,
5655
+ periodIndex: index,
5656
+ occurrenceIndex: index
5657
+ };
5658
+ };
5659
+ const startEpochNanoseconds = BigInt(startMilliseconds) * NS_PER_MILLISECOND;
5660
+ const stepEpochNanoseconds = BigInt(stepMilliseconds) * NS_PER_MILLISECOND;
5661
+ const countAsBigInt = BigInt(maximumCount);
5662
+ const directLowerBound = (targetEpochNanoseconds, strict) => {
5663
+ const delta = targetEpochNanoseconds - startEpochNanoseconds;
5664
+ const rawIndex = strict ? floorDivBigInt(delta, stepEpochNanoseconds) + 1n : ceilDivBigInt(delta, stepEpochNanoseconds);
5665
+ if (rawIndex <= 0n) return 0;
5666
+ if (rawIndex >= countAsBigInt) return maximumCount;
5667
+ return Number(rawIndex);
5668
+ };
5669
+ return this.createNumericQueryPlan("fixed-step", maximumCount, select, directLowerBound);
5670
+ }
5671
+ resolveNumericWallMilliseconds(wallMilliseconds) {
5672
+ if (!isSafeTemporalEpochMilliseconds(wallMilliseconds)) return null;
5673
+ if (this.tzid === "UTC") return wallMilliseconds;
5674
+ const resolution = this.getZoneResolver().epochMsForWall(wallMilliseconds);
5675
+ if (resolution.pushed || !isSafeTemporalEpochMilliseconds(resolution.epochMs)) return null;
5676
+ return resolution.epochMs;
5677
+ }
5678
+ numericQueryGapHazard(timeOfDayMilliseconds, lastEpochMilliseconds) {
5679
+ if (this.tzid === "UTC") return false;
5680
+ const startEpochMilliseconds = this.originalDtstart.epochMilliseconds;
5681
+ const MAX_SPAN_MS = 200 * 366 * MS_PER_DAY;
5682
+ if (lastEpochMilliseconds - startEpochMilliseconds > MAX_SPAN_MS) return true;
5683
+ return this.getZoneResolver().timeOfDayMayHitGap(timeOfDayMilliseconds, startEpochMilliseconds - MS_PER_DAY, lastEpochMilliseconds + MS_PER_DAY);
5684
+ }
5685
+ buildDailyNumericQueryPlan(maximumCount) {
5686
+ const interval = this.opts.interval;
5687
+ const startEpochMilliseconds = this.originalDtstart.epochMilliseconds;
5688
+ const startWallMilliseconds = this.tzid === "UTC" ? startEpochMilliseconds : this.wallMsOf(this.originalDtstart);
5689
+ const startEpochDay = Math.floor(startWallMilliseconds / MS_PER_DAY);
5690
+ const startDayOfWeek = isoDayOfWeekOfEpochDay(startEpochDay);
5691
+ const allowedDayMask = weekdayMask(this.simpleByDayIsoDays);
5692
+ if (!Boolean(this.opts.byHour || this.opts.byMinute || this.opts.bySecond)) {
5693
+ const timeOfDayMilliseconds = startWallMilliseconds - startEpochDay * MS_PER_DAY;
5694
+ const firstMatchingStep = this.simpleByDayIsoDays?.length ? this.findFirstMatchingDailyStep(startDayOfWeek, interval, this.simpleByDayIsoDays) : 0;
5695
+ if (firstMatchingStep === null) return null;
5696
+ const cyclePeriods = 7 / gcd(interval, 7);
5697
+ const matchingPeriodOffsets = [];
5698
+ for (let offset = 0; offset < cyclePeriods; offset++) if (includesIsoWeekday(allowedDayMask, addIsoDays(startDayOfWeek, (firstMatchingStep + offset) * interval))) matchingPeriodOffsets.push(offset);
5699
+ if (matchingPeriodOffsets.length === 0) return null;
5700
+ const select = (index) => {
5701
+ const cycleIndex = Math.floor(index / matchingPeriodOffsets.length);
5702
+ const offsetIndex = index % matchingPeriodOffsets.length;
5703
+ const periodIndex = cycleIndex * cyclePeriods + matchingPeriodOffsets[offsetIndex];
5704
+ const dayDelta = (firstMatchingStep + periodIndex) * interval;
5705
+ if (!Number.isSafeInteger(periodIndex) || !Number.isSafeInteger(dayDelta)) return null;
5706
+ const wallMilliseconds = startWallMilliseconds + dayDelta * MS_PER_DAY;
5707
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5708
+ if (epochMilliseconds === null) return null;
5709
+ return {
5710
+ epochMilliseconds,
5711
+ periodIndex,
5712
+ occurrenceIndex: index
5713
+ };
5714
+ };
5715
+ const plan = this.createNumericQueryPlan("daily", maximumCount, select);
5716
+ const last = plan?.select(maximumCount - 1);
5717
+ if (last && this.numericQueryGapHazard(timeOfDayMilliseconds, last.epochMilliseconds)) return null;
5718
+ return plan;
5719
+ }
5720
+ const timeSlotOffsets = this.timeSlotOffsetsMs;
5721
+ if (!timeSlotOffsets?.length || !this.hasUniqueTimeSlotOffsets) return null;
5722
+ const firstDayOffset = this.simpleByDayIsoDays?.length ? this.findFirstMatchingDailyStep(startDayOfWeek, 1, this.simpleByDayIsoDays) : 0;
5723
+ if (firstDayOffset === null) return null;
5724
+ const firstEpochDay = startEpochDay + firstDayOffset;
5725
+ const firstDayOfWeek = addIsoDays(startDayOfWeek, firstDayOffset);
5726
+ const cyclePeriods = 7 / gcd(interval, 7);
5727
+ const firstCandidates = [];
5728
+ if (includesIsoWeekday(allowedDayMask, firstDayOfWeek)) for (const timeSlotOffset of timeSlotOffsets) {
5729
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(firstEpochDay * MS_PER_DAY + timeSlotOffset);
5730
+ if (epochMilliseconds === null) return null;
5731
+ if (epochMilliseconds >= startEpochMilliseconds) firstCandidates.push({
5732
+ epochMilliseconds,
5733
+ periodIndex: 0,
5734
+ occurrenceIndex: firstCandidates.length
5735
+ });
5736
+ }
5737
+ const cycleSlots = [];
5738
+ for (let periodOffset = 0; periodOffset < cyclePeriods; periodOffset++) {
5739
+ if (!includesIsoWeekday(allowedDayMask, addIsoDays(firstDayOfWeek, (1 + periodOffset) * interval))) continue;
5740
+ for (const timeSlotOffset of timeSlotOffsets) cycleSlots.push({
5741
+ periodOffset,
5742
+ timeSlotOffset
5743
+ });
5744
+ }
5745
+ if (firstCandidates.length === 0 && cycleSlots.length === 0) return null;
5746
+ const select = (index) => {
5747
+ if (index < firstCandidates.length) return {
5748
+ ...firstCandidates[index],
5749
+ occurrenceIndex: index
5750
+ };
5751
+ if (cycleSlots.length === 0) return null;
5752
+ const remainingIndex = index - firstCandidates.length;
5753
+ const cycleIndex = Math.floor(remainingIndex / cycleSlots.length);
5754
+ const slot = cycleSlots[remainingIndex % cycleSlots.length];
5755
+ const periodIndex = 1 + cycleIndex * cyclePeriods + slot.periodOffset;
5756
+ const dayDelta = firstDayOffset + periodIndex * interval;
5757
+ if (!Number.isSafeInteger(periodIndex) || !Number.isSafeInteger(dayDelta)) return null;
5758
+ const wallMilliseconds = (startEpochDay + dayDelta) * MS_PER_DAY + slot.timeSlotOffset;
5759
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5760
+ if (epochMilliseconds === null) return null;
5761
+ return {
5762
+ epochMilliseconds,
5763
+ periodIndex,
5764
+ occurrenceIndex: index
5765
+ };
5766
+ };
5767
+ const plan = this.createNumericQueryPlan("daily", maximumCount, select);
5768
+ const last = plan?.select(maximumCount - 1);
5769
+ if (last && timeSlotOffsets.some((offset) => this.numericQueryGapHazard(offset, last.epochMilliseconds))) return null;
5770
+ return plan;
5771
+ }
5772
+ buildWeeklyNumericQueryPlan(maximumCount) {
5773
+ const timeSlotOffsets = this.timeSlotOffsetsMs;
5774
+ if (!timeSlotOffsets?.length || !this.hasUniqueTimeSlotOffsets) return null;
5775
+ const startEpochMilliseconds = this.originalDtstart.epochMilliseconds;
5776
+ const startWallMilliseconds = this.tzid === "UTC" ? startEpochMilliseconds : this.wallMsOf(this.originalDtstart);
5777
+ const startEpochDay = Math.floor(startWallMilliseconds / MS_PER_DAY);
5778
+ const startDayOfWeek = isoDayOfWeekOfEpochDay(startEpochDay);
5779
+ const wkstDay = weekdayToIsoDay[extractWeekdayToken(this.opts.wkst || "MO") ?? "MO"] ?? 1;
5780
+ const dayOffsets = (this.opts.byDay ? [...this.allByDayIsoDays ?? []] : [startDayOfWeek]).map((day) => (day - wkstDay + 7) % 7).sort((a, b) => a - b);
5781
+ if (dayOffsets.length === 0) return null;
5782
+ const firstWeekStartDay = startEpochDay - (startDayOfWeek - wkstDay + 7) % 7;
5783
+ const weeklySlots = dayOffsets.flatMap((dayOffset) => timeSlotOffsets.map((timeSlotOffset) => ({
5784
+ dayOffset,
5785
+ timeSlotOffset
5786
+ })));
5787
+ const firstCandidates = [];
5788
+ for (const slot of weeklySlots) {
5789
+ const wallMilliseconds = (firstWeekStartDay + slot.dayOffset) * MS_PER_DAY + slot.timeSlotOffset;
5790
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5791
+ if (epochMilliseconds === null) return null;
5792
+ if (epochMilliseconds >= startEpochMilliseconds) firstCandidates.push({
5793
+ epochMilliseconds,
5794
+ periodIndex: 0,
5795
+ occurrenceIndex: firstCandidates.length
5796
+ });
5797
+ }
5798
+ const select = (index) => {
5799
+ if (index < firstCandidates.length) return {
5800
+ ...firstCandidates[index],
5801
+ occurrenceIndex: index
5802
+ };
5803
+ const remainingIndex = index - firstCandidates.length;
5804
+ const periodIndex = 1 + Math.floor(remainingIndex / weeklySlots.length);
5805
+ const slot = weeklySlots[remainingIndex % weeklySlots.length];
5806
+ const weekDelta = periodIndex * this.opts.interval * 7;
5807
+ if (!Number.isSafeInteger(periodIndex) || !Number.isSafeInteger(weekDelta)) return null;
5808
+ const wallMilliseconds = (firstWeekStartDay + weekDelta + slot.dayOffset) * MS_PER_DAY + slot.timeSlotOffset;
5809
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5810
+ if (epochMilliseconds === null) return null;
5811
+ return {
5812
+ epochMilliseconds,
5813
+ periodIndex,
5814
+ occurrenceIndex: index
5815
+ };
5816
+ };
5817
+ const plan = this.createNumericQueryPlan("weekly", maximumCount, select);
5818
+ const last = plan?.select(maximumCount - 1);
5819
+ if (last && timeSlotOffsets.some((offset) => this.numericQueryGapHazard(offset, last.epochMilliseconds))) return null;
5820
+ return plan;
5821
+ }
5822
+ buildMonthlyNumericQueryPlan(maximumCount) {
5823
+ const interval = this.opts.interval;
5824
+ const timeSlotOffsets = this.timeSlotOffsetsMs;
5825
+ if (!timeSlotOffsets?.length || !this.hasUniqueTimeSlotOffsets) return null;
5826
+ if (this.opts.byMonth?.some((value) => typeof value !== "number")) return null;
5827
+ if (this.opts.bySetPos && new Set(this.opts.bySetPos).size !== this.opts.bySetPos.length) return null;
5828
+ const startEpochMilliseconds = this.originalDtstart.epochMilliseconds;
5829
+ const startMonthIndex = this.originalDtstart.year * 12 + (this.originalDtstart.month - 1);
5830
+ const wallsForPeriod = (periodIndex) => {
5831
+ const monthDelta = periodIndex * interval;
5832
+ const monthIndex = startMonthIndex + monthDelta;
5833
+ if (!Number.isSafeInteger(monthDelta) || !Number.isSafeInteger(monthIndex)) return null;
5834
+ const { year, month } = this.monthIndexToYearMonth(monthIndex);
5835
+ return this.generateMonthlyOccurrenceEpochsUtc(year, month);
5836
+ };
5837
+ const firstWalls = wallsForPeriod(0);
5838
+ if (!firstWalls) return null;
5839
+ const firstCandidates = [];
5840
+ for (const wallMilliseconds of firstWalls) {
5841
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5842
+ if (epochMilliseconds === null) return null;
5843
+ if (epochMilliseconds >= startEpochMilliseconds) firstCandidates.push({
5844
+ epochMilliseconds,
5845
+ periodIndex: 0,
5846
+ occurrenceIndex: firstCandidates.length
5847
+ });
5848
+ }
5849
+ const cyclePeriods = 4800 / gcd(interval, 4800);
5850
+ const requiredCycleOccurrences = Math.max(0, maximumCount - firstCandidates.length);
5851
+ const cyclePrefixCounts = [0];
5852
+ for (let periodOffset = 0; periodOffset < cyclePeriods && cyclePrefixCounts.at(-1) < requiredCycleOccurrences; periodOffset++) {
5853
+ const walls = wallsForPeriod(1 + periodOffset);
5854
+ if (!walls) return null;
5855
+ cyclePrefixCounts.push(cyclePrefixCounts[periodOffset] + walls.length);
5856
+ }
5857
+ const completedCycle = cyclePrefixCounts.length - 1 === cyclePeriods;
5858
+ const occurrencesPerPrecomputedSpan = cyclePrefixCounts.at(-1);
5859
+ if (occurrencesPerPrecomputedSpan === 0 && firstCandidates.length < maximumCount) return null;
5860
+ const select = (index) => {
5861
+ if (index < firstCandidates.length) return {
5862
+ ...firstCandidates[index],
5863
+ occurrenceIndex: index
5864
+ };
5865
+ if (occurrencesPerPrecomputedSpan === 0) return null;
5866
+ const remainingIndex = index - firstCandidates.length;
5867
+ const cycleIndex = completedCycle ? Math.floor(remainingIndex / occurrencesPerPrecomputedSpan) : 0;
5868
+ const indexWithinCycle = completedCycle ? remainingIndex % occurrencesPerPrecomputedSpan : remainingIndex;
5869
+ if (indexWithinCycle >= occurrencesPerPrecomputedSpan) return null;
5870
+ let low = 1;
5871
+ let high = cyclePrefixCounts.length - 1;
5872
+ while (low < high) {
5873
+ const middle = low + Math.floor((high - low) / 2);
5874
+ if (cyclePrefixCounts[middle] > indexWithinCycle) high = middle;
5875
+ else low = middle + 1;
5876
+ }
5877
+ const periodOffset = low - 1;
5878
+ const periodIndex = 1 + cycleIndex * cyclePeriods + periodOffset;
5879
+ if (!Number.isSafeInteger(periodIndex)) return null;
5880
+ const walls = wallsForPeriod(periodIndex);
5881
+ if (!walls) return null;
5882
+ const wallMilliseconds = walls[indexWithinCycle - cyclePrefixCounts[periodOffset]];
5883
+ if (wallMilliseconds === void 0) return null;
5884
+ const epochMilliseconds = this.resolveNumericWallMilliseconds(wallMilliseconds);
5885
+ if (epochMilliseconds === null) return null;
5886
+ return {
5887
+ epochMilliseconds,
5888
+ periodIndex,
5889
+ occurrenceIndex: index
5890
+ };
5891
+ };
5892
+ const plan = this.createNumericQueryPlan("monthly", maximumCount, select);
5893
+ const last = plan?.select(maximumCount - 1);
5894
+ if (last && timeSlotOffsets.some((offset) => this.numericQueryGapHazard(offset, last.epochMilliseconds))) return null;
5895
+ return plan;
5896
+ }
5897
+ buildNumericQueryPlan() {
5898
+ const maximumCount = this.opts.count;
5899
+ const interval = this.opts.interval;
5900
+ if (maximumCount === void 0 || !Number.isSafeInteger(maximumCount) || maximumCount <= 0 || !Number.isSafeInteger(interval) || interval <= 0 || !Number.isSafeInteger(this.maxIterations) || this.maxIterations <= 0 || this.includeDtstart || this.opts.rscale !== void 0 || this.opts.rDate !== void 0 || this.opts.exDate !== void 0 || !this.canUseEpochMillisecondsPrecisionFlag || this.originalDtstart.timeZoneId !== this.tzid || !["iso8601", "gregory"].includes(this.originalDtstart.calendarId)) return null;
5901
+ const hasCalendarFilters = Boolean(this.opts.byMonth || this.opts.byMonthDay || this.opts.byYearDay || this.opts.byWeekNo || this.opts.bySetPos);
5902
+ switch (this.opts.freq) {
5903
+ case "HOURLY":
5904
+ case "MINUTELY":
5905
+ case "SECONDLY":
5906
+ if (hasCalendarFilters || this.opts.byDay || this.opts.byHour || this.opts.byMinute || this.opts.bySecond) return null;
5907
+ return this.buildFixedStepNumericQueryPlan(maximumCount);
5908
+ case "DAILY":
5909
+ if (hasCalendarFilters || this.hasOrdinalByDay || !this.hasUniqueTimeSlotOffsets) return null;
5910
+ return this.buildDailyNumericQueryPlan(maximumCount);
5911
+ case "WEEKLY":
5912
+ if (hasCalendarFilters || this.hasOrdinalByDay || !this.hasUniqueTimeSlotOffsets) return null;
5913
+ return this.buildWeeklyNumericQueryPlan(maximumCount);
5914
+ case "MONTHLY":
5915
+ if (this.opts.byYearDay || this.opts.byWeekNo || !(this.opts.byDay || this.opts.byMonthDay) || !this.hasUniqueTimeSlotOffsets) return null;
5916
+ return this.buildMonthlyNumericQueryPlan(maximumCount);
5917
+ default: return null;
5918
+ }
5919
+ }
5920
+ getNumericQueryPlan() {
5921
+ if (this.numericQueryPlanCache !== void 0) return this.numericQueryPlanCache;
5922
+ try {
5923
+ this.numericQueryPlanCache = this.buildNumericQueryPlan();
5924
+ } catch {
5925
+ this.numericQueryPlanCache = null;
5926
+ }
5927
+ return this.numericQueryPlanCache;
5928
+ }
5540
5929
  findFirstMatchingDailyStep(startDayOfWeek, stepDays, allowedDays) {
5541
5930
  let dayOfWeek = startDayOfWeek;
5542
5931
  for (let steps = 0; steps < 7; steps++) {
@@ -5816,7 +6205,7 @@ var RRuleTemporal = class RRuleTemporal {
5816
6205
  gregorianIsoDayOfWeek(year, month, day) {
5817
6206
  let adjustedYear = year;
5818
6207
  if (month < 3) adjustedYear -= 1;
5819
- const sundayZero = (adjustedYear + Math.floor(adjustedYear / 4) - Math.floor(adjustedYear / 100) + Math.floor(adjustedYear / 400) + GREGORIAN_WEEKDAY_OFFSETS[month - 1] + day) % 7;
6208
+ const sundayZero = ((adjustedYear + Math.floor(adjustedYear / 4) - Math.floor(adjustedYear / 100) + Math.floor(adjustedYear / 400) + GREGORIAN_WEEKDAY_OFFSETS[month - 1] + day) % 7 + 7) % 7;
5820
6209
  return sundayZero === 0 ? 7 : sundayZero;
5821
6210
  }
5822
6211
  monthIndexToYearMonth(monthIndex) {
@@ -5869,7 +6258,8 @@ var RRuleTemporal = class RRuleTemporal {
5869
6258
  generateMonthlyOccurrenceEpochsUtc(year, month) {
5870
6259
  const days = this.generateMonthlyOccurrenceDaysUtc(year, month);
5871
6260
  if (days.length === 0) return [];
5872
- const monthStartMs = Date.UTC(year, month - 1, 1, 0, 0, 0, 0);
6261
+ const monthStartMs = gregorianEpochDay(year, month, 1) * MS_PER_DAY;
6262
+ if (!isSafeTemporalEpochMilliseconds(monthStartMs)) return [];
5873
6263
  const timeSlotOffsets = this.timeSlotOffsetsMs ?? [0];
5874
6264
  if (this.opts.bySetPos && this.opts.bySetPos.length > 0) {
5875
6265
  if (timeSlotOffsets.length === 1) {
@@ -6499,9 +6889,9 @@ var RRuleTemporal = class RRuleTemporal {
6499
6889
  all(iterator) {
6500
6890
  if (!iterator && this.opts.cache !== false) {
6501
6891
  if (!this.allResultCache) this.allResultCache = this.allInternal();
6502
- return RRuleTemporal.toPublicDates(this.allResultCache.slice());
6892
+ return this.toPublicDates(this.allResultCache.slice());
6503
6893
  }
6504
- return RRuleTemporal.toPublicDates(this.allInternal(RRuleTemporal.toInternalIterator(iterator)));
6894
+ return this.toPublicDates(this.allInternal(this.toInternalIterator(iterator)));
6505
6895
  }
6506
6896
  allInternal(iterator) {
6507
6897
  if (this.opts.rscale && [
@@ -6731,6 +7121,74 @@ var RRuleTemporal = class RRuleTemporal {
6731
7121
  }
6732
7122
  return false;
6733
7123
  }
7124
+ assertNumericCandidateReachable(candidate) {
7125
+ if (candidate && candidate.periodIndex >= this.maxIterations) throw new Error(`Maximum iterations (${this.maxIterations}) exceeded in all()`);
7126
+ }
7127
+ numericExhaustionCandidate(plan) {
7128
+ if (plan.count < plan.maximumCount) return plan.select(plan.count);
7129
+ return plan.count > 0 ? plan.select(plan.count - 1) : null;
7130
+ }
7131
+ tryNumericNext(targetEpochNanoseconds, inclusive) {
7132
+ const plan = this.getNumericQueryPlan();
7133
+ if (!plan) return { handled: false };
7134
+ const index = plan.lowerBound(targetEpochNanoseconds, !inclusive);
7135
+ if (index >= plan.count) {
7136
+ this.assertNumericCandidateReachable(this.numericExhaustionCandidate(plan));
7137
+ return {
7138
+ handled: true,
7139
+ value: null
7140
+ };
7141
+ }
7142
+ const candidate = plan.select(index);
7143
+ if (!candidate) return { handled: false };
7144
+ this.assertNumericCandidateReachable(candidate);
7145
+ return {
7146
+ handled: true,
7147
+ value: this.zdtFromEpochMs(candidate.epochMilliseconds)
7148
+ };
7149
+ }
7150
+ tryNumericPrevious(targetEpochNanoseconds, inclusive) {
7151
+ const plan = this.getNumericQueryPlan();
7152
+ if (!plan) return { handled: false };
7153
+ const stopIndex = plan.lowerBound(targetEpochNanoseconds, inclusive);
7154
+ const reachedCandidate = stopIndex < plan.count ? plan.select(stopIndex) : this.numericExhaustionCandidate(plan);
7155
+ this.assertNumericCandidateReachable(reachedCandidate);
7156
+ const resultIndex = stopIndex - 1;
7157
+ if (resultIndex < 0) return {
7158
+ handled: true,
7159
+ value: null
7160
+ };
7161
+ const candidate = plan.select(resultIndex);
7162
+ if (!candidate) return { handled: false };
7163
+ return {
7164
+ handled: true,
7165
+ value: this.zdtFromEpochMs(candidate.epochMilliseconds)
7166
+ };
7167
+ }
7168
+ tryNumericBetween(startEpochNanoseconds, endEpochNanoseconds, inclusive) {
7169
+ if (startEpochNanoseconds > endEpochNanoseconds) return { handled: false };
7170
+ const plan = this.getNumericQueryPlan();
7171
+ if (!plan) return { handled: false };
7172
+ const firstIndex = plan.lowerBound(startEpochNanoseconds, !inclusive);
7173
+ const endIndex = plan.lowerBound(endEpochNanoseconds, inclusive);
7174
+ const scanStopIndex = plan.lowerBound(endEpochNanoseconds, true);
7175
+ const reachedCandidate = scanStopIndex < plan.count ? plan.select(scanStopIndex) : this.numericExhaustionCandidate(plan);
7176
+ this.assertNumericCandidateReachable(reachedCandidate);
7177
+ if (firstIndex >= endIndex) return {
7178
+ handled: true,
7179
+ value: []
7180
+ };
7181
+ const dates = new Array(endIndex - firstIndex);
7182
+ for (let index = firstIndex; index < endIndex; index++) {
7183
+ const candidate = plan.select(index);
7184
+ if (!candidate) return { handled: false };
7185
+ dates[index - firstIndex] = this.zdtFromEpochMs(candidate.epochMilliseconds);
7186
+ }
7187
+ return {
7188
+ handled: true,
7189
+ value: dates
7190
+ };
7191
+ }
6734
7192
  /**
6735
7193
  * Returns all occurrences of the rule within a specified time window.
6736
7194
  * @param after - The start date or Temporal.ZonedDateTime object.
@@ -6741,13 +7199,18 @@ var RRuleTemporal = class RRuleTemporal {
6741
7199
  between(after, before, inc = false) {
6742
7200
  const startInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : normalizeZonedDateTime(after, "after").toInstant();
6743
7201
  const endInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : normalizeZonedDateTime(before, "before").toInstant();
7202
+ const numericResult = this.tryNumericBetween(startInst.epochNanoseconds, endInst.epochNanoseconds, inc);
7203
+ if (numericResult.handled) return this.toPublicDates(numericResult.value);
6744
7204
  const startZdt = Temporal.Instant.from(startInst).toZonedDateTimeISO(this.tzid);
6745
7205
  const beforeZdt = Temporal.Instant.from(endInst).toZonedDateTimeISO(this.tzid);
6746
7206
  const tempOpts = { ...this.opts };
6747
7207
  if (!tempOpts.until || Temporal.ZonedDateTime.compare(beforeZdt, tempOpts.until) < 0) tempOpts.until = beforeZdt;
6748
7208
  if (tempOpts.count === void 0) tempOpts.dtstart = this.jumpAlignedDtstart(startZdt);
6749
- const allDates = new RRuleTemporal(tempOpts).allInternal();
6750
- return RRuleTemporal.toPublicDates(allDates.filter((date) => {
7209
+ const allDates = new RRuleTemporal({
7210
+ ...tempOpts,
7211
+ temporal: this.outputTemporal
7212
+ }).allInternal();
7213
+ return this.toPublicDates(allDates.filter((date) => {
6751
7214
  const inst = date.toInstant();
6752
7215
  const afterStart = inc ? Temporal.Instant.compare(inst, startInst) >= 0 : Temporal.Instant.compare(inst, startInst) > 0;
6753
7216
  const beforeEnd = inc ? Temporal.Instant.compare(inst, endInst) <= 0 : Temporal.Instant.compare(inst, endInst) < 0;
@@ -6852,6 +7315,8 @@ var RRuleTemporal = class RRuleTemporal {
6852
7315
  */
6853
7316
  next(after = /* @__PURE__ */ new Date(), inc = false) {
6854
7317
  const afterInst = after instanceof Date ? Temporal.Instant.from(after.toISOString()) : normalizeZonedDateTime(after, "after").toInstant();
7318
+ const numericResult = this.tryNumericNext(afterInst.epochNanoseconds, inc);
7319
+ if (numericResult.handled) return this.toPublicDate(numericResult.value);
6855
7320
  let result = null;
6856
7321
  const scanFrom = (rule) => {
6857
7322
  rule.allInternal((occ) => {
@@ -6865,7 +7330,7 @@ var RRuleTemporal = class RRuleTemporal {
6865
7330
  };
6866
7331
  if (this.opts.count !== void 0) scanFrom(this);
6867
7332
  else scanFrom(this.ruleFromAlignedDtstart(afterInst.toZonedDateTimeISO(this.tzid)));
6868
- return RRuleTemporal.toPublicDate(result);
7333
+ return this.toPublicDate(result);
6869
7334
  }
6870
7335
  /**
6871
7336
  * Build a temporary rule identical to this one but starting at the
@@ -6877,6 +7342,7 @@ var RRuleTemporal = class RRuleTemporal {
6877
7342
  if (aligned.epochNanoseconds === this.originalDtstart.epochNanoseconds) return this;
6878
7343
  return new RRuleTemporal({
6879
7344
  ...this.opts,
7345
+ temporal: this.outputTemporal,
6880
7346
  dtstart: aligned,
6881
7347
  includeDtstart: false
6882
7348
  });
@@ -6889,6 +7355,8 @@ var RRuleTemporal = class RRuleTemporal {
6889
7355
  */
6890
7356
  previous(before = /* @__PURE__ */ new Date(), inc = false) {
6891
7357
  const beforeInst = before instanceof Date ? Temporal.Instant.from(before.toISOString()) : normalizeZonedDateTime(before, "before").toInstant();
7358
+ const numericResult = this.tryNumericPrevious(beforeInst.epochNanoseconds, inc);
7359
+ if (numericResult.handled) return this.toPublicDate(numericResult.value);
6892
7360
  const scanFrom = (rule) => {
6893
7361
  let prev = null;
6894
7362
  rule.allInternal((occ) => {
@@ -6899,7 +7367,7 @@ var RRuleTemporal = class RRuleTemporal {
6899
7367
  });
6900
7368
  return prev;
6901
7369
  };
6902
- if (this.opts.count !== void 0) return RRuleTemporal.toPublicDate(scanFrom(this));
7370
+ if (this.opts.count !== void 0) return this.toPublicDate(scanFrom(this));
6903
7371
  const beforeZdt = beforeInst.toZonedDateTimeISO(this.tzid);
6904
7372
  const anchor = this.opts.until && Temporal.ZonedDateTime.compare(this.opts.until, beforeZdt) < 0 ? this.opts.until : beforeZdt;
6905
7373
  const interval = this.opts.interval ?? 1;
@@ -6907,9 +7375,9 @@ var RRuleTemporal = class RRuleTemporal {
6907
7375
  const target = backoff === 0 ? anchor : anchor.subtract(this.freqDuration(interval * 4 ** backoff));
6908
7376
  const rule = this.ruleFromAlignedDtstart(target);
6909
7377
  const prev = scanFrom(rule);
6910
- if (prev || rule === this) return RRuleTemporal.toPublicDate(prev);
7378
+ if (prev || rule === this) return this.toPublicDate(prev);
6911
7379
  }
6912
- return RRuleTemporal.toPublicDate(scanFrom(this));
7380
+ return this.toPublicDate(scanFrom(this));
6913
7381
  }
6914
7382
  /** A duration of `count` steps in this rule's frequency unit. */
6915
7383
  freqDuration(count) {