bizdays-toolkit 0.31.8 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,48 @@ Entries from 0.31.0 are in English. Earlier entries remain in Japanese (their **
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.32.0] - 2026-11-14
10
+
11
+ This minor version stops one silent loss of closed days, makes aliases of a time zone the same time zone on runtimes with Temporal, and makes one mistaken call a type error. Some code needs a check; see Migration.
12
+
13
+ ### Changed
14
+
15
+ - A day of a `holidayOverlapPolicy: "after-holiday"` rule that cannot be moved past a long run of holidays now throws instead of being silently lost. When a holiday provider returns holidays on more than 31 consecutive days and the rule's own day is more than 31 days before the first day after the run, the rule was not moved and the closed day did not appear at all (documented since 0.31.8). Evaluating that first day now throws a `RangeError` with the new code `holiday-run-too-long`, as do searches that pass the day (`addBusinessDays`, `nextBusinessDay` and the like) and calculations over a range that contains it (`diffBusinessDays`, `daysBetween`, `businessDatesBetween`, `nthBusinessDayOfMonth` and the like). Days inside the run and other days are evaluated as before, a rule whose day is within 31 days is moved as before, and weekly rules and rules for the day before or after a holiday are not affected. The same code is thrown when a run goes on for more than 367 days, because the day to move cannot be determined. Because the search for that day now goes further back than 31 days, the first day after a run of 31 or more days that starts on the first day of the provider's supported years throws `out-of-range` with `outOfRangePolicy: "throw"` (the default), even when no day is lost: the days before the run are not known. Shorter runs there already did. The bundled providers are not affected (their longest run is 8 days). Write a long closure with `closedDates` or `closedAnnualDates`, not as holidays (design decisions 24)
16
+ - Whether two time zones are the same (calendars combined with `combineCalendars`, the holiday providers of one set of options, and a schedule and the counting calendar of its nth-business-day rule) is now decided with the runtime's `Temporal` when their names differ and the runtime has one. Aliases of one time zone, such as `"UTC"` and `"Etc/UTC"` or `"Asia/Kolkata"` and `"Asia/Calcutta"`, are therefore the same time zone on every runtime with Temporal: Bun no longer throws `time-zone-conflict` for them, and on Node.js 26, Chrome and Edge a few more pairs are accepted (such as `"CST6CDT"` and `"America/Chicago"`). Runtimes without Temporal compare the names `Intl` reports, as before; on Safari without Temporal, aliases remain a `time-zone-conflict`. The name `timeZone` returns is unchanged. Only exceptions disappear; no result of a calendar or schedule changes (design decisions 18)
17
+ - TypeScript: passing a holiday provider, a calendar or a schedule itself as the options of `createCalendar` (`createCalendar(jp)`) is now a type error. It compiled until 0.31.9 and made a calendar without holidays. The options types have `holidaysInYear?: never` for this; at run time such a key is still an unknown option that the diagnostics report (design decisions 8). Pass the provider as `createCalendar({ holidayProvider: jp })`
18
+
19
+ ### Added
20
+
21
+ - The error code `holiday-run-too-long` (`KnownErrorCode`), and the same code as a `warning` of the option diagnostics: `diagnoseCalendar` and `diagnoseSchedule` report each `"after-holiday"` rule that loses a day this way, at the rule, with `relatedPath` pointing to the holiday provider when there is only one. The options can still be created, as with `out-of-range` and `no-business-day`
22
+
23
+ ### Fixed
24
+
25
+ - Documentation: the guide and the design decisions (18) now describe offsets from UTC as time zones. `"+09:00"`, `"+0900"` and `"+09"` are accepted and returned as `"+09:00"` on every runtime tested (Node.js, Chrome, Firefox, Edge, Safari, Cloudflare Workers, Bun and Deno); other forms such as `"UTC+9"` are an `invalid-time-zone`, and an offset and a named time zone are different time zones. The README now notes the Safari limitation above. The design decisions (18) now say that duplicate providers and duplicate calendars are deliberately treated differently. Results are unchanged
26
+
27
+ ### Migration
28
+
29
+ Check your code if one of these applies; otherwise no work is needed. The same steps are in [docs/migration.md](./docs/migration.md) (in Japanese).
30
+
31
+ - **You use your own holiday provider that returns holidays on more than 31 consecutive days, together with `"after-holiday"` rules.** Run `diagnoseCalendar` or `diagnoseSchedule` on your options and look for a `warning` with code `holiday-run-too-long`. If there is one, the first day after the run now throws, and so does every search that passes it and every calculation over a range that contains it: one lost day stops a count over the whole year. Write the long closure with `closedDates` or `closedAnnualDates` instead of returning it as holidays
32
+ - **You branch on `time-zone-conflict`.** Aliases of one time zone no longer throw on runtimes with Temporal. Remove code that relies on the exception
33
+ - **You pass a holiday provider, a calendar or a schedule directly to `createCalendar` in TypeScript.** Pass the provider as `{ holidayProvider: provider }`; a calendar or schedule was never read as options
34
+ - **You branch on error codes.** Make sure the new `holiday-run-too-long` falls into your default branch
35
+
36
+ ## [0.31.9] - 2026-11-14
37
+
38
+ This version removes two wrong diagnostics, makes evaluation and the option diagnostics faster, and documents how time zone names are compared. Results of calendars and schedules do not change.
39
+
40
+ ### Fixed
41
+
42
+ - The option diagnostics reported `never-matches` (a warning) for a recurring rule that does match, when its effective period is open on one side and the 28 years scanned from the other end reach a year divisible by 100 but not by 400 (such as 1900 or 2100). For example, `{ weekday: 1, nth: 5, months: [2], effectiveFrom: "2073-01-01" }` first matches on 2112-02-29, and removing the rule as the warning suggested changed that day. Such a period is now scanned for 56 years, which contain every combination of weekday and date, and `redundant` is decided over the same range. The guide and the design decisions (31) described this as a limit in 0.31.7 and now describe the new range; rules with `interval` or `cycle` remain an approximation across such a year. Only the wrong warning disappears (a wrong diagnostic may disappear in a patch version; design decisions 33)
43
+ - `diagnoseSchedule` returned a second `error`, a `time-zone-conflict` at the `calendar` of an nth-business-day rule, when the time zone of the schedule itself could not be determined (an invalid `timeZone`, or holiday providers with different time zones and no `timeZone`). It compared the calendar with a placeholder that the options do not mention (`"UTC"`, or the time zone of the first provider). It now returns only the error at `timeZone`, the one that `createSchedule` throws (design decisions 30). A conflict with a valid `timeZone` is reported as before
44
+ - Documentation: the guide, the type descriptions of `HolidayLookup.timeZone` and of `time-zone-conflict` in `KnownErrorCode`, and the design decisions (18) now say that `timeZone` returns the name the runtime's `Intl` reports, which can differ from the spelling in the options and from one runtime to another, and that time zones are compared by that name. Aliases of one time zone (such as `"UTC"` and `"Etc/UTC"`, or `"Asia/Kolkata"` and `"Asia/Calcutta"`) are therefore accepted on Node.js but are a `time-zone-conflict` on a runtime that does not turn aliases into one name (confirmed on Bun 1.4.3 and Safari 27.2). Results are unchanged. Write the same spelling wherever time zones must match; which time zones count as the same will be defined in the next minor version
45
+ - Documentation: the design decisions said that a mistyped option is a type error in TypeScript (8). That holds only for options written as an object literal: passing a holiday provider or a calendar itself as the options (`createCalendar(jp)`) compiles and makes a calendar without holidays, and the diagnostics report `unknown-option`. The design decisions also said that the supported years do not matter to the diagnostics (17) and that effective periods outside the scanned range are scanned (31); with `outOfRangePolicy: "throw"` only the supported years are scanned, as the guide said. The design decisions (18) now give the reasons why `combineCalendars` throws for fewer than two calendars and for the same calendar twice, and the guide says to remove duplicates before handling the case of one calendar. The bundle sizes in the README were measured again for 0.31.9
46
+
47
+ ### Changed
48
+
49
+ - Evaluating a day and the option diagnostics are faster. The date string of the day was parsed again by every step of the evaluation and by every rule; the last parsed date is now remembered. The parsed result depends only on the string, so results are unchanged (design decisions 16)
50
+
9
51
  ## [0.31.8] - 2026-11-13
10
52
 
11
53
  This version fixes one input that was silently accepted and corrects type descriptions and documents. Results of calls that were written correctly do not change.
@@ -959,7 +1001,9 @@ This version rebuilds the `redundant` diagnostic so that the reported rules can
959
1001
 
960
1002
  - 日本: 2026 年 2 月の官報(2027 年の春分・秋分の日)まで反映(`dataVersion: "2026-02"`、`confirmedThrough: 2027`)
961
1003
 
962
- [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.8...HEAD
1004
+ [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.0...HEAD
1005
+ [0.32.0]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.9...v0.32.0
1006
+ [0.31.9]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.8...v0.31.9
963
1007
  [0.31.8]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.7...v0.31.8
964
1008
  [0.31.7]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.6...v0.31.7
965
1009
  [0.31.6]: https://github.com/inohan77/bizdays-toolkit/compare/v0.31.5...v0.31.6
package/README.md CHANGED
@@ -23,7 +23,7 @@ A business-day calendar that combines public holidays with company or store clos
23
23
  - **Recurring rules**: "closed on the 3rd Wednesday", "every other Wednesday", "stocktaking on the last day of the month", "closed on Mondays, moved to the next non-holiday when Monday is a holiday", "the day after (or before) a holiday", "the last weekday before a bank holiday", shift cycles such as four days on and two days off, each with its own behaviour on holidays and an optional effective period
24
24
  - **Day-by-day values and combined calendars**: store hours that change by weekday, holiday and date; a business-day calendar made from such a schedule; and the days on which all (or any) of several calendars are open
25
25
  - **Option diagnostics**: `bizdays-toolkit/diagnose` lists rules that never apply, rules that are shadowed or redundant, rules that have ended, typos in option names and options with no business day at all, without throwing. One line in a test keeps options honest
26
- - **Lightweight, zero dependencies, time-zone safe**: about 14.0 KB min+gzip (about 15.8 KB with Japanese holidays, about 16.2 KB with UK bank holidays, about 14.9 KB with French holidays, about 15.0 KB with Singapore holidays; measured for 0.31.6). Standard JavaScript and `Intl` only, ESM with bundled types; tested on Node.js, Chrome, Firefox, Edge, Safari, Cloudflare Workers, Bun and Deno. Instants such as `Date` are converted to a civil date in the calendar's time zone before evaluation
26
+ - **Lightweight, zero dependencies, time-zone safe**: about 14.5 KB min+gzip (about 16.3 KB with Japanese holidays, about 16.7 KB with UK bank holidays, about 15.4 KB with French holidays, about 15.5 KB with Singapore holidays; measured for 0.32.0). Standard JavaScript and `Intl` only, ESM with bundled types; tested on Node.js, Chrome, Firefox, Edge, Safari, Cloudflare Workers, Bun and Deno (on Safari without Temporal, aliases of one time zone such as `"UTC"` and `"Etc/UTC"` are a `time-zone-conflict`: write the same spelling). Instants such as `Date` are converted to a civil date in the calendar's time zone before evaluation
27
27
  - **Extensible to other countries and regions**: holiday providers are pluggable through the `HolidayProvider` interface, and `bizdays-toolkit/provider` exposes the calendar arithmetic (nth weekday of a month, Easter, substitute days for holidays on a weekend) that most countries' holidays are built from
28
28
 
29
29
  ## Installation
@@ -2,7 +2,7 @@ import { addDays, lengthOfMonth, formatDate, fromDayNumber, toDayNumber, } from
2
2
  import { checkUnknownKeys, internalError, IssueCollector, describeValue, rangeError, withoutUndefined, } from "./errors.js";
3
3
  import { isOptionsObject } from "./options.js";
4
4
  import { renameKeys, writtenKey } from "./renamed.js";
5
- import { parseTimeOfDaySeconds, toCivil } from "./input.js";
5
+ import { distinctTimeZones, parseTimeOfDaySeconds, toCivil } from "./input.js";
6
6
  import { checkClosingDay, closingDayIn, closingMonth as calendarClosingMonth, dayOfMonth, formatMonth, isDayOfMonthValue, parseMonth, readsAsDate, shiftMonth, } from "./month.js";
7
7
  import { buildSchedule, compileAnnualRules, compileDateRules, compileHolidaySource, compileRecurringRules, createHolidayLookup, infoOfSchedule, valuesOfSchedule, isWeekday, mapDays, RECURRING_RULE_KEYS, jpUsage, } from "./schedule.js";
8
8
  export const CALENDAR_OPTION_KEYS = [
@@ -361,7 +361,7 @@ export function combineCalendars(calendars, options) {
361
361
  if (!Number.isInteger(searchDayLimit) || searchDayLimit < 1) {
362
362
  throw rangeError("invalid-option", "searchDayLimit must be a positive integer");
363
363
  }
364
- const zones = [...new Set(calendars.map((c) => c.timeZone))];
364
+ const zones = distinctTimeZones(calendars.map((c) => c.timeZone));
365
365
  if (zones.length > 1) {
366
366
  throw rangeError("time-zone-conflict", `Calendars use different time zones (${zones.join(", ")}); combine calendars with the same time zone`);
367
367
  }
@@ -14,11 +14,11 @@ export type DateString = string;
14
14
  * @public
15
15
  */
16
16
  export type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6;
17
- /** 年月日に分解する。形式または暦として不正なら RangeError */
17
+ /** 年月日に分解する。形式または暦として不正なら RangeError。返すオブジェクトは変更できない */
18
18
  export declare function parseDate(value: string): {
19
- year: number;
20
- month: number;
21
- day: number;
19
+ readonly year: number;
20
+ readonly month: number;
21
+ readonly day: number;
22
22
  };
23
23
  /**
24
24
  * "YYYY-MM-DD" として正しい暦日か。
package/dist/core/date.js CHANGED
@@ -2,7 +2,11 @@ import { describeValue, rangeError } from "./errors.js";
2
2
  const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
3
3
  const MS_PER_DAY = 86_400_000;
4
4
  const MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
5
+ let lastValue = "2000-01-01";
6
+ let lastParts = Object.freeze({ year: 2000, month: 1, day: 1 });
5
7
  export function parseDate(value) {
8
+ if (value === lastValue)
9
+ return lastParts;
6
10
  const m = typeof value === "string" ? DATE_RE.exec(value) : null;
7
11
  if (!m) {
8
12
  throw rangeError("invalid-date", `Invalid date string: ${describeValue(value)} (expected YYYY-MM-DD)`);
@@ -13,7 +17,8 @@ export function parseDate(value) {
13
17
  if (year < 1000 || month < 1 || month > 12 || day < 1 || day > lengthOfMonth(year, month)) {
14
18
  throw rangeError("invalid-date", `Invalid date: ${describeValue(value)}`);
15
19
  }
16
- return { year, month, day };
20
+ lastValue = value;
21
+ return (lastParts = Object.freeze({ year, month, day }));
17
22
  }
18
23
  export function isValidDate(input) {
19
24
  if (typeof input !== "string")
@@ -3,7 +3,7 @@ import { compileCalendarOptions } from "./calendar.js";
3
3
  import { internalError, InternalError, describeValue, IssueCollector, rangeError, } from "./errors.js";
4
4
  import { isOptionsObject } from "./options.js";
5
5
  import { RENAMED_KEYS, RENAMED_VALUES } from "./renamed.js";
6
- import { compileScheduleOptions, createBasis, createHolidayLookup, createResolver, inPeriod, MAX_HOLIDAY_RUN, jpUsage, matchMonthDay, matchPattern, isHolidayBasedRule, resultIgnoresHolidays, } from "./schedule.js";
6
+ import { compileScheduleOptions, createBasis, createHolidayLookup, createResolver, ignoreLostShift, lostShiftMessage, inPeriod, MAX_HOLIDAY_RUN, jpUsage, matchMonthDay, matchPattern, isHolidayBasedRule, resultIgnoresHolidays, } from "./schedule.js";
7
7
  function editDistance(a, b) {
8
8
  const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
9
9
  for (let i = 1; i <= a.length; i++) {
@@ -53,6 +53,28 @@ const MAX_WINDOW_YEARS = 200;
53
53
  const MAX_DATE_RULE_DAYS = 366 * MAX_WINDOW_YEARS;
54
54
  const atCalendarEdge = (n, error) => (n < MIN_DAY + MAX_HOLIDAY_RUN || n > MAX_DAY - MAX_HOLIDAY_RUN) &&
55
55
  error?.code === "out-of-range";
56
+ function openEndedDays(from, days) {
57
+ const lo = Math.max(from, MIN_DAY);
58
+ const hi = Math.min(from + days - 1, MAX_DAY);
59
+ if (lo > hi)
60
+ return days;
61
+ const last = yearOf(hi);
62
+ for (let y = Math.ceil(yearOf(lo) / 100) * 100; y <= last; y += 100)
63
+ if (y % 400 !== 0)
64
+ return Math.max(days, 2 * PATTERN_DAYS);
65
+ return days;
66
+ }
67
+ function periodSpan(rule, cycle) {
68
+ const { effectiveFrom, effectiveTo } = rule;
69
+ if (effectiveFrom === null) {
70
+ const to = effectiveTo;
71
+ return { from: to - openEndedDays(to - cycle + 1, cycle) + 1, to };
72
+ }
73
+ return {
74
+ from: effectiveFrom,
75
+ to: effectiveTo ?? effectiveFrom + openEndedDays(effectiveFrom, cycle) - 1,
76
+ };
77
+ }
56
78
  const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
57
79
  const lcm = (a, b) => (a / gcd(a, b)) * b;
58
80
  function patternCycle(rules) {
@@ -102,9 +124,9 @@ function scanWindow(source, rules, cycle) {
102
124
  for (const rule of rules) {
103
125
  if (rule.effectiveFrom === null && rule.effectiveTo === null)
104
126
  continue;
105
- const from = rule.effectiveFrom ?? rule.effectiveTo - cycle + 1;
106
- const to = Math.min(rule.effectiveTo ?? from + cycle - 1, from + 366 * MAX_WINDOW_YEARS - 1);
107
- ranges.push({ from: Math.max(from, MIN_DAY), to: Math.min(to, MAX_DAY) });
127
+ const span = periodSpan(rule, cycle);
128
+ const to = Math.min(span.to, span.from + 366 * MAX_WINDOW_YEARS - 1);
129
+ ranges.push({ from: Math.max(span.from, MIN_DAY), to: Math.min(to, MAX_DAY) });
108
130
  }
109
131
  }
110
132
  ranges.sort((a, b) => a.from - b.from);
@@ -140,10 +162,13 @@ function patternBits(rule) {
140
162
  return bits;
141
163
  }
142
164
  function matchesAnyDay(rule, cycle) {
143
- const start = rule.effectiveFrom ?? (rule.effectiveTo === null ? PATTERN_FROM : rule.effectiveTo - cycle + 1);
144
- const from = Math.max(start, MIN_DAY);
145
- const to = Math.min(rule.effectiveTo ?? Infinity, start + cycle - 1, MAX_DAY);
146
- for (let n = from; n <= to; n++)
165
+ const span = rule.effectiveFrom === null && rule.effectiveTo === null
166
+ ? { from: PATTERN_FROM, to: PATTERN_FROM + cycle - 1 }
167
+ : periodSpan(rule, cycle);
168
+ const to = rule.effectiveFrom !== null && rule.effectiveTo !== null
169
+ ? Math.min(span.to, span.from + openEndedDays(span.from, cycle) - 1)
170
+ : span.to;
171
+ for (let n = Math.max(span.from, MIN_DAY); n <= Math.min(to, MAX_DAY); n++)
147
172
  if (matchPattern(rule, fromDayNumber(n)))
148
173
  return true;
149
174
  return false;
@@ -271,7 +296,7 @@ function checkProviderData(c, source) {
271
296
  });
272
297
  return ok;
273
298
  }
274
- const UNJUDGEABLE = new Set(["out-of-range", "unconfirmed-holiday"]);
299
+ const UNJUDGEABLE = new Set(["out-of-range", "unconfirmed-holiday", "holiday-run-too-long"]);
275
300
  function guardBases(compiled, unknownMonths) {
276
301
  if (!compiled.recurring.some((r) => r.basis !== null && r.calendar !== null))
277
302
  return compiled;
@@ -399,6 +424,41 @@ export function unsureOf(compiled, unknown) {
399
424
  return overlaps(item.effectiveFrom, item.effectiveTo);
400
425
  };
401
426
  }
427
+ function checkLostShifts(c, compiled, lookup, window) {
428
+ const { source, recurring } = compiled;
429
+ const shifting = recurring.filter((r) => r.holidayOverlapPolicy === "after-holiday");
430
+ if (!window || source.providers.length === 0 || shifting.length === 0)
431
+ return;
432
+ const found = new Map();
433
+ const resolve = createResolver(compiled, lookup, (rule, date, origin) => {
434
+ if (!found.has(rule))
435
+ found.set(rule, lostShiftMessage(date, origin));
436
+ });
437
+ const skipping = shifting.some((r) => r.skipWeekdays !== null);
438
+ for (const { from, to } of window.ranges) {
439
+ const days = [];
440
+ for (let y = yearOf(from); y <= yearOf(to); y++)
441
+ for (const h of lookup.holidaysInYear(y))
442
+ days.push(toDayNumber(h.date));
443
+ for (let i = 0; i < days.length; i++) {
444
+ const back = MAX_HOLIDAY_RUN - 1;
445
+ if (!skipping && days[i - back] !== days[i] - back)
446
+ continue;
447
+ const last = Math.min(days[i] + 7, (days[i + 1] ?? Infinity) - 1, to, MAX_DAY);
448
+ for (let n = days[i] + 1; n <= last; n++) {
449
+ try {
450
+ resolve(fromDayNumber(n), false);
451
+ }
452
+ catch (error) {
453
+ if (!atCalendarEdge(n, error))
454
+ throw error;
455
+ }
456
+ }
457
+ }
458
+ }
459
+ for (const [rule, message] of found)
460
+ c.warning("holiday-run-too-long", rule.path, message, source.providers.length === 1 ? providerPath(source, 0) : undefined);
461
+ }
402
462
  export function dropUnsure(c, from, unsure, recorded, unknown) {
403
463
  for (const m of recorded)
404
464
  if (!unknown.months.has(m))
@@ -429,6 +489,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
429
489
  const cycle = patternCycle(recurring);
430
490
  const window = rulesScanWindow(compiled, cycle);
431
491
  const unused = new Set();
492
+ checkLostShifts(c, compiled, lookup, window);
432
493
  dates.forEach((rule, j) => {
433
494
  const fromYear = yearOf(rule.from);
434
495
  const toYear = yearOf(rule.to);
@@ -640,7 +701,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
640
701
  }
641
702
  }
642
703
  if (isCalendar && window && !dates.some((r) => r.value === true)) {
643
- const resolve = createResolver(without(compiled, null, true), lookup);
704
+ const resolve = createResolver(without(compiled, null, true), lookup, ignoreLostShift);
644
705
  let found = false;
645
706
  eachDay(window, (n) => {
646
707
  try {
@@ -698,7 +759,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
698
759
  };
699
760
  };
700
761
  const redundant = (rule, base, days, original) => {
701
- const resolve = createResolver(without(base, rule, false), lookup);
762
+ const resolve = createResolver(without(base, rule, false), lookup, ignoreLostShift);
702
763
  for (const n of days) {
703
764
  let value;
704
765
  try {
@@ -727,7 +788,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
727
788
  });
728
789
  const judgeDate = (rule) => {
729
790
  const base = current(true);
730
- const resolve = createResolver(base, lookup);
791
+ const resolve = createResolver(base, lookup, ignoreLostShift);
731
792
  const decided = [];
732
793
  const span = [];
733
794
  let checked = 0;
@@ -768,7 +829,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
768
829
  const decidedIn = (rule) => {
769
830
  if (!decided && window) {
770
831
  const map = new Map(candidates.map((r) => [r, new Set()]));
771
- const resolveNow = createResolver(current(counting.length > 0), lookup);
832
+ const resolveNow = createResolver(current(counting.length > 0), lookup, ignoreLostShift);
772
833
  eachDay(window, (n) => {
773
834
  let by;
774
835
  try {
@@ -788,7 +849,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
788
849
  const refresh = (affected) => {
789
850
  if (!decided)
790
851
  return;
791
- const resolveNow = createResolver(current(counting.length > 0), lookup);
852
+ const resolveNow = createResolver(current(counting.length > 0), lookup, ignoreLostShift);
792
853
  for (const n of affected) {
793
854
  if (!inWindow(n) || unjudged.has(n))
794
855
  continue;
@@ -799,7 +860,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
799
860
  decided.get(by)?.add(n);
800
861
  }
801
862
  };
802
- const originalNow = originalOf(createResolver(current(counting.length > 0), lookup));
863
+ const originalNow = originalOf(createResolver(current(counting.length > 0), lookup, ignoreLostShift));
803
864
  const unitsOf = new Map();
804
865
  const annualUnits = (rule) => {
805
866
  const known = unitsOf.get(rule);
@@ -862,7 +923,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
862
923
  }
863
924
  if (reported.size === 0)
864
925
  return;
865
- const resolveFinal = createResolver(current(true), lookup);
926
+ const resolveFinal = createResolver(current(true), lookup, ignoreLostShift);
866
927
  const relatedOf = (days) => {
867
928
  const paths = new Set();
868
929
  for (const n of days) {
@@ -32,7 +32,8 @@ export type KnownErrorCode =
32
32
  | "invalid-option"
33
33
  /**
34
34
  * 同じタイムゾーンでなければならないものが食い違う(1 つの設定の祝日の提供元どうしで、timeZone の指定がない。
35
- * 合成するカレンダーどうし。スケジュールと、第 n 営業日の規則の数える基準のカレンダー)
35
+ * 合成するカレンダーどうし。スケジュールと、第 n 営業日の規則の数える基準のカレンダー)。実行環境の Intl が返す名前が
36
+ * 同じかで比べるので、別名どうし("UTC" と "Etc/UTC" など)は、別名を同じ名前に直さない実行環境では食い違いになる
36
37
  */
37
38
  | "time-zone-conflict"
38
39
  /**
@@ -46,6 +47,12 @@ export type KnownErrorCode =
46
47
  | "invalid-provider"
47
48
  /** 祝日の提供元が返したデータの誤り */
48
49
  | "invalid-provider-data"
50
+ /**
51
+ * 祝日の連続が長すぎて、"after-holiday" の規則の日を連続が明けた日に振り替えられない(連続が 31 日を超えて届かない、
52
+ * または 367 日を超えて続き振替元を確かめられない)。その日の判定と、その日を通る探索・その日を含む期間の計算が投げる。
53
+ * 長い休業は祝日ではなく closedDates・closedAnnualDates で書く
54
+ */
55
+ | "holiday-run-too-long"
49
56
  /**
50
57
  * 営業日が見つからない(探索が searchDayLimit 日を超えた、月の営業日が第 n 営業日の n に足りない、カレンダーの締めの月に
51
58
  * 固有の期間がない)
@@ -29,6 +29,27 @@ export function validateTimeZone(timeZone) {
29
29
  throw rangeError("invalid-time-zone", `Invalid time zone: ${describeValue(timeZone)}`);
30
30
  }
31
31
  }
32
+ export function sameTimeZone(a, b) {
33
+ if (a === b)
34
+ return true;
35
+ const T = globalThis.Temporal;
36
+ if (T === undefined)
37
+ return false;
38
+ try {
39
+ const at = T.Instant.fromEpochMilliseconds(0);
40
+ return at.toZonedDateTimeISO(a).equals(at.toZonedDateTimeISO(b)) === true;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
46
+ export function distinctTimeZones(zones) {
47
+ const out = [];
48
+ for (const z of zones)
49
+ if (!out.some((o) => sameTimeZone(o, z)))
50
+ out.push(z);
51
+ return out;
52
+ }
32
53
  function wallParts(epochMilliseconds, timeZone) {
33
54
  const parts = formatterFor(timeZone).formatToParts(new Date(epochMilliseconds));
34
55
  const get = (type) => {
@@ -442,6 +442,8 @@ export interface ScheduleDateRange<Value> {
442
442
  }
443
443
  /**
444
444
  * 祝日の提供元とタイムゾーンの設定(スケジュールと営業日カレンダーで共通)。
445
+ * 祝日の提供元・作成済みのカレンダー・スケジュールをそのまま設定として渡す誤り(createCalendar(jp) など。提供元は
446
+ * holidayProvider に渡す)を型で止めるため、その 3 つがどれも持つ項目 holidaysInYear は書けない。
445
447
  * @public
446
448
  */
447
449
  export interface HolidaySourceOptions<Kind extends string = string> {
@@ -468,6 +470,7 @@ export interface HolidaySourceOptions<Kind extends string = string> {
468
470
  * 判定が祝日に依存する設定でだけ意味がある(条件はガイドの「Unconfirmed holidays」。decisions.md の 17 番)
469
471
  */
470
472
  readonly unconfirmedHolidayPolicy?: "accept" | "throw";
473
+ readonly holidaysInYear?: never;
471
474
  }
472
475
  /**
473
476
  * スケジュールの設定。
@@ -532,7 +535,11 @@ export interface ScheduleDayInfo<Value, Kind extends string = string> {
532
535
  * @public
533
536
  */
534
537
  export interface HolidayLookup<Kind extends string = string> {
535
- /** 日時の入力を暦日に変換するタイムゾーン */
538
+ /**
539
+ * 日時の入力を暦日に変換するタイムゾーン。実行環境の Intl が返す名前で、設定に書いた綴りと違うことがあり、実行環境によっても
540
+ * 違う("Asia/Kolkata" と書くと、Node.js では "Asia/Calcutta"、Bun では "Asia/Kolkata")。同じタイムゾーンかは、この名前が
541
+ * 同じかで比べる(違えば time-zone-conflict)
542
+ */
536
543
  readonly timeZone: string;
537
544
  /** 祝日の提供元 */
538
545
  readonly providers: readonly HolidayProvider<Kind>[];
@@ -3,7 +3,7 @@ import { checkUnknownKeys, describeValue, IssueCollector, rangeError, withoutUnd
3
3
  import { isOptionsObject } from "./options.js";
4
4
  import { checkNames } from "./names.js";
5
5
  import { RENAMED_VALUES, renameKeys, renameValue, writtenKey } from "./renamed.js";
6
- import { instantToCivil, isDate, toCivil, toDateTimeParts, toInstant, validateTimeZone, } from "./input.js";
6
+ import { distinctTimeZones, instantToCivil, isDate, sameTimeZone, toCivil, toDateTimeParts, toInstant, validateTimeZone, } from "./input.js";
7
7
  import { HOLIDAY_KEY_PATTERN } from "./types.js";
8
8
  const MONTH_DAY_RE = /^(\d{2})-(\d{2})$/;
9
9
  const MAX_DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
@@ -649,7 +649,7 @@ export function matchRecurring(rule, date, holidayOf, basis, fromJp) {
649
649
  export function createBasis(compiled, lookup) {
650
650
  if (!compiled.recurring.some((r) => r.businessDays !== null && r.basis === null))
651
651
  return undefined;
652
- const resolve = createResolver({ ...compiled, recurring: [] }, lookup);
652
+ const resolve = createResolver({ ...compiled, recurring: [] }, lookup, ignoreLostShift);
653
653
  return basisFromPredicate((date) => resolve(date, false).day.value === true);
654
654
  }
655
655
  function requiredValue(c) {
@@ -741,7 +741,7 @@ export function compileHolidaySource(c, options) {
741
741
  }
742
742
  }
743
743
  else {
744
- const zones = [...new Set(providers.map((p) => validateTimeZone(p.timeZone)))];
744
+ const zones = distinctTimeZones(providers.map((p) => validateTimeZone(p.timeZone)));
745
745
  if (zones.length > 1) {
746
746
  c.error("time-zone-conflict", "timeZone", `Holiday providers use different time zones (${zones.join(", ")}); specify timeZone`);
747
747
  }
@@ -987,18 +987,29 @@ export function compileScheduleOptions(c, options) {
987
987
  const annual = compileAnnualRules(c, "annualDates", o["annualDates"], requiredValue(c), false, true);
988
988
  const dates = compileDateRules(c, "dates", o["dates"], requiredValue(c), false, true);
989
989
  const recurring = compileRecurringRules(c, "recurringRules", o["recurringRules"], requiredValue(c), [...RECURRING_RULE_KEYS, "value"], "schedule", writtenKey(["source", "schedule"], written, "recurringRules"), jpUsage(source));
990
+ const zoneKnown = !c.issues.some((i) => i.severity === "error" && i.path === "timeZone");
990
991
  for (const rule of recurring) {
991
- if (rule.businessDays === null)
992
+ if (rule.businessDays === null || !zoneKnown)
992
993
  continue;
993
994
  const entry = o["recurringRules"][Number(/\[(\d+)\]$/.exec(rule.path)[1])];
994
995
  const tz = entry["calendar"].timeZone;
995
- if (tz !== source.timeZone) {
996
+ if (!sameTimeZone(tz, source.timeZone)) {
996
997
  c.error("time-zone-conflict", `${rule.path}.calendar`, `the calendar's time zone ${tz} differs from the schedule's ${source.timeZone}`);
997
998
  }
998
999
  }
999
1000
  return { source, weekly, holiday, annual, dates, recurring };
1000
1001
  }
1001
1002
  export const MAX_HOLIDAY_RUN = 31;
1003
+ const MAX_HOLIDAY_RUN_SCAN = 367;
1004
+ const MIN_DAY_NUMBER = toDayNumber("1000-01-01");
1005
+ export const lostShiftMessage = (date, origin) => (origin === undefined
1006
+ ? `no day can be moved to ${date}: the run of holidays before it is longer than ${MAX_HOLIDAY_RUN_SCAN} days, so the day to move cannot be determined`
1007
+ : `the day ${origin} cannot be moved to ${date}: the run of holidays between them is longer than ${MAX_HOLIDAY_RUN} days`) +
1008
+ " (write a long closure with closedDates or closedAnnualDates, not as holidays)";
1009
+ export const throwLostShift = (rule, date, origin) => {
1010
+ throw rangeError("holiday-run-too-long", `${rule.path}: ${lostShiftMessage(date, origin)}`);
1011
+ };
1012
+ export const ignoreLostShift = () => { };
1002
1013
  export function matchMonthDay(rule, monthDay) {
1003
1014
  return rule.from <= rule.to
1004
1015
  ? monthDay >= rule.from && monthDay <= rule.to
@@ -1014,7 +1025,7 @@ export function resultIgnoresHolidays(compiled) {
1014
1025
  r.holidayOverlapPolicy === "after-holiday" ||
1015
1026
  r.holidayOverlapPolicy === "over-holiday"));
1016
1027
  }
1017
- export function createResolver(compiled, lookup) {
1028
+ export function createResolver(compiled, lookup, onLostShift) {
1018
1029
  const { weekly, holiday: holidayRule, annual, dates, recurring } = compiled;
1019
1030
  const hasShift = recurring.some((r) => r.holidayOverlapPolicy === "after-holiday");
1020
1031
  const holidayUnused = resultIgnoresHolidays(compiled);
@@ -1029,6 +1040,20 @@ export function createResolver(compiled, lookup) {
1029
1040
  if (matchRecurring(rule, prev, holidayOfNeighbour, undefined, lookup.fromJp))
1030
1041
  return prev;
1031
1042
  }
1043
+ const first = toDayNumber(date) - MAX_HOLIDAY_RUN_SCAN;
1044
+ for (let n = toDayNumber(date) - MAX_HOLIDAY_RUN - 1; n >= MIN_DAY_NUMBER; n--) {
1045
+ if (n < first) {
1046
+ onLostShift(rule, date, undefined);
1047
+ return undefined;
1048
+ }
1049
+ const prev = fromDayNumber(n);
1050
+ if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOf(prev)))
1051
+ return undefined;
1052
+ if (matchRecurring(rule, prev, holidayOfNeighbour, undefined, lookup.fromJp)) {
1053
+ onLostShift(rule, date, prev);
1054
+ return undefined;
1055
+ }
1056
+ }
1032
1057
  return undefined;
1033
1058
  }
1034
1059
  return function resolve(date, withHoliday = true) {
@@ -1106,7 +1131,7 @@ export function infoOfSchedule(schedule) {
1106
1131
  }
1107
1132
  export function buildSchedule(compiled) {
1108
1133
  const lookup = createHolidayLookup(compiled.source);
1109
- const resolve = createResolver(compiled, lookup);
1134
+ const resolve = createResolver(compiled, lookup, throwLostShift);
1110
1135
  const info = (date) => resolve(date).day;
1111
1136
  const values = Object.freeze(typeof compiled.holiday === "object" && "value" in compiled.holiday
1112
1137
  ? [...compiled.weekly, compiled.holiday.value]
@@ -38,9 +38,9 @@ export interface Holiday<Kind extends string = string> {
38
38
  * holidaysInYear が返すデータは、年ごとに初めて使うときに検証され、誤りがあれば
39
39
  * code: "invalid-provider-data" の例外になる。返した祝日は、契約の項目(date・name・nameEn・names・
40
40
  * kind・confirmed・key)だけを持つ変更できないオブジェクトに複製される。
41
- * 祝日が長く続くとき、"after-holiday" の規則は、本来の日が振り替わる先の日より 31 日を超えて前にあると振り替わらない
42
- * (振替元をさかのぼるのは 31 日まで。祝日の前後の規則は連続の長さによらず当てはまる。長い休業は closedDates・
43
- * closedAnnualDates で書く。decisions.md の 24 番)。
41
+ * 祝日が長く続くとき、"after-holiday" の規則の本来の日が、振り替わる先の日より 31 日を超えて前にあると振り替えられず、
42
+ * 連続が明けた日の判定が code: "holiday-run-too-long" の例外になる(振替元をさかのぼるのは 31 日まで。祝日の前後の規則は
43
+ * 連続の長さによらず当てはまる。長い休業は closedDates・closedAnnualDates で書く。decisions.md の 24 番)。
44
44
  *
45
45
  * 項目を足すときのバージョンは RELEASING.md の区分の表による。1.0.0 以降、マイナーバージョンで足す項目は省略可能なものに限る
46
46
  * (必須にすると、自作の提供元が型エラーになるため)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bizdays-toolkit",
3
- "version": "0.31.8",
3
+ "version": "0.32.0",
4
4
  "description": "Holidays, business-day calendar and day-by-day schedules (e.g. store hours) with time zone support. Japanese holidays verified against the Cabinet Office data; UK bank holidays (England, Wales, Scotland, Northern Ireland) verified against GOV.UK and The Gazette; French public holidays (metropole, Alsace-Moselle) verified against data.gouv.fr; Singapore public holidays verified against data.gov.sg. / 祝日と営業日のカレンダー(タイムゾーン対応・日本の祝日は内閣府、英国の bank holidays は GOV.UK と The Gazette、フランスの祝日は data.gouv.fr、シンガポールの祝日は data.gov.sg のデータで全日照合)",
5
5
  "keywords": [
6
6
  "bank-holidays",