@final-commerce/common 2.11.1-staging2.1 → 2.12.0-staging.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -31,10 +31,12 @@ __export(index_exports, {
31
31
  AttributeType: () => AttributeType,
32
32
  BNPL_METHOD_STATUS: () => BNPL_METHOD_STATUS,
33
33
  BNPL_SKIP_REASON: () => BNPL_SKIP_REASON,
34
+ BookingDurationUnit: () => BookingDurationUnit,
34
35
  BookingRatePeriod: () => BookingRatePeriod,
35
36
  BookingResourceKind: () => BookingResourceKind,
36
37
  BookingResourceStatus: () => BookingResourceStatus,
37
38
  BookingRulesError: () => BookingRulesError,
39
+ BookingSessionSale: () => BookingSessionSale,
38
40
  BookingType: () => BookingType,
39
41
  CANADA_PROVINCES: () => CANADA_PROVINCES,
40
42
  CONDITION_OPERATORS: () => CONDITION_OPERATORS,
@@ -124,6 +126,7 @@ __export(index_exports, {
124
126
  StripeStatus: () => StripeStatus,
125
127
  TimePeriod: () => TimePeriod,
126
128
  TopMetericsSort: () => TopMetericsSort,
129
+ UNLIMITED_PLACES: () => UNLIMITED_PLACES,
127
130
  UserTypes: () => UserTypes,
128
131
  addAmounts: () => addAmounts,
129
132
  addressPlaceKeys: () => addressPlaceKeys,
@@ -132,6 +135,7 @@ __export(index_exports, {
132
135
  adyenStoreRequiresStateOrProvince: () => adyenStoreRequiresStateOrProvince,
133
136
  adyenSupportsTaxNumberAbsent: () => adyenSupportsTaxNumberAbsent,
134
137
  adyenTaxNumberFormat: () => adyenTaxNumberFormat,
138
+ allowedDurationUnits: () => allowedDurationUnits,
135
139
  amountToString: () => amountToString,
136
140
  ancestorChain: () => ancestorChain,
137
141
  applyAssignment: () => applyAssignment,
@@ -141,15 +145,21 @@ __export(index_exports, {
141
145
  baseFulfillmentDefinitions: () => baseFulfillmentDefinitions,
142
146
  baseOf: () => baseOf,
143
147
  basePaymentDefinitions: () => basePaymentDefinitions,
148
+ bookingMethodOf: () => bookingMethodOf,
149
+ bookingRuleParts: () => bookingRuleParts,
144
150
  buildAvailability: () => buildAvailability,
145
151
  buildGrid: () => buildGrid,
146
152
  buildOrderContext: () => buildOrderContext,
147
153
  buildPosPresetConfig: () => buildPosPresetConfig,
148
154
  buildResolvedConfig: () => buildResolvedConfig,
149
155
  calculatePercentage: () => calculatePercentage,
156
+ calendarDate: () => calendarDate,
150
157
  canTransition: () => canTransition,
158
+ capacityOf: () => capacityOf,
151
159
  cheapestCompositeItem: () => cheapestCompositeItem,
152
160
  cheapestCompositePrice: () => cheapestCompositePrice,
161
+ checkPartySize: () => checkPartySize,
162
+ checkQtyPerBooking: () => checkQtyPerBooking,
153
163
  compositeItemCost: () => compositeItemCost,
154
164
  compositeItemUnavailable: () => compositeItemUnavailable,
155
165
  compositeMakeable: () => compositeMakeable,
@@ -158,6 +168,9 @@ __export(index_exports, {
158
168
  compositeVariantInStock: () => compositeVariantInStock,
159
169
  conditionSummary: () => conditionSummary,
160
170
  convertFixedFeeToLocalCurrency: () => convertFixedFeeToLocalCurrency,
171
+ courseSessions: () => courseSessions,
172
+ courseStarted: () => courseStarted,
173
+ courseStartedInZone: () => courseStartedInZone,
161
174
  createAmount: () => createAmount,
162
175
  crossAxisRuleApplies: () => crossAxisRuleApplies,
163
176
  currentAssignees: () => currentAssignees,
@@ -166,10 +179,13 @@ __export(index_exports, {
166
179
  deriveUnitId: () => deriveUnitId,
167
180
  displayRuleMatchesPair: () => displayRuleMatchesPair,
168
181
  divideAmount: () => divideAmount,
182
+ durationProblems: () => durationProblems,
183
+ durationText: () => durationText,
169
184
  evaluateCondition: () => evaluateCondition,
170
185
  evaluateConditionSet: () => evaluateConditionSet,
171
186
  extendPrice: () => extendPrice,
172
187
  extendPriceFor: () => extendPriceFor,
188
+ fewestFreeOver: () => fewestFreeOver,
173
189
  formatCurrency: () => formatCurrency,
174
190
  formatInUnit: () => formatInUnit,
175
191
  formatMinorUnitsToString: () => formatMinorUnitsToString,
@@ -211,7 +227,9 @@ __export(index_exports, {
211
227
  listCountries: () => listCountries,
212
228
  listProvinces: () => listProvinces,
213
229
  listShippingCountries: () => listShippingCountries,
230
+ longestMinutesOf: () => longestMinutesOf,
214
231
  mapToLegacyStatus: () => mapToLegacyStatus,
232
+ maxAdvanceMinutesOf: () => maxAdvanceMinutesOf,
215
233
  maxPrecisionFor: () => maxPrecisionFor,
216
234
  mergeFragment: () => mergeFragment,
217
235
  modifiersSellable: () => modifiersSellable,
@@ -223,11 +241,14 @@ __export(index_exports, {
223
241
  normalizePostCode: () => normalizePostCode,
224
242
  normalizeProvince: () => normalizeProvince,
225
243
  occupancyIn: () => occupancyIn,
244
+ oldMaxAdvanceOf: () => oldMaxAdvanceOf,
226
245
  orderAssignments: () => orderAssignments,
227
246
  parseAmountToMinorUnits: () => parseAmountToMinorUnits,
228
247
  parseCurrencyCode: () => parseCurrencyCode,
229
248
  parseStripeCurrencyCode: () => parseStripeCurrencyCode,
249
+ pickFreeResource: () => pickFreeResource,
230
250
  placeKey: () => placeKey,
251
+ planCourse: () => planCourse,
231
252
  planWindow: () => planWindow,
232
253
  poolDemand: () => poolDemand,
233
254
  poolOf: () => poolOf,
@@ -244,13 +265,18 @@ __export(index_exports, {
244
265
  resolveTemplate: () => resolveTemplate,
245
266
  resolveUnit: () => resolveUnit,
246
267
  roundToPrecision: () => roundToPrecision,
268
+ ruleDurationsOf: () => ruleDurationsOf,
269
+ ruleInNewShape: () => ruleInNewShape,
247
270
  sameFamily: () => sameFamily,
271
+ sessionCells: () => sessionCells,
248
272
  setOrderState: () => setOrderState,
249
273
  shipsToCountry: () => shipsToCountry,
250
274
  shopDayKey: () => shopDayKey,
251
275
  shopDayRange: () => shopDayRange,
276
+ shortestMinutesOf: () => shortestMinutesOf,
252
277
  signReportForDisplay: () => signReportForDisplay,
253
278
  slotsForWindow: () => slotsForWindow,
279
+ soldAsCourse: () => soldAsCourse,
254
280
  stringifyMinorUnits: () => stringifyMinorUnits,
255
281
  subtractAmounts: () => subtractAmounts,
256
282
  toBase: () => toBase,
@@ -261,6 +287,8 @@ __export(index_exports, {
261
287
  validateShippingZone: () => validateShippingZone,
262
288
  violatesFinancialInvariant: () => violatesFinancialInvariant,
263
289
  windowEndsAt: () => windowEndsAt,
290
+ windowEndsAtInZone: () => windowEndsAtInZone,
291
+ windowForPeriods: () => windowForPeriods,
264
292
  withinPresence: () => withinPresence
265
293
  });
266
294
  module.exports = __toCommonJS(index_exports);
@@ -721,21 +749,37 @@ var PaymentProcessor = /* @__PURE__ */ ((PaymentProcessor2) => {
721
749
  })(PaymentProcessor || {});
722
750
 
723
751
  // enums/booking.enum.ts
724
- var BookingType = /* @__PURE__ */ ((BookingType3) => {
725
- BookingType3["RENTAL"] = "rental";
726
- BookingType3["APPOINTMENT"] = "appointment";
727
- BookingType3["OVERNIGHT"] = "overnight";
728
- BookingType3["GROUP"] = "group";
729
- return BookingType3;
752
+ var BookingType = /* @__PURE__ */ ((BookingType2) => {
753
+ BookingType2["RENTAL"] = "rental";
754
+ BookingType2["APPOINTMENT"] = "appointment";
755
+ BookingType2["OVERNIGHT"] = "overnight";
756
+ BookingType2["GROUP"] = "group";
757
+ return BookingType2;
730
758
  })(BookingType || {});
731
759
  var BookingRatePeriod = /* @__PURE__ */ ((BookingRatePeriod2) => {
732
760
  BookingRatePeriod2["SLOT"] = "slot";
761
+ BookingRatePeriod2["HOUR"] = "hour";
762
+ BookingRatePeriod2["SESSION"] = "session";
733
763
  BookingRatePeriod2["DAY"] = "day";
734
764
  BookingRatePeriod2["NIGHT"] = "night";
735
765
  BookingRatePeriod2["WEEK"] = "week";
736
766
  BookingRatePeriod2["MONTH"] = "month";
737
767
  return BookingRatePeriod2;
738
768
  })(BookingRatePeriod || {});
769
+ var BookingDurationUnit = /* @__PURE__ */ ((BookingDurationUnit2) => {
770
+ BookingDurationUnit2["MINUTE"] = "minute";
771
+ BookingDurationUnit2["HOUR"] = "hour";
772
+ BookingDurationUnit2["DAY"] = "day";
773
+ BookingDurationUnit2["NIGHT"] = "night";
774
+ BookingDurationUnit2["WEEK"] = "week";
775
+ BookingDurationUnit2["MONTH"] = "month";
776
+ return BookingDurationUnit2;
777
+ })(BookingDurationUnit || {});
778
+ var BookingSessionSale = /* @__PURE__ */ ((BookingSessionSale2) => {
779
+ BookingSessionSale2["SESSION"] = "session";
780
+ BookingSessionSale2["COURSE"] = "course";
781
+ return BookingSessionSale2;
782
+ })(BookingSessionSale || {});
739
783
  var BookingResourceKind = /* @__PURE__ */ ((BookingResourceKind2) => {
740
784
  BookingResourceKind2["ASSET"] = "asset";
741
785
  BookingResourceKind2["ROOM"] = "room";
@@ -3596,6 +3640,7 @@ var ORDER_STATE_EVENTS = {
3596
3640
  };
3597
3641
 
3598
3642
  // booking/types.ts
3643
+ var UNLIMITED_PLACES = Number.MAX_SAFE_INTEGER;
3599
3644
  var BookingRulesError = class extends Error {
3600
3645
  constructor(message) {
3601
3646
  super(message);
@@ -3664,153 +3709,39 @@ function atZonedMinute(dayStart, minutes, timeZone) {
3664
3709
  const { year, month, day } = zonedParts(dayStart, timeZone);
3665
3710
  return instantFromLocal(year, month, day, minutes, timeZone);
3666
3711
  }
3667
-
3668
- // booking/grid.ts
3669
- var MINUTE2 = 6e4;
3670
- var MAX_RANGE_DAYS = 366;
3671
- var asTime = (value, field) => {
3672
- if (value == null) return void 0;
3673
- const time = new Date(value).getTime();
3674
- if (Number.isNaN(time)) throw new BookingRulesError(`Booking rules: ${field} is not a date, got "${String(value)}"`);
3675
- return time;
3676
- };
3677
- function parseHhMm(value, field) {
3678
- const [hours, minutes] = value.split(":").map(Number);
3679
- if (!Number.isInteger(hours) || !Number.isInteger(minutes)) {
3680
- throw new BookingRulesError(`Booking rules: ${field} must be "HH:mm", got "${value}"`);
3681
- }
3682
- return hours * 60 + minutes;
3683
- }
3684
- function windowEndsAt(rule, now) {
3685
- const { maxAdvanceDays, bookableTo } = rule.window;
3686
- const ends = Math.min(
3687
- maxAdvanceDays ? now.getTime() + maxAdvanceDays * 1440 * MINUTE2 : Number.POSITIVE_INFINITY,
3688
- asTime(bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
3689
- );
3690
- return Number.isFinite(ends) ? new Date(ends) : null;
3712
+ function sameDayMonthsLaterDate(year, month, day, months) {
3713
+ const target = new Date(Date.UTC(year, month - 1 + months, 1));
3714
+ const lastDay = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();
3715
+ return [target.getUTCFullYear(), target.getUTCMonth() + 1, Math.min(day, lastDay)];
3691
3716
  }
3692
- function periodSlot(dayStart, timeZone, rule, openMinute, closeMinute) {
3693
- const { ratePeriod, slot, checkInTime, checkOutTime } = rule;
3694
- const at = (minutes) => atZonedMinute(dayStart, minutes, timeZone);
3695
- if (ratePeriod === "night" /* NIGHT */) {
3696
- if (!checkInTime || !checkOutTime) {
3697
- throw new BookingRulesError("Overnight booking rules need both checkInTime and checkOutTime");
3698
- }
3699
- const checkIn = parseHhMm(checkInTime, "checkInTime");
3700
- const checkOut = parseHhMm(checkOutTime, "checkOutTime");
3701
- return {
3702
- startAt: at(checkIn),
3703
- endAt: at(1440 + checkOut),
3704
- // Housekeeping sits between check-out and the next check-in: it costs no night.
3705
- bufferEndAt: at(1440 + checkIn),
3706
- canStart: true
3707
- };
3708
- }
3709
- const from = ratePeriod === "day" /* DAY */ ? openMinute ?? 0 : 0;
3710
- const to = ratePeriod === "day" /* DAY */ ? closeMinute ?? 1440 : 1440;
3711
- return {
3712
- startAt: at(from),
3713
- endAt: at(to),
3714
- bufferEndAt: at(to + (slot.bufferMinutes ?? 0)),
3715
- canStart: true
3716
- };
3717
- }
3718
- function freeGaps(openAt, closeAt, busy) {
3719
- const inside = busy.map(({ startAt, bufferEndAt }) => ({ from: +startAt, to: +bufferEndAt })).filter(({ from, to }) => to > openAt && from < closeAt).sort((first, second) => first.from - second.from);
3720
- const gaps = [];
3721
- let cursor = openAt;
3722
- for (const { from, to } of inside) {
3723
- if (from > cursor) gaps.push({ from: cursor, to: from, endsAtBooking: true });
3724
- cursor = Math.max(cursor, to);
3725
- if (cursor >= closeAt) break;
3726
- }
3727
- if (cursor < closeAt) gaps.push({ from: cursor, to: closeAt, endsAtBooking: false });
3728
- return gaps;
3729
- }
3730
- function buildGrid(rule, timeZone, from, to, now, busy = []) {
3731
- if (to.getTime() - from.getTime() > MAX_RANGE_DAYS * 1440 * MINUTE2) {
3732
- throw new BookingRulesError(`A booking range may span at most ${MAX_RANGE_DAYS} days`);
3733
- }
3734
- const { availability, slot, window, ratePeriod } = rule;
3735
- const periodMode = ratePeriod !== "slot" /* SLOT */;
3736
- const weeklyHours = availability.weeklyHours ?? [];
3737
- const notBefore = Math.max(
3738
- now.getTime() + (window.minNoticeMinutes ?? 0) * MINUTE2,
3739
- asTime(window.bookableFrom, "window.bookableFrom") ?? 0,
3740
- asTime(availability.availableFrom, "availability.availableFrom") ?? 0
3741
- );
3742
- const notAfter = windowEndsAt(rule, now)?.getTime() ?? Number.POSITIVE_INFINITY;
3743
- const blocked = (availability.offMarket ?? []).map(({ from: blockFrom, to: blockTo }) => ({
3744
- from: asTime(blockFrom, "availability.offMarket.from"),
3745
- to: asTime(blockTo, "availability.offMarket.to")
3746
- }));
3747
- const arrivalDays = availability.arrivalDays;
3748
- const step = slot.lengthMinutes + (slot.bufferMinutes ?? 0);
3749
- const slots = [];
3750
- const lastDay = startOfZonedDay(to, timeZone).getTime();
3751
- let dayStart = startOfZonedDay(from, timeZone);
3752
- while (dayStart.getTime() <= lastDay) {
3753
- const weekday = zonedParts(dayStart, timeZone).weekday;
3754
- const rows = weeklyHours.filter((entry) => entry.weekday === weekday);
3755
- if (periodMode) {
3756
- const openToday = weeklyHours.length === 0 || rows.length > 0;
3757
- if (openToday) {
3758
- const built = periodSlot(dayStart, timeZone, rule, rows[0]?.openMinute, rows[0]?.closeMinute);
3759
- slots.push({ ...built, canStart: !arrivalDays?.length || arrivalDays.includes(weekday) });
3760
- }
3761
- } else {
3762
- for (const row of rows) {
3763
- const openAt = +atZonedMinute(dayStart, row.openMinute, timeZone);
3764
- const closeAt = +atZonedMinute(dayStart, row.closeMinute, timeZone);
3765
- for (const gap of freeGaps(openAt, closeAt, busy)) {
3766
- const mustFit = (gap.endsAtBooking ? step : slot.lengthMinutes) * MINUTE2;
3767
- for (let start = gap.from; start + mustFit <= gap.to; start += step * MINUTE2) {
3768
- slots.push({
3769
- startAt: new Date(start),
3770
- endAt: new Date(start + slot.lengthMinutes * MINUTE2),
3771
- bufferEndAt: new Date(start + step * MINUTE2),
3772
- canStart: true
3773
- });
3774
- }
3775
- }
3776
- }
3777
- }
3778
- dayStart = nextZonedDay(dayStart, timeZone);
3779
- }
3780
- const askedFrom = from.getTime();
3781
- const askedTo = to.getTime();
3782
- return slots.filter(({ startAt, bufferEndAt }) => {
3783
- const start = startAt.getTime();
3784
- if (start < askedFrom || start >= askedTo) return false;
3785
- if (start < notBefore || start > notAfter) return false;
3786
- return !blocked.some(
3787
- ({ from: blockFrom, to: blockTo }) => start < blockTo && bufferEndAt.getTime() > blockFrom
3788
- );
3789
- }).sort((first, second) => +first.startAt - +second.startAt);
3790
- }
3791
- function slotsForWindow(grid, startAt, endAt) {
3792
- const startIndex = grid.findIndex((entry) => entry.startAt.getTime() === startAt.getTime());
3793
- if (startIndex < 0) {
3794
- throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
3795
- }
3796
- if (!grid[startIndex].canStart) {
3797
- throw new BookingRulesError(`${startAt.toISOString()} is not an arrival day for these rules`);
3798
- }
3799
- const covered = [];
3800
- for (let index = startIndex; index < grid.length; index++) {
3801
- const entry = grid[index];
3802
- const previous = covered[covered.length - 1];
3803
- if (previous && entry.startAt.getTime() !== previous.bufferEndAt.getTime()) break;
3804
- covered.push(entry);
3805
- if (entry.endAt.getTime() === endAt.getTime()) return covered;
3806
- if (entry.endAt.getTime() > endAt.getTime()) break;
3807
- }
3717
+ function addClockDuration(from, { count, unit: unit2 }) {
3718
+ if (unit2 === "minute" /* MINUTE */) return new Date(from.getTime() + count * MINUTE);
3719
+ if (unit2 === "hour" /* HOUR */) return new Date(from.getTime() + count * 60 * MINUTE);
3808
3720
  throw new BookingRulesError(
3809
- `${startAt.toISOString()} \u2192 ${endAt.toISOString()} does not line up with the bookable grid`
3721
+ `Booking rules: ${count} ${unit2} is not minutes or hours \u2014 it needs the shop's time zone`
3810
3722
  );
3811
3723
  }
3724
+ var DAYS_IN = {
3725
+ ["day" /* DAY */]: 1,
3726
+ ["night" /* NIGHT */]: 1,
3727
+ ["week" /* WEEK */]: 7
3728
+ };
3729
+ function addDuration(from, duration, timeZone) {
3730
+ const { count, unit: unit2 } = duration;
3731
+ if (unit2 === "minute" /* MINUTE */ || unit2 === "hour" /* HOUR */) return addClockDuration(from, duration);
3732
+ const days = DAYS_IN[unit2];
3733
+ if (days === void 0 && unit2 !== "month" /* MONTH */) {
3734
+ throw new BookingRulesError(`Booking rules: "${unit2}" is not a duration unit`);
3735
+ }
3736
+ if (!Number.isInteger(count)) throw new BookingRulesError(`Booking rules: ${count} ${unit2} is not a whole number`);
3737
+ const { year, month, day, hour, minute, second } = zonedParts(from, timeZone);
3738
+ const [toYear, toMonth, toDay] = days === void 0 ? sameDayMonthsLaterDate(year, month, day, count) : [year, month, day + days * count];
3739
+ const wallClock = instantFromLocal(toYear, toMonth, toDay, hour * 60 + minute, timeZone);
3740
+ return new Date(wallClock.getTime() + second * 1e3 + from.getUTCMilliseconds());
3741
+ }
3812
3742
 
3813
3743
  // booking/availability.ts
3744
+ var placesOnTheWire = (entry) => Number.isFinite(entry.capacity) ? entry : { ...entry, capacity: UNLIMITED_PLACES, free: UNLIMITED_PLACES, unlimited: true };
3814
3745
  var withinPresence = (slot, timeZone, presence) => {
3815
3746
  if (!presence?.length) return true;
3816
3747
  const dayStart = startOfZonedDay(slot.startAt, timeZone);
@@ -3857,25 +3788,33 @@ function shopDayRange(fromDayKey, count, timeZone) {
3857
3788
  function buildAvailability({
3858
3789
  productId,
3859
3790
  bookingRulesId,
3860
- bookingType,
3861
3791
  rule,
3862
3792
  resources,
3863
3793
  occupied,
3864
3794
  from,
3865
3795
  to,
3866
- now
3796
+ now,
3797
+ timeZone
3867
3798
  }) {
3868
3799
  const shared = rule.slot.sharedAcrossProducts ?? false;
3869
- const bookableUntil = windowEndsAt(rule, now);
3800
+ const bookableUntil = windowEndsAtInZone(rule, now, timeZone ?? null);
3801
+ const parts = bookingRuleParts(rule);
3870
3802
  const header = {
3871
3803
  productId,
3872
3804
  bookingRulesId,
3873
- bookingType,
3874
3805
  ratePeriod: rule.ratePeriod,
3806
+ // Time slots / sessions / date ranges — so a reader never re-classifies `ratePeriod` itself.
3807
+ bookingMethod: bookingMethodOf(rule),
3875
3808
  // Passed through for the UI to label: a group slot under minimumToRun may not run.
3876
3809
  minimumToRun: rule.slot.minimumToRun,
3877
3810
  minStay: rule.slot.minStay,
3878
3811
  maxStay: rule.slot.maxStay,
3812
+ // The same limits with their own units, both rule shapes. `minStay` / `maxStay` above go at B13 step 9.
3813
+ minStayLength: parts.method === "date-ranges" ? parts.minStay : void 0,
3814
+ maxStayLength: parts.method === "date-ranges" ? parts.maxStay : void 0,
3815
+ // The per-booking limits, so a stepper is bounded by the rules (G7) instead of a number in the flow.
3816
+ maxQtyPerBooking: rule.slot.maxQtyPerBooking,
3817
+ maxPartySize: rule.slot.maxPartySize,
3879
3818
  // Why a day can come back empty. Past this instant the rule refuses everything, so the UI
3880
3819
  // can say "beyond the booking window" where it would otherwise claim "nothing free".
3881
3820
  bookableUntil,
@@ -3899,7 +3838,7 @@ function buildAvailability({
3899
3838
  const byInstant = /* @__PURE__ */ new Map();
3900
3839
  const freeSlotsPerResource = /* @__PURE__ */ new Map();
3901
3840
  for (const { resource, slots: slots2 } of grids) {
3902
- const capacity = resource.seats ?? 1;
3841
+ const capacity = capacityOf(rule, resource);
3903
3842
  const mine = byResource.get(resource.id) ?? [];
3904
3843
  for (const slot of slots2) {
3905
3844
  const { taken, foreignProductId } = occupancyIn(mine, productId, slot.startAt, slot.bufferEndAt, shared);
@@ -3916,7 +3855,9 @@ function buildAvailability({
3916
3855
  entry.booked += foreignProductId ? capacity : taken;
3917
3856
  entry.free += free;
3918
3857
  entry.canStart = entry.canStart || slot.canStart;
3919
- entry.resources.push({ resourceId: resource.id, name: resource.name, capacity, booked: taken, free });
3858
+ entry.resources.push(
3859
+ placesOnTheWire({ resourceId: resource.id, name: resource.name, capacity, booked: taken, free })
3860
+ );
3920
3861
  if (free > 0) freeSlotsPerResource.set(resource.id, (freeSlotsPerResource.get(resource.id) ?? 0) + 1);
3921
3862
  byInstant.set(+slot.startAt, entry);
3922
3863
  }
@@ -3938,9 +3879,10 @@ function buildAvailability({
3938
3879
  )
3939
3880
  };
3940
3881
  });
3941
- const slots = [...byInstant.values()].sort((first, second) => +first.startAt - +second.startAt);
3882
+ const slots = [...byInstant.values()].map(placesOnTheWire).map((slot) => withMaxQtyNow(slot, slot.resources, rule.slot.maxQtyPerBooking)).sort((first, second) => +first.startAt - +second.startAt);
3942
3883
  return {
3943
3884
  ...header,
3885
+ course: soldAsCourse(rule) ? courseAvailability(rule, resources, byResource, productId, shared, now) : void 0,
3944
3886
  resources: inWindow,
3945
3887
  slots,
3946
3888
  /**
@@ -3952,6 +3894,51 @@ function buildAvailability({
3952
3894
  days: [...new Set(slots.map((slot) => slot.dayKey))]
3953
3895
  };
3954
3896
  }
3897
+ function courseAvailability(rule, resources, byResource, productId, shared, now) {
3898
+ if (resources.length === 0) return void 0;
3899
+ const sessions = courseSessions(rule, resources[0].timeZone);
3900
+ const alreadyStarted = courseStartedInZone(rule, sessions, now, resources[0].timeZone);
3901
+ const free = resources.map((resource) => {
3902
+ const mine = byResource.get(resource.id) ?? [];
3903
+ const everySession = sessions.every((session) => withinPresence(session, resource.timeZone, resource.presence));
3904
+ const freePerSession = sessions.map((session) => {
3905
+ const { taken, foreignProductId } = occupancyIn(mine, productId, session.startAt, session.bufferEndAt, shared);
3906
+ return foreignProductId ? 0 : Math.max(capacityOf(rule, resource) - taken, 0);
3907
+ });
3908
+ const fewest = everySession && !alreadyStarted ? Math.min(...freePerSession) : 0;
3909
+ return Number.isFinite(fewest) ? { resourceId: resource.id, free: fewest } : { resourceId: resource.id, free: UNLIMITED_PLACES, unlimited: true };
3910
+ });
3911
+ return withMaxQtyNow(
3912
+ {
3913
+ sessions: sessions.length,
3914
+ alreadyStarted,
3915
+ sessionTimes: sessions.map(({ startAt, endAt }) => ({ startAt, endAt })),
3916
+ startAt: sessions[0].startAt,
3917
+ endAt: sessions[sessions.length - 1].endAt,
3918
+ resources: free
3919
+ },
3920
+ free,
3921
+ rule.slot.maxQtyPerBooking
3922
+ );
3923
+ }
3924
+ function pickFreeResource(slot, qty = 1) {
3925
+ return slot.resources.find((entry) => entry.free >= qty);
3926
+ }
3927
+ function withMaxQtyNow(entry, resources, maxQtyPerBooking) {
3928
+ const largest = resources.some((resource) => resource.unlimited) ? Number.POSITIVE_INFINITY : Math.max(0, ...resources.map((resource) => resource.free));
3929
+ const maxQtyNow = Math.min(largest, maxQtyPerBooking ?? Number.POSITIVE_INFINITY);
3930
+ return Number.isFinite(maxQtyNow) ? { ...entry, maxQtyNow } : entry;
3931
+ }
3932
+ function fewestFreeOver(slots, from, to) {
3933
+ const cells = slots.filter(({ startAt, endAt }) => +startAt >= +from && +endAt <= +to);
3934
+ if (cells.length === 0) return [];
3935
+ return cells[0].resources.map((resource) => ({
3936
+ ...resource,
3937
+ free: Math.min(
3938
+ ...cells.map((cell) => cell.resources.find(({ resourceId }) => resourceId === resource.resourceId)?.free ?? 0)
3939
+ )
3940
+ }));
3941
+ }
3955
3942
  function presentAt(resources, rows, outletId) {
3956
3943
  const byResource = /* @__PURE__ */ new Map();
3957
3944
  for (const row of rows) {
@@ -3965,6 +3952,107 @@ function presentAt(resources, rows, outletId) {
3965
3952
  });
3966
3953
  }
3967
3954
 
3955
+ // booking/durations.ts
3956
+ var { MINUTE: MINUTE2, HOUR, DAY, NIGHT, WEEK, MONTH } = BookingDurationUnit;
3957
+ var NONE = [];
3958
+ var CLOCK = [MINUTE2, HOUR];
3959
+ var everyType = (units) => Object.fromEntries(Object.values(BookingRatePeriod).map((ratePeriod) => [ratePeriod, units]));
3960
+ var STAY = {
3961
+ slot: NONE,
3962
+ session: NONE,
3963
+ hour: [HOUR, DAY, WEEK],
3964
+ night: [NIGHT, WEEK, MONTH],
3965
+ day: [DAY, WEEK, MONTH],
3966
+ week: [WEEK],
3967
+ month: [MONTH]
3968
+ };
3969
+ var ALLOWED_UNITS = {
3970
+ "timeSlots.length": { ...everyType(NONE), slot: CLOCK },
3971
+ "slot.buffer": { ...everyType(CLOCK), night: NONE },
3972
+ "window.hold": everyType(CLOCK),
3973
+ "window.minNotice": everyType([MINUTE2, HOUR, DAY, WEEK]),
3974
+ "window.maxAdvance": everyType([MINUTE2, HOUR, DAY, WEEK, MONTH]),
3975
+ "dateRanges.minStay": STAY,
3976
+ "dateRanges.maxStay": STAY
3977
+ };
3978
+ function allowedDurationUnits(rule, field) {
3979
+ const units = ALLOWED_UNITS[field]?.[rule.ratePeriod];
3980
+ if (!units) throw new BookingRulesError(`Booking rules: no duration "${field}" for rate period "${rule.ratePeriod}"`);
3981
+ return units;
3982
+ }
3983
+ var DURATION_AT = {
3984
+ "timeSlots.length": (rule) => rule.timeSlots?.length,
3985
+ "slot.buffer": (rule) => rule.slot.buffer,
3986
+ "window.hold": (rule) => rule.window.hold,
3987
+ "window.minNotice": (rule) => rule.window.minNotice,
3988
+ "window.maxAdvance": (rule) => rule.window.maxAdvance,
3989
+ "dateRanges.minStay": (rule) => rule.dateRanges?.minStay,
3990
+ "dateRanges.maxStay": (rule) => rule.dateRanges?.maxStay
3991
+ };
3992
+ function durationProblems(rule) {
3993
+ const problems = Object.keys(DURATION_AT).flatMap((field) => {
3994
+ const duration = DURATION_AT[field](rule);
3995
+ const problem = duration && problemOf(field, duration, allowedDurationUnits(rule, field), rule.ratePeriod);
3996
+ return problem ? [problem] : [];
3997
+ });
3998
+ if (problems.length > 0) return problems;
3999
+ return [stayAboveMax(rule.dateRanges?.minStay, rule.dateRanges?.maxStay), noticeAboveAdvance(rule.window)].filter(
4000
+ (problem) => !!problem
4001
+ );
4002
+ }
4003
+ function problemOf(field, duration, allowed, ratePeriod) {
4004
+ if (!Number.isInteger(duration.count) || duration.count < 1) {
4005
+ const message = `${field}: count must be a whole number of at least 1, got ${String(duration.count)}`;
4006
+ return { field, kind: "count", message };
4007
+ }
4008
+ if (allowed.length === 0) {
4009
+ return { field, kind: "not-for-type", message: `${field}: does not apply to ${ratePeriod} rules` };
4010
+ }
4011
+ if (!allowed.includes(duration.unit)) {
4012
+ return { field, kind: "unit", allowed, message: `${field}: takes ${allowed.join(", ")}, got ${duration.unit}` };
4013
+ }
4014
+ return void 0;
4015
+ }
4016
+ var MINUTES_RANGE = {
4017
+ minute: [1, 1],
4018
+ hour: [60, 60],
4019
+ day: [1440, 1440],
4020
+ night: [1440, 1440],
4021
+ week: [7 * 1440, 7 * 1440],
4022
+ month: [28 * 1440, 31 * 1440]
4023
+ };
4024
+ var clockShiftOf = (unit2) => unit2 === MINUTE2 || unit2 === HOUR ? 0 : 60;
4025
+ var shortestMinutesOf = ({ count, unit: unit2 }) => count * MINUTES_RANGE[unit2][0] - clockShiftOf(unit2);
4026
+ var longestMinutesOf = ({ count, unit: unit2 }) => count * MINUTES_RANGE[unit2][1] + clockShiftOf(unit2);
4027
+ var durationText = ({ count, unit: unit2 }) => `${count} ${unit2}${count === 1 ? "" : "s"}`;
4028
+ var DAYS_IN_UNIT = { day: 1, night: 1, week: 7 };
4029
+ var MINUTES_IN_UNIT = { minute: 1, hour: 60 };
4030
+ function exactly(min, max) {
4031
+ if (min.unit === max.unit) return [min.count, max.count];
4032
+ for (const table of [DAYS_IN_UNIT, MINUTES_IN_UNIT]) {
4033
+ const [minSize, maxSize] = [table[min.unit], table[max.unit]];
4034
+ if (minSize && maxSize) return [min.count * minSize, max.count * maxSize];
4035
+ }
4036
+ return void 0;
4037
+ }
4038
+ function minLongerThanMax(min, max) {
4039
+ const exact = exactly(min, max);
4040
+ return exact ? exact[0] > exact[1] : longestMinutesOf(min) > shortestMinutesOf(max);
4041
+ }
4042
+ function stayAboveMax(min, max) {
4043
+ if (!min || !max || !minLongerThanMax(min, max)) return void 0;
4044
+ const message = `dateRanges.maxStay: Max ${durationText(max)} can be shorter than Min ${durationText(min)}`;
4045
+ return { field: "dateRanges.maxStay", kind: "min-above-max", min, max, message };
4046
+ }
4047
+ function noticeAboveAdvance({
4048
+ minNotice,
4049
+ maxAdvance
4050
+ }) {
4051
+ if (!minNotice || !maxAdvance || !minLongerThanMax(minNotice, maxAdvance)) return void 0;
4052
+ const message = `window.maxAdvance: ${durationText(maxAdvance)} ahead can be shorter than the notice of ${durationText(minNotice)}`;
4053
+ return { field: "window.maxAdvance", kind: "min-above-max", min: minNotice, max: maxAdvance, message };
4054
+ }
4055
+
3968
4056
  // booking/plan.ts
3969
4057
  var DEFAULT_HOLD_MINUTES = 10;
3970
4058
  function planWindow({ rule, timeZone, presence, startAt, endAt, now, busy = [] }) {
@@ -3972,17 +4060,623 @@ function planWindow({ rule, timeZone, presence, startAt, endAt, now, busy = [] }
3972
4060
  (slot) => withinPresence(slot, timeZone, presence)
3973
4061
  );
3974
4062
  const slots = slotsForWindow(grid, startAt, endAt);
3975
- const { minStay, maxStay } = rule.slot;
3976
- if (minStay && slots.length < minStay) {
3977
- throw new BookingRulesError(`These rules ask for at least ${minStay} period(s), got ${slots.length}`);
4063
+ const last = slots[slots.length - 1];
4064
+ const parts = bookingRuleParts(rule);
4065
+ const wholePeriods = parts.method === "date-ranges" && parts.wholePeriods;
4066
+ const periods = wholePeriods ? wholePeriodsIn(rule.ratePeriod, timeZone, startAt, last.endAt, slots.length) : slots.length;
4067
+ checkStay(parts, timeZone, startAt, periods);
4068
+ const { buffer } = ruleDurationsOf(rule);
4069
+ const bufferEndAt = rule.ratePeriod === "hour" /* HOUR */ || wholePeriods ? buffer ? addDuration(last.endAt, buffer, timeZone) : new Date(last.endAt.getTime()) : last.bufferEndAt;
4070
+ return { slots, periods, endAt: last.endAt, bufferEndAt };
4071
+ }
4072
+ function checkStay(parts, timeZone, startAt, periods) {
4073
+ if (parts.method !== "date-ranges") return;
4074
+ const stay = { count: periods, unit: periodUnitOf(parts) };
4075
+ const length = (duration) => stayLength(parts.ratePeriod, duration, startAt, timeZone);
4076
+ const { minStay, maxStay } = parts;
4077
+ if (minStay && length(stay) < length(minStay)) {
4078
+ throw new BookingRulesError(
4079
+ `These rules ask for a stay of at least ${durationText(minStay)}, got ${durationText(stay)}`
4080
+ );
3978
4081
  }
3979
- if (maxStay && slots.length > maxStay) {
3980
- throw new BookingRulesError(`These rules allow at most ${maxStay} period(s), got ${slots.length}`);
4082
+ if (maxStay && length(stay) > length(maxStay)) {
4083
+ throw new BookingRulesError(
4084
+ `These rules allow a stay of at most ${durationText(maxStay)}, got ${durationText(stay)}`
4085
+ );
3981
4086
  }
3982
- const last = slots[slots.length - 1];
3983
- return { slots, endAt: last.endAt, bufferEndAt: last.bufferEndAt };
3984
4087
  }
3985
- var holdExpiresAt = (rule, now) => new Date(now.getTime() + (rule.window.holdMinutes ?? DEFAULT_HOLD_MINUTES) * 6e4);
4088
+ function stayLength(ratePeriod, duration, startAt, timeZone) {
4089
+ if (ratePeriod === "hour" /* HOUR */) return addDuration(startAt, duration, timeZone).getTime();
4090
+ const { count, unit: unit2 } = duration;
4091
+ if (unit2 === "day" /* DAY */ || unit2 === "night" /* NIGHT */) return count;
4092
+ if (unit2 === "week" /* WEEK */) return 7 * count;
4093
+ if (unit2 !== "month" /* MONTH */) {
4094
+ throw new BookingRulesError(`Booking rules: a ${ratePeriod} stay cannot be counted in ${unit2}s`);
4095
+ }
4096
+ const { year, month, day } = zonedParts(startAt, timeZone);
4097
+ const [toYear, toMonth, toDay] = sameDayMonthsLaterDate(year, month, day, count);
4098
+ return (Date.UTC(toYear, toMonth - 1, toDay) - Date.UTC(year, month - 1, day)) / 864e5;
4099
+ }
4100
+ function windowForPeriods({ rule, timeZone, startAt, periods, now }) {
4101
+ if (!Number.isInteger(periods) || periods < 1) {
4102
+ throw new BookingRulesError(`periods must be a whole number of at least 1, got ${String(periods)}`);
4103
+ }
4104
+ const parts = bookingRuleParts(rule);
4105
+ checkStay(parts, timeZone, startAt, periods);
4106
+ const wholePeriods = parts.method === "date-ranges" && parts.wholePeriods;
4107
+ const monthsEnd = wholePeriods && rule.ratePeriod === "month" /* MONTH */ ? sameDayMonthsLater(startAt, periods, timeZone) : null;
4108
+ const cells = wholePeriods && rule.ratePeriod === "week" /* WEEK */ ? periods * 7 : periods;
4109
+ const lastDay = monthsEnd ?? new Date(startAt.getTime() + (cells + 2) * 1440 * 6e4);
4110
+ const grid = buildGrid(
4111
+ rule,
4112
+ timeZone,
4113
+ startAt,
4114
+ new Date(Math.min(lastDay.getTime() + 1440 * 6e4, startAt.getTime() + 366 * 1440 * 6e4)),
4115
+ now
4116
+ );
4117
+ const startIndex = grid.findIndex((cell) => cell.startAt.getTime() === startAt.getTime());
4118
+ if (startIndex < 0)
4119
+ throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
4120
+ const endAt = monthsEnd ?? grid[startIndex + cells - 1]?.endAt;
4121
+ if (!endAt)
4122
+ throw new BookingRulesError(`${periods} period(s) from ${startAt.toISOString()} run past the bookable grid`);
4123
+ slotsForWindow(grid, startAt, endAt);
4124
+ return { startAt, endAt };
4125
+ }
4126
+ function sameDayMonthsLater(startAt, months, timeZone) {
4127
+ const { year, month, day } = zonedParts(startAt, timeZone);
4128
+ return instantFromLocal(...sameDayMonthsLaterDate(year, month, day, months), 0, timeZone);
4129
+ }
4130
+ function wholePeriodsIn(ratePeriod, timeZone, startAt, endAt, days) {
4131
+ if (ratePeriod === "week" /* WEEK */) {
4132
+ if (days % 7 !== 0) throw new BookingRulesError(`Book whole weeks: ${days} day(s) is not a number of weeks`);
4133
+ return days / 7;
4134
+ }
4135
+ if (ratePeriod !== "month" /* MONTH */) {
4136
+ throw new BookingRulesError("Whole periods are for week and month rules only");
4137
+ }
4138
+ const start = zonedParts(startAt, timeZone);
4139
+ const end = zonedParts(endAt, timeZone);
4140
+ const months = (end.year - start.year) * 12 + (end.month - start.month);
4141
+ const lastDayOfEndMonth = new Date(Date.UTC(end.year, end.month, 0)).getUTCDate();
4142
+ if (months < 1 || end.day !== Math.min(start.day, lastDayOfEndMonth)) {
4143
+ throw new BookingRulesError("Book whole months: the stay must end on the same day of a later month");
4144
+ }
4145
+ return months;
4146
+ }
4147
+ function courseSessions(rule, timeZone) {
4148
+ const { bookableFrom, bookableTo } = rule.window;
4149
+ if (!bookableFrom || !bookableTo) throw new BookingRulesError("A course needs both course dates");
4150
+ const sessions = sessionCells(rule, timeZone, new Date(bookableFrom), new Date(bookableTo)).sort(
4151
+ (first, second) => +first.startAt - +second.startAt
4152
+ );
4153
+ if (sessions.length === 0) throw new BookingRulesError("These course dates hold no session");
4154
+ return sessions;
4155
+ }
4156
+ var courseStarted = (rule, sessions, now) => sessions[0].startAt.getTime() < now.getTime() + (rule.window.minNoticeMinutes ?? 0) * 6e4;
4157
+ function courseStartedInZone(rule, sessions, now, timeZone) {
4158
+ const { minNotice } = ruleDurationsOf(rule);
4159
+ return sessions[0].startAt.getTime() < (minNotice ? addDuration(now, minNotice, timeZone) : now).getTime();
4160
+ }
4161
+ function planCourse({ rule, timeZone, presence, now }) {
4162
+ const sessions = courseSessions(rule, timeZone);
4163
+ if (!sessions.every((session) => withinPresence(session, timeZone, presence))) {
4164
+ throw new BookingRulesError("This resource is not there for every session of the course");
4165
+ }
4166
+ if (courseStartedInZone(rule, sessions, now, timeZone))
4167
+ throw new BookingRulesError("This course has already started");
4168
+ return sessions;
4169
+ }
4170
+ function holdExpiresAt(rule, now) {
4171
+ return addClockDuration(now, holdOf(rule) ?? DEFAULT_HOLD);
4172
+ }
4173
+ var DEFAULT_HOLD = { count: DEFAULT_HOLD_MINUTES, unit: "minute" /* MINUTE */ };
4174
+ function holdOf(rule) {
4175
+ const { hold } = ruleDurationsOf(rule);
4176
+ if (!hold) return void 0;
4177
+ const field = rule.window.hold ? "window.hold" : "window.holdMinutes";
4178
+ if (!Number.isInteger(hold.count)) {
4179
+ throw new BookingRulesError(`${field} must be a whole number of ${hold.unit}s, got ${hold.count}`);
4180
+ }
4181
+ if (hold.count < 1) throw new BookingRulesError(`${field} must be at least 1 ${hold.unit}, got ${hold.count}`);
4182
+ return hold;
4183
+ }
4184
+ function checkQtyPerBooking(rule, qty) {
4185
+ const max = rule.slot.maxQtyPerBooking;
4186
+ if (max !== void 0 && qty > max) {
4187
+ throw new BookingRulesError(`These rules allow at most ${max} per booking, got ${qty}`);
4188
+ }
4189
+ }
4190
+ function checkPartySize(rule, partySize) {
4191
+ const max = rule.slot.maxPartySize;
4192
+ if (max !== void 0 && partySize > max) {
4193
+ throw new BookingRulesError(`These rules allow at most ${max} people per booking, got ${partySize}`);
4194
+ }
4195
+ }
4196
+ function bookingMethodOf(rule) {
4197
+ if (rule.ratePeriod === "slot" /* SLOT */) return "time-slots";
4198
+ if (rule.ratePeriod === "session" /* SESSION */) return "sessions";
4199
+ return "date-ranges";
4200
+ }
4201
+ var soldAsCourse = (rule) => rule.ratePeriod === "session" /* SESSION */ && rule.sessions?.sold === "course" /* COURSE */;
4202
+ function capacityOf(rule, resource) {
4203
+ if (rule.ratePeriod !== "session" /* SESSION */) return resource.seats ?? 1;
4204
+ if (!rule.sessions) throw new BookingRulesError("Scheduled-session rules need their sessions");
4205
+ return rule.sessions.spots ?? Number.POSITIVE_INFINITY;
4206
+ }
4207
+ function bookingRuleParts(rule) {
4208
+ const method = bookingMethodOf(rule);
4209
+ if (method === "sessions") {
4210
+ if (!rule.sessions) throw new BookingRulesError("Scheduled-session rules need their sessions");
4211
+ return { method, sessions: rule.sessions };
4212
+ }
4213
+ if (method === "time-slots") {
4214
+ const timeSlots = rule.timeSlots ? newTimeSlotsOf(rule.timeSlots) : oldTimeSlotsOf(rule);
4215
+ const { count } = timeSlots.length;
4216
+ if (!Number.isInteger(count) || count < 1) {
4217
+ const field = rule.timeSlots ? "timeSlots.length" : "slot.lengthMinutes";
4218
+ throw new BookingRulesError(`Booking rules: ${field} must be a whole number of at least 1, got ${count}`);
4219
+ }
4220
+ return { method, ...timeSlots };
4221
+ }
4222
+ if (!rule.dateRanges) return { method, ratePeriod: rule.ratePeriod, ...oldDateRangesOf(rule) };
4223
+ const wholePeriods = rule.ratePeriod === "week" /* WEEK */ || rule.ratePeriod === "month" /* MONTH */;
4224
+ return { method, ratePeriod: rule.ratePeriod, wholePeriods, ...rule.dateRanges };
4225
+ }
4226
+ function newTimeSlotsOf({ length, weeklyHours }) {
4227
+ if (!weeklyHours?.length) throw new BookingRulesError("Booking rules: timeSlots.weeklyHours needs at least one day");
4228
+ return { length, weeklyHours };
4229
+ }
4230
+ function oldTimeSlotsOf({ slot, availability }) {
4231
+ if (slot.lengthMinutes == null) throw new BookingRulesError("Time-slot rules need their slot length");
4232
+ return {
4233
+ length: { count: slot.lengthMinutes, unit: "minute" /* MINUTE */ },
4234
+ weeklyHours: availability.weeklyHours ?? []
4235
+ };
4236
+ }
4237
+ function oldDateRangesOf(rule) {
4238
+ const { slot, availability } = rule;
4239
+ const wholePeriods = slot.wholePeriods ?? false;
4240
+ const stay = (count) => count ? { count, unit: periodUnitOf({ ratePeriod: rule.ratePeriod, wholePeriods }) } : void 0;
4241
+ return {
4242
+ // Old `[]` meant "open every day" — the new form says that by having no rows.
4243
+ weeklyHours: availability.weeklyHours?.length ? availability.weeklyHours : void 0,
4244
+ arrivalDays: availability.arrivalDays,
4245
+ checkInTime: rule.checkInTime,
4246
+ checkOutTime: rule.checkOutTime,
4247
+ checkTimesByWeekday: rule.checkTimesByWeekday,
4248
+ minStay: stay(slot.minStay),
4249
+ maxStay: stay(slot.maxStay),
4250
+ wholePeriods
4251
+ };
4252
+ }
4253
+ function periodUnitOf({
4254
+ ratePeriod,
4255
+ wholePeriods
4256
+ }) {
4257
+ const units = {
4258
+ ["hour" /* HOUR */]: "hour" /* HOUR */,
4259
+ ["night" /* NIGHT */]: "night" /* NIGHT */,
4260
+ ["day" /* DAY */]: "day" /* DAY */,
4261
+ ["week" /* WEEK */]: wholePeriods ? "week" /* WEEK */ : "day" /* DAY */,
4262
+ ["month" /* MONTH */]: wholePeriods ? "month" /* MONTH */ : "day" /* DAY */
4263
+ };
4264
+ const unit2 = units[ratePeriod];
4265
+ if (!unit2) throw new BookingRulesError(`Booking rules: "${ratePeriod}" is not a date-range rate period`);
4266
+ return unit2;
4267
+ }
4268
+ var OLD_BUFFER = {
4269
+ path: "slot.bufferMinutes",
4270
+ home: {
4271
+ "time-slots": "slot.buffer",
4272
+ sessions: "slot.buffer",
4273
+ // The old night grid never read it: housekeeping is the gap between check-out and check-in (O-1).
4274
+ "date-ranges": ({ ratePeriod }) => ratePeriod === "night" /* NIGHT */ ? { unread: "nights clean between check-out and check-in" } : "slot.buffer"
4275
+ }
4276
+ };
4277
+ var OLD_FIELDS = [
4278
+ {
4279
+ path: "slot.lengthMinutes",
4280
+ home: {
4281
+ "time-slots": "timeSlots.length",
4282
+ sessions: { unread: "placeholder" },
4283
+ "date-ranges": { unread: "placeholder" }
4284
+ }
4285
+ },
4286
+ OLD_BUFFER,
4287
+ {
4288
+ path: "slot.minStay",
4289
+ home: {
4290
+ "time-slots": { dropped: "time-slots rules have no stay limits" },
4291
+ sessions: { dropped: "sessions rules have no stay limits" },
4292
+ "date-ranges": "dateRanges.minStay"
4293
+ }
4294
+ },
4295
+ {
4296
+ path: "slot.maxStay",
4297
+ home: {
4298
+ "time-slots": { dropped: "time-slots rules have no stay limits" },
4299
+ sessions: { dropped: "sessions rules have no stay limits" },
4300
+ "date-ranges": "dateRanges.maxStay"
4301
+ }
4302
+ },
4303
+ {
4304
+ path: "window.holdMinutes",
4305
+ home: { "time-slots": "window.hold", sessions: "window.hold", "date-ranges": "window.hold" }
4306
+ },
4307
+ {
4308
+ path: "window.minNoticeMinutes",
4309
+ home: { "time-slots": "window.minNotice", sessions: "window.minNotice", "date-ranges": "window.minNotice" }
4310
+ },
4311
+ // The two old max-advance fields are one fact, as the old readers took it: minutes, else days × 1440.
4312
+ ...["window.maxAdvanceMinutes", "window.maxAdvanceDays"].map((path) => ({
4313
+ path,
4314
+ carried: maxAdvanceMinutesOf,
4315
+ home: { "time-slots": "window.maxAdvance", sessions: "window.maxAdvance", "date-ranges": "window.maxAdvance" }
4316
+ })),
4317
+ {
4318
+ path: "availability.weeklyHours",
4319
+ home: {
4320
+ "time-slots": "timeSlots.weeklyHours",
4321
+ sessions: { unread: "sessions read their timetable" },
4322
+ "date-ranges": "dateRanges.weeklyHours"
4323
+ }
4324
+ },
4325
+ ...["availability.arrivalDays", "checkInTime", "checkOutTime", "checkTimesByWeekday"].map((path) => ({
4326
+ path,
4327
+ home: {
4328
+ "time-slots": { unread: "date ranges only" },
4329
+ sessions: { unread: "date ranges only" },
4330
+ "date-ranges": `dateRanges.${path.replace("availability.", "")}`
4331
+ }
4332
+ }))
4333
+ ];
4334
+ var homeOf = (field, rule) => {
4335
+ const home = field.home[bookingMethodOf(rule)];
4336
+ return typeof home === "function" ? home(rule) : home;
4337
+ };
4338
+ var carriedValueOf = (rule, field) => field.carried ? field.carried(rule) : valueAt(rule, field.path);
4339
+ var carries = (value) => value != null && value !== 0 && !(Array.isArray(value) && value.length === 0);
4340
+ function ruleInNewShape(rule) {
4341
+ const set = { ...typePartInNewShape(rule), ...durationsInNewShape(rule) };
4342
+ const unset = [...OLD_FIELDS.map(({ path }) => path), "slot.wholePeriods"].filter(
4343
+ (path) => valueAt(rule, path) !== void 0
4344
+ );
4345
+ const written = writtenRule(rule, set, unset);
4346
+ bookingRuleParts(written);
4347
+ refuseLostValues(rule, written);
4348
+ const changesBehaviour = sellsOneDayOfWeekOrMonth(rule) ? "whole-periods" : void 0;
4349
+ const notes = [
4350
+ ...droppedFieldNotes(rule, written),
4351
+ ...changesBehaviour ? [`${rule.ratePeriod} rule now sells whole ${rule.ratePeriod}s, was one day per booking`] : []
4352
+ ];
4353
+ return { set, unset, problems: durationProblems(written), notes, ...changesBehaviour && { changesBehaviour } };
4354
+ }
4355
+ function typePartInNewShape(rule) {
4356
+ const method = bookingMethodOf(rule);
4357
+ if (method === "sessions") return {};
4358
+ if (method === "time-slots") return { timeSlots: newTimeSlotsOf(rule.timeSlots ?? oldTimeSlotsOf(rule)) };
4359
+ if (rule.dateRanges) return { dateRanges: rule.dateRanges };
4360
+ const dateRanges = oldDateRangesOf(rule);
4361
+ delete dateRanges.wholePeriods;
4362
+ return { dateRanges: definedOnly(dateRanges) };
4363
+ }
4364
+ function durationsInNewShape(rule) {
4365
+ const { buffer, minNotice } = ruleDurationsOf(rule);
4366
+ return definedOnly({
4367
+ "slot.buffer": rule.slot.buffer ?? (typeof homeOf(OLD_BUFFER, rule) === "string" ? buffer : void 0),
4368
+ "window.hold": holdOf(rule) ?? DEFAULT_HOLD,
4369
+ "window.minNotice": minNotice,
4370
+ "window.maxAdvance": ruleDurationsOf(rule).maxAdvance
4371
+ });
4372
+ }
4373
+ var sellsOneDayOfWeekOrMonth = ({ ratePeriod, slot, dateRanges }) => !dateRanges && (ratePeriod === "week" /* WEEK */ || ratePeriod === "month" /* MONTH */) && !slot.wholePeriods;
4374
+ function droppedFieldNotes(rule, written) {
4375
+ const weekOrMonth = rule.ratePeriod === "week" /* WEEK */ || rule.ratePeriod === "month" /* MONTH */;
4376
+ return [
4377
+ ...OLD_FIELDS.flatMap((field) => {
4378
+ const home = homeOf(field, rule);
4379
+ const dropped = typeof home === "object" && "dropped" in home && carries(carriedValueOf(rule, field));
4380
+ return dropped ? [`${field.path} is dropped: ${home.dropped}`] : [];
4381
+ }),
4382
+ ...rule.slot.wholePeriods && !weekOrMonth ? ["slot.wholePeriods is dropped: only week and month rules have it"] : [],
4383
+ ...rule.ratePeriod === "hour" /* HOUR */ && !written.dateRanges?.weeklyHours?.length ? ["hour rule has no opening hours: nothing can be booked"] : [],
4384
+ ...rule.window.holdMinutes == null && !rule.window.hold ? [`window.hold is set to the default ${DEFAULT_HOLD_MINUTES} minutes`] : []
4385
+ ];
4386
+ }
4387
+ function writtenRule(rule, set, unset) {
4388
+ const written = {
4389
+ ...rule,
4390
+ slot: { ...rule.slot },
4391
+ window: { ...rule.window },
4392
+ availability: { ...rule.availability }
4393
+ };
4394
+ for (const path of unset) {
4395
+ const [head, leaf] = path.split(".");
4396
+ if (leaf) delete written[head][leaf];
4397
+ else delete written[head];
4398
+ }
4399
+ for (const [path, value] of Object.entries(set)) {
4400
+ const [head, leaf] = path.split(".");
4401
+ if (leaf) written[head][leaf] = value;
4402
+ else written[head] = value;
4403
+ }
4404
+ return written;
4405
+ }
4406
+ function refuseLostValues(rule, written) {
4407
+ for (const field of OLD_FIELDS) {
4408
+ const home = homeOf(field, rule);
4409
+ if (typeof home === "string" && carries(carriedValueOf(rule, field)) && valueAt(written, home) == null) {
4410
+ throw new BookingRulesError(`Booking rules: ${home} is missing \u2014 the rule's old value would be lost`);
4411
+ }
4412
+ }
4413
+ }
4414
+ var definedOnly = (value) => Object.fromEntries(Object.entries(value).filter(([, entry]) => entry != null));
4415
+ var valueAt = (rule, path) => path.split(".").reduce((node, key) => node?.[key], rule);
4416
+
4417
+ // booking/grid.ts
4418
+ var MINUTE3 = 6e4;
4419
+ var HOUR_MINUTES = 60;
4420
+ var MAX_RANGE_DAYS = 366;
4421
+ var asTime = (value, field) => {
4422
+ if (value == null) return void 0;
4423
+ const time = new Date(value).getTime();
4424
+ if (Number.isNaN(time)) throw new BookingRulesError(`Booking rules: ${field} is not a date, got "${String(value)}"`);
4425
+ return time;
4426
+ };
4427
+ function parseHhMm(value, field) {
4428
+ const [hours, minutes] = value.split(":").map(Number);
4429
+ if (!Number.isInteger(hours) || !Number.isInteger(minutes)) {
4430
+ throw new BookingRulesError(`Booking rules: ${field} must be "HH:mm", got "${value}"`);
4431
+ }
4432
+ return hours * 60 + minutes;
4433
+ }
4434
+ function windowEndsAt(rule, now) {
4435
+ const maxAdvanceMinutes = maxAdvanceMinutesOf(rule);
4436
+ const ends = Math.min(
4437
+ maxAdvanceMinutes ? now.getTime() + maxAdvanceMinutes * MINUTE3 : Number.POSITIVE_INFINITY,
4438
+ asTime(rule.window.bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
4439
+ );
4440
+ return Number.isFinite(ends) ? new Date(ends) : null;
4441
+ }
4442
+ function windowEndsAtInZone(rule, now, timeZone) {
4443
+ const { maxAdvance } = ruleDurationsOf(rule);
4444
+ const ends = Math.min(
4445
+ maxAdvance ? addInZone(now, maxAdvance, timeZone, "window.maxAdvance").getTime() : Number.POSITIVE_INFINITY,
4446
+ asTime(rule.window.bookableTo, "window.bookableTo") ?? Number.POSITIVE_INFINITY
4447
+ );
4448
+ return Number.isFinite(ends) ? new Date(ends) : null;
4449
+ }
4450
+ function addInZone(from, duration, timeZone, field) {
4451
+ if (timeZone) return addDuration(from, duration, timeZone);
4452
+ if (duration.unit === "minute" /* MINUTE */ || duration.unit === "hour" /* HOUR */) {
4453
+ return addClockDuration(from, duration);
4454
+ }
4455
+ throw new BookingRulesError(`Booking rules: ${field} in ${duration.unit}s needs the shop's time zone`);
4456
+ }
4457
+ function maxAdvanceMinutesOf(rule) {
4458
+ const { maxAdvanceMinutes, maxAdvanceDays } = rule.window;
4459
+ return maxAdvanceMinutes ?? (maxAdvanceDays ?? 0) * 1440;
4460
+ }
4461
+ var asMinutes = (minutes) => minutes == null ? void 0 : { count: minutes, unit: "minute" /* MINUTE */ };
4462
+ var inMinutes = (minutes) => minutes === 0 ? void 0 : asMinutes(minutes);
4463
+ function notNegative(duration, field) {
4464
+ if (duration && !(Number.isFinite(duration.count) && duration.count >= 0)) {
4465
+ throw new BookingRulesError(`Booking rules: ${field} must be a number of at least 0, got ${duration.count}`);
4466
+ }
4467
+ return duration;
4468
+ }
4469
+ function ruleDurationsOf(rule) {
4470
+ const { slot, window } = rule;
4471
+ return {
4472
+ buffer: notNegative(
4473
+ slot.buffer ?? inMinutes(slot.bufferMinutes),
4474
+ slot.buffer ? "slot.buffer" : "slot.bufferMinutes"
4475
+ ),
4476
+ hold: window.hold ?? asMinutes(window.holdMinutes),
4477
+ minNotice: notNegative(
4478
+ window.minNotice ?? inMinutes(window.minNoticeMinutes),
4479
+ window.minNotice ? "window.minNotice" : "window.minNoticeMinutes"
4480
+ ),
4481
+ maxAdvance: window.maxAdvance ?? oldMaxAdvanceOf(window)
4482
+ };
4483
+ }
4484
+ function oldMaxAdvanceOf({
4485
+ maxAdvanceMinutes,
4486
+ maxAdvanceDays
4487
+ }) {
4488
+ const days = maxAdvanceDays ?? 0;
4489
+ if (maxAdvanceMinutes == null || days > 0 && maxAdvanceMinutes === days * 1440) {
4490
+ return days > 0 ? { count: days, unit: "day" /* DAY */ } : void 0;
4491
+ }
4492
+ return maxAdvanceMinutes ? { count: maxAdvanceMinutes, unit: "minute" /* MINUTE */ } : void 0;
4493
+ }
4494
+ function periodSlot(dayStart, timeZone, parts, buffer, openMinute, closeMinute) {
4495
+ const { ratePeriod } = parts;
4496
+ const at = (minutes) => atZonedMinute(dayStart, minutes, timeZone);
4497
+ if (ratePeriod === "night" /* NIGHT */) {
4498
+ const arrival = zonedParts(dayStart, timeZone).weekday;
4499
+ const departure = (arrival + 1) % 7;
4500
+ return {
4501
+ startAt: at(checkTimesOf(parts, arrival).checkIn),
4502
+ endAt: at(1440 + checkTimesOf(parts, departure).checkOut),
4503
+ // Housekeeping sits between check-out and the next check-in: it costs no night.
4504
+ bufferEndAt: at(1440 + checkTimesOf(parts, departure).checkIn),
4505
+ canStart: true
4506
+ };
4507
+ }
4508
+ const from = ratePeriod === "day" /* DAY */ ? openMinute ?? 0 : 0;
4509
+ const to = ratePeriod === "day" /* DAY */ ? closeMinute ?? 1440 : 1440;
4510
+ const turnaround = parts.wholePeriods ? void 0 : buffer;
4511
+ return {
4512
+ startAt: at(from),
4513
+ endAt: at(to),
4514
+ bufferEndAt: turnaround ? addDuration(at(to), turnaround, timeZone) : at(to),
4515
+ canStart: true
4516
+ };
4517
+ }
4518
+ function checkTimesOf(rule, weekday) {
4519
+ const row = rule.checkTimesByWeekday?.find((entry) => entry.weekday === weekday);
4520
+ const checkInTime = row?.checkInTime ?? rule.checkInTime;
4521
+ const checkOutTime = row?.checkOutTime ?? rule.checkOutTime;
4522
+ if (!checkInTime || !checkOutTime) {
4523
+ throw new BookingRulesError("Overnight booking rules need both checkInTime and checkOutTime");
4524
+ }
4525
+ return { checkIn: parseHhMm(checkInTime, "checkInTime"), checkOut: parseHhMm(checkOutTime, "checkOutTime") };
4526
+ }
4527
+ function freeGaps(openAt, closeAt, busy) {
4528
+ const inside = busy.map(({ startAt, bufferEndAt }) => ({ from: +startAt, to: +bufferEndAt })).filter(({ from, to }) => to > openAt && from < closeAt).sort((first, second) => first.from - second.from);
4529
+ const gaps = [];
4530
+ let cursor = openAt;
4531
+ for (const { from, to } of inside) {
4532
+ if (from > cursor) gaps.push({ from: cursor, to: from, endsAtBooking: true });
4533
+ cursor = Math.max(cursor, to);
4534
+ if (cursor >= closeAt) break;
4535
+ }
4536
+ if (cursor < closeAt) gaps.push({ from: cursor, to: closeAt, endsAtBooking: false });
4537
+ return gaps;
4538
+ }
4539
+ function sessionCells(rule, timeZone, from, to) {
4540
+ if (!rule.sessions) throw new BookingRulesError("Scheduled-session rules need their sessions");
4541
+ const { weekly = [], dates = [] } = rule.sessions;
4542
+ const { buffer } = ruleDurationsOf(rule);
4543
+ const cell = (startAt, endAt) => ({
4544
+ startAt: new Date(startAt),
4545
+ endAt: new Date(endAt),
4546
+ bufferEndAt: buffer ? addDuration(new Date(endAt), buffer, timeZone) : new Date(endAt),
4547
+ canStart: true
4548
+ });
4549
+ const cells = dates.map(({ date, startMinute, endMinute }) => {
4550
+ const [year, month, day] = calendarDate(date);
4551
+ return cell(
4552
+ +instantFromLocal(year, month, day, startMinute, timeZone),
4553
+ +instantFromLocal(year, month, day, endMinute, timeZone)
4554
+ );
4555
+ });
4556
+ const lastDay = startOfZonedDay(to, timeZone).getTime();
4557
+ for (let day = startOfZonedDay(from, timeZone); day.getTime() <= lastDay; day = nextZonedDay(day, timeZone)) {
4558
+ const weekday = zonedParts(day, timeZone).weekday;
4559
+ for (const row of weekly.filter((entry) => entry.weekday === weekday)) {
4560
+ cells.push(cell(+atZonedMinute(day, row.startMinute, timeZone), +atZonedMinute(day, row.endMinute, timeZone)));
4561
+ }
4562
+ }
4563
+ const blocked = offMarketOf(rule);
4564
+ return cells.filter(({ startAt, bufferEndAt }) => {
4565
+ const start = startAt.getTime();
4566
+ return start >= from.getTime() && start <= to.getTime() && !isBlocked(blocked, start, bufferEndAt.getTime());
4567
+ });
4568
+ }
4569
+ function calendarDate(value) {
4570
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value ?? "");
4571
+ const [year, month, day] = match ? match.slice(1).map(Number) : [];
4572
+ const real = match && new Date(Date.UTC(year, month - 1, day)).toISOString().slice(0, 10) === value;
4573
+ if (!real) throw new BookingRulesError(`Booking rules: "${value}" is not a date (YYYY-MM-DD)`);
4574
+ return [year, month, day];
4575
+ }
4576
+ var offMarketOf = (rule) => (rule.availability.offMarket ?? []).map(({ from: blockFrom, to: blockTo }) => ({
4577
+ from: asTime(blockFrom, "availability.offMarket.from"),
4578
+ to: asTime(blockTo, "availability.offMarket.to")
4579
+ }));
4580
+ var isBlocked = (blocked, start, bufferEnd) => blocked.some(({ from, to }) => start < to && bufferEnd > from);
4581
+ function hourCells(openAt, closeAt) {
4582
+ const cells = [];
4583
+ for (let start = openAt; start + HOUR_MINUTES * MINUTE3 <= closeAt; start += HOUR_MINUTES * MINUTE3) {
4584
+ const endAt = new Date(start + HOUR_MINUTES * MINUTE3);
4585
+ cells.push({ startAt: new Date(start), endAt, bufferEndAt: endAt, canStart: true });
4586
+ }
4587
+ return cells;
4588
+ }
4589
+ function cellsOf(rule, parts, timeZone, from, to, busy) {
4590
+ if (parts.method === "sessions") return sessionCells(rule, timeZone, from, to);
4591
+ const { buffer } = ruleDurationsOf(rule);
4592
+ const cells = [];
4593
+ const lastDay = startOfZonedDay(to, timeZone).getTime();
4594
+ for (let day = startOfZonedDay(from, timeZone); day.getTime() <= lastDay; day = nextZonedDay(day, timeZone)) {
4595
+ cells.push(
4596
+ ...parts.method === "time-slots" ? timeSlotCells(parts, buffer, day, timeZone, busy) : periodCells(parts, buffer, day, timeZone)
4597
+ );
4598
+ }
4599
+ return cells;
4600
+ }
4601
+ function timeSlotCells(parts, buffer, dayStart, timeZone, busy) {
4602
+ const weekday = zonedParts(dayStart, timeZone).weekday;
4603
+ return parts.weeklyHours.filter((entry) => entry.weekday === weekday).flatMap(
4604
+ (row) => freeGaps(
4605
+ +atZonedMinute(dayStart, row.openMinute, timeZone),
4606
+ +atZonedMinute(dayStart, row.closeMinute, timeZone),
4607
+ busy
4608
+ ).flatMap((gap) => cellsInGap(gap, parts.length, buffer, timeZone))
4609
+ );
4610
+ }
4611
+ function cellsInGap(gap, length, buffer, timeZone) {
4612
+ const cells = [];
4613
+ for (let start = gap.from; ; ) {
4614
+ const endAt = addDuration(new Date(start), length, timeZone);
4615
+ const bufferEndAt = buffer ? addDuration(endAt, buffer, timeZone) : new Date(endAt.getTime());
4616
+ if ((gap.endsAtBooking ? bufferEndAt : endAt).getTime() > gap.to) return cells;
4617
+ cells.push({ startAt: new Date(start), endAt, bufferEndAt, canStart: true });
4618
+ start = bufferEndAt.getTime();
4619
+ }
4620
+ }
4621
+ function periodCells(parts, buffer, dayStart, timeZone) {
4622
+ const weekday = zonedParts(dayStart, timeZone).weekday;
4623
+ const rows = (parts.weeklyHours ?? []).filter((entry) => entry.weekday === weekday);
4624
+ if (parts.ratePeriod === "hour" /* HOUR */) {
4625
+ return rows.flatMap(
4626
+ (row) => hourCells(
4627
+ +atZonedMinute(dayStart, row.openMinute, timeZone),
4628
+ +atZonedMinute(dayStart, row.closeMinute, timeZone)
4629
+ )
4630
+ );
4631
+ }
4632
+ if (parts.weeklyHours?.length && rows.length === 0) return [];
4633
+ const built = periodSlot(dayStart, timeZone, parts, buffer, rows[0]?.openMinute, rows[0]?.closeMinute);
4634
+ return [{ ...built, canStart: !parts.arrivalDays?.length || parts.arrivalDays.includes(weekday) }];
4635
+ }
4636
+ function buildGrid(rule, timeZone, from, to, now, busy = []) {
4637
+ if (to.getTime() - from.getTime() > MAX_RANGE_DAYS * 1440 * MINUTE3) {
4638
+ throw new BookingRulesError(`A booking range may span at most ${MAX_RANGE_DAYS} days`);
4639
+ }
4640
+ const { availability, window } = rule;
4641
+ const { minNotice } = ruleDurationsOf(rule);
4642
+ const notBefore = Math.max(
4643
+ (minNotice ? addDuration(now, minNotice, timeZone) : now).getTime(),
4644
+ asTime(window.bookableFrom, "window.bookableFrom") ?? 0,
4645
+ asTime(availability.availableFrom, "availability.availableFrom") ?? 0
4646
+ );
4647
+ const notAfter = windowEndsAtInZone(rule, now, timeZone)?.getTime() ?? Number.POSITIVE_INFINITY;
4648
+ const blocked = offMarketOf(rule);
4649
+ const slots = cellsOf(rule, bookingRuleParts(rule), timeZone, from, to, busy);
4650
+ const askedFrom = from.getTime();
4651
+ const askedTo = to.getTime();
4652
+ return slots.filter(({ startAt, bufferEndAt }) => {
4653
+ const start = startAt.getTime();
4654
+ if (start < askedFrom || start >= askedTo) return false;
4655
+ if (start < notBefore || start > notAfter) return false;
4656
+ return !isBlocked(blocked, start, bufferEndAt.getTime());
4657
+ }).sort((first, second) => +first.startAt - +second.startAt);
4658
+ }
4659
+ function slotsForWindow(grid, startAt, endAt) {
4660
+ const startIndex = grid.findIndex((entry) => entry.startAt.getTime() === startAt.getTime());
4661
+ if (startIndex < 0) {
4662
+ throw new BookingRulesError(`${startAt.toISOString()} is not a bookable slot start for these rules`);
4663
+ }
4664
+ if (!grid[startIndex].canStart) {
4665
+ throw new BookingRulesError(`${startAt.toISOString()} is not an arrival day for these rules`);
4666
+ }
4667
+ const covered = [];
4668
+ for (let index = startIndex; index < grid.length; index++) {
4669
+ const entry = grid[index];
4670
+ const previous = covered[covered.length - 1];
4671
+ if (previous && entry.startAt.getTime() !== previous.bufferEndAt.getTime()) break;
4672
+ covered.push(entry);
4673
+ if (entry.endAt.getTime() === endAt.getTime()) return covered;
4674
+ if (entry.endAt.getTime() > endAt.getTime()) break;
4675
+ }
4676
+ throw new BookingRulesError(
4677
+ `${startAt.toISOString()} \u2192 ${endAt.toISOString()} does not line up with the bookable grid`
4678
+ );
4679
+ }
3986
4680
 
3987
4681
  // shipping/fold-text.ts
3988
4682
  function foldText(value) {
@@ -4419,10 +5113,12 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4419
5113
  AttributeType,
4420
5114
  BNPL_METHOD_STATUS,
4421
5115
  BNPL_SKIP_REASON,
5116
+ BookingDurationUnit,
4422
5117
  BookingRatePeriod,
4423
5118
  BookingResourceKind,
4424
5119
  BookingResourceStatus,
4425
5120
  BookingRulesError,
5121
+ BookingSessionSale,
4426
5122
  BookingType,
4427
5123
  CANADA_PROVINCES,
4428
5124
  CONDITION_OPERATORS,
@@ -4512,6 +5208,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4512
5208
  StripeStatus,
4513
5209
  TimePeriod,
4514
5210
  TopMetericsSort,
5211
+ UNLIMITED_PLACES,
4515
5212
  UserTypes,
4516
5213
  addAmounts,
4517
5214
  addressPlaceKeys,
@@ -4520,6 +5217,7 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4520
5217
  adyenStoreRequiresStateOrProvince,
4521
5218
  adyenSupportsTaxNumberAbsent,
4522
5219
  adyenTaxNumberFormat,
5220
+ allowedDurationUnits,
4523
5221
  amountToString,
4524
5222
  ancestorChain,
4525
5223
  applyAssignment,
@@ -4529,15 +5227,21 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4529
5227
  baseFulfillmentDefinitions,
4530
5228
  baseOf,
4531
5229
  basePaymentDefinitions,
5230
+ bookingMethodOf,
5231
+ bookingRuleParts,
4532
5232
  buildAvailability,
4533
5233
  buildGrid,
4534
5234
  buildOrderContext,
4535
5235
  buildPosPresetConfig,
4536
5236
  buildResolvedConfig,
4537
5237
  calculatePercentage,
5238
+ calendarDate,
4538
5239
  canTransition,
5240
+ capacityOf,
4539
5241
  cheapestCompositeItem,
4540
5242
  cheapestCompositePrice,
5243
+ checkPartySize,
5244
+ checkQtyPerBooking,
4541
5245
  compositeItemCost,
4542
5246
  compositeItemUnavailable,
4543
5247
  compositeMakeable,
@@ -4546,6 +5250,9 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4546
5250
  compositeVariantInStock,
4547
5251
  conditionSummary,
4548
5252
  convertFixedFeeToLocalCurrency,
5253
+ courseSessions,
5254
+ courseStarted,
5255
+ courseStartedInZone,
4549
5256
  createAmount,
4550
5257
  crossAxisRuleApplies,
4551
5258
  currentAssignees,
@@ -4554,10 +5261,13 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4554
5261
  deriveUnitId,
4555
5262
  displayRuleMatchesPair,
4556
5263
  divideAmount,
5264
+ durationProblems,
5265
+ durationText,
4557
5266
  evaluateCondition,
4558
5267
  evaluateConditionSet,
4559
5268
  extendPrice,
4560
5269
  extendPriceFor,
5270
+ fewestFreeOver,
4561
5271
  formatCurrency,
4562
5272
  formatInUnit,
4563
5273
  formatMinorUnitsToString,
@@ -4599,7 +5309,9 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4599
5309
  listCountries,
4600
5310
  listProvinces,
4601
5311
  listShippingCountries,
5312
+ longestMinutesOf,
4602
5313
  mapToLegacyStatus,
5314
+ maxAdvanceMinutesOf,
4603
5315
  maxPrecisionFor,
4604
5316
  mergeFragment,
4605
5317
  modifiersSellable,
@@ -4611,11 +5323,14 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4611
5323
  normalizePostCode,
4612
5324
  normalizeProvince,
4613
5325
  occupancyIn,
5326
+ oldMaxAdvanceOf,
4614
5327
  orderAssignments,
4615
5328
  parseAmountToMinorUnits,
4616
5329
  parseCurrencyCode,
4617
5330
  parseStripeCurrencyCode,
5331
+ pickFreeResource,
4618
5332
  placeKey,
5333
+ planCourse,
4619
5334
  planWindow,
4620
5335
  poolDemand,
4621
5336
  poolOf,
@@ -4632,13 +5347,18 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4632
5347
  resolveTemplate,
4633
5348
  resolveUnit,
4634
5349
  roundToPrecision,
5350
+ ruleDurationsOf,
5351
+ ruleInNewShape,
4635
5352
  sameFamily,
5353
+ sessionCells,
4636
5354
  setOrderState,
4637
5355
  shipsToCountry,
4638
5356
  shopDayKey,
4639
5357
  shopDayRange,
5358
+ shortestMinutesOf,
4640
5359
  signReportForDisplay,
4641
5360
  slotsForWindow,
5361
+ soldAsCourse,
4642
5362
  stringifyMinorUnits,
4643
5363
  subtractAmounts,
4644
5364
  toBase,
@@ -4649,6 +5369,8 @@ var EXPENSE_DEFAULT_CATEGORIES = [
4649
5369
  validateShippingZone,
4650
5370
  violatesFinancialInvariant,
4651
5371
  windowEndsAt,
5372
+ windowEndsAtInZone,
5373
+ windowForPeriods,
4652
5374
  withinPresence
4653
5375
  });
4654
5376
  //# sourceMappingURL=index.js.map