Initial Commit

This commit is contained in:
2026-05-27 23:47:53 +01:00
parent fbc70f96e6
commit 9b28db724f
18103 changed files with 1600554 additions and 0 deletions

View File

@@ -0,0 +1,100 @@
# business-days
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
The `business-days` module provides a complete suite of working-day arithmetic functions for `@suaveplan/datetime`. It models "business day" as any day that is neither in the caller-supplied `weekendDays` set (default: Sunday and Saturday) nor in the caller-supplied `holidays` list. This allows the same API to serve different jurisdictions and corporate calendars without baking in any cultural assumptions.
All functions accept the polymorphic `DateInput` type and delegate to `toDate` for coercion, so callers can pass ISO strings, epoch milliseconds, or `Date` objects interchangeably.
## Features
- `isBusinessDay` — predicate for whether a given date is a working day
- `nextBusinessDay` / `previousBusinessDay` — scan forward/backward for the nearest working day
- `addBusinessDays` / `subtractBusinessDays` — advance or retreat by an exact count of working days
- `businessDaysBetween` — count working days in a half-open interval `[start, end)`
- Configurable `weekendDays` (any subset of 0–6)
- Holiday exclusion via an `Date[]` array
- Cooperative cancellation via `AbortSignal` (checked every 256 iterations in `businessDaysBetween`)
- OTel counter via `recordBusinessDaysBetween`
## Usage: Basic Example
```ts
import { isBusinessDay, addBusinessDays } from "@suaveplan/datetime/business-days";
// Simple weekday check
console.log(isBusinessDay("2024-03-18")); // true (Monday)
console.log(isBusinessDay("2024-03-16")); // false (Saturday)
// Advance 5 business days
const result = addBusinessDays("2024-03-18", 5);
console.log(result.toDateString()); // Fri Mar 29 2024 (skips weekend)
```
## Usage: Advanced Example
```ts
import {
businessDaysBetween,
nextBusinessDay,
} from "@suaveplan/datetime/business-days";
const nyseHolidays = [
new Date("2024-01-01"), // New Year's Day
new Date("2024-07-04"), // Independence Day
];
// How many NYSE trading days in Q1 2024?
const q1 = businessDaysBetween("2024-01-01", "2024-04-01", {
holidays: nyseHolidays,
});
console.log(q1); // ~62 trading days
// Cooperative cancellation
const controller = new AbortController();
setTimeout(() => controller.abort(), 10);
const days = businessDaysBetween("2020-01-01", "2030-01-01", {
signal: controller.signal,
});
console.log(days); // partial count, aborted after ~256 iterations
```
## API Reference
### `isBusinessDay(date: DateInput, opts?: BusinessDayOptions): boolean`
Returns `true` when `date` is not a weekend day and not a holiday.
- `opts.weekendDays` — default `[0, 6]` (Sun, Sat)
- `opts.holidays` — list of `Date` objects to exclude
### `nextBusinessDay(date: DateInput, opts?: BusinessDayOptions): Date`
Returns the first business day strictly after `date`.
### `previousBusinessDay(date: DateInput, opts?: BusinessDayOptions): Date`
Returns the first business day strictly before `date`.
### `addBusinessDays(date: DateInput, n: number, opts?: BusinessDayOptions): Date`
Advance `date` by exactly `|n|` business days. Negative `n` moves backward.
### `subtractBusinessDays(date: DateInput, n: number, opts?: BusinessDayOptions): Date`
Move `date` backward by exactly `n` business days. Delegates to `addBusinessDays(date, -n)`.
### `businessDaysBetween(start: DateInput, end: DateInput, opts?: BusinessDayOptions): number`
Count business days in `[start, end)`. Returns a negative number when `end < start`. Checks `opts.signal` every 256 iterations.
## Implementation Notes
Holiday lookup uses a `Set<string>` keyed by `"YYYY-M-D"` (local time) built once per call. This is O(1) per day check and avoids allocating `Date` objects for the comparison.
All date arithmetic is performed at local-midnight epoch millis to prevent time-of-day accumulation errors across DST transitions. The `midnight()` helper normalises any input to 00:00:00.000 local time before iteration begins.
`addBusinessDays(d, 0)` returns the local midnight of `d` regardless of whether `d` itself is a business day, because zero steps means no movement.

View File

@@ -0,0 +1,219 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import * as fc from "fast-check";
import {
addBusinessDays,
businessDaysBetween,
isBusinessDay,
nextBusinessDay,
previousBusinessDay,
subtractBusinessDays,
} from "./business-days.js";
describe("isBusinessDay", () => {
it("Monday is a business day", { timeout: 5000 }, () => {
expect(isBusinessDay(new Date(2024, 2, 18))).toBe(true); // Mon
});
it("Saturday is not a business day", { timeout: 5000 }, () => {
expect(isBusinessDay(new Date(2024, 2, 16))).toBe(false); // Sat
});
it("Sunday is not a business day", { timeout: 5000 }, () => {
expect(isBusinessDay(new Date(2024, 2, 17))).toBe(false); // Sun
});
it("holidays are excluded", { timeout: 5000 }, () => {
const holiday = new Date(2024, 2, 18); // Mon
expect(isBusinessDay(holiday, { holidays: [holiday] })).toBe(false);
});
it("custom weekendDays", { timeout: 5000 }, () => {
// Only Friday off
expect(isBusinessDay(new Date(2024, 2, 15), { weekendDays: [5] })).toBe(
false
); // Fri
expect(isBusinessDay(new Date(2024, 2, 16), { weekendDays: [5] })).toBe(
true
); // Sat
});
});
describe("nextBusinessDay", () => {
it("Friday → Monday (skips weekend)", { timeout: 5000 }, () => {
const fri = new Date(2024, 2, 15); // Fri
const result = nextBusinessDay(fri);
expect(result.getDay()).toBe(1); // Mon
expect(result.getDate()).toBe(18);
});
it("skips holidays", { timeout: 5000 }, () => {
const thu = new Date(2024, 2, 14); // Thu
const fri = new Date(2024, 2, 15); // Fri
const result = nextBusinessDay(thu, { holidays: [fri] });
expect(result.getDay()).toBe(1); // Mon
});
it("Monday → Tuesday", { timeout: 5000 }, () => {
const mon = new Date(2024, 2, 18);
const result = nextBusinessDay(mon);
expect(result.getDate()).toBe(19);
});
});
describe("previousBusinessDay", () => {
it("Monday → Friday (skips weekend)", { timeout: 5000 }, () => {
const mon = new Date(2024, 2, 18); // Mon
const result = previousBusinessDay(mon);
expect(result.getDay()).toBe(5); // Fri
expect(result.getDate()).toBe(15);
});
it("skips holidays", { timeout: 5000 }, () => {
const tue = new Date(2024, 2, 19); // Tue
const mon = new Date(2024, 2, 18); // Mon
const result = previousBusinessDay(tue, { holidays: [mon] });
expect(result.getDay()).toBe(5); // Fri
});
});
describe("addBusinessDays", () => {
it("adds 5 business days from Monday", { timeout: 5000 }, () => {
const mon = new Date(2024, 2, 18); // Mon Mar 18
const result = addBusinessDays(mon, 5);
// Mon+5 business = Fri Mar 22 → actually Mon, Tue, Wed, Thu, Fri = Mar 22
expect(result.getDate()).toBe(25); // next Mon because Mon+5 = Mon
// Let's verify: Mon→Tue→Wed→Thu→Fri = 5 days, result = Fri Mar 22
// Actually counting: step 1=Tue, 2=Wed, 3=Thu, 4=Fri, 5=Mon(next week)
// Mon + skip weekends: Tue(1), Wed(2), Thu(3), Fri(4), Mon(5) = Mar 25
expect(result.getDay()).toBe(1); // Monday
});
it("n=0 returns local midnight of same date", { timeout: 5000 }, () => {
const d = new Date(2024, 2, 18, 14, 30, 0);
const result = addBusinessDays(d, 0);
expect(result.getDate()).toBe(18);
expect(result.getHours()).toBe(0);
});
it("negative n moves backward", { timeout: 5000 }, () => {
const wed = new Date(2024, 2, 20); // Wed
const result = addBusinessDays(wed, -2);
expect(result.getDay()).toBe(1); // Mon
expect(result.getDate()).toBe(18);
});
it("result is always a business day (property test)", {
timeout: 30000,
}, () => {
fc.assert(
fc.property(
fc.date({
min: new Date("2020-01-01"),
max: new Date("2025-12-31"),
}),
fc.integer({ min: 1, max: 30 }),
(date, n) => {
const result = addBusinessDays(date, n);
expect(isBusinessDay(result)).toBe(true);
}
),
{ numRuns: 200 }
);
});
it("result is always a business day going backward (property test)", {
timeout: 30000,
}, () => {
fc.assert(
fc.property(
fc.date({
min: new Date("2020-01-01"),
max: new Date("2025-12-31"),
}),
fc.integer({ min: 1, max: 30 }),
(date, n) => {
const result = addBusinessDays(date, -n);
expect(isBusinessDay(result)).toBe(true);
}
),
{ numRuns: 200 }
);
});
});
describe("subtractBusinessDays", () => {
it("delegates to addBusinessDays with -n", { timeout: 5000 }, () => {
const wed = new Date(2024, 2, 20);
expect(subtractBusinessDays(wed, 2).getTime()).toBe(
addBusinessDays(wed, -2).getTime()
);
});
});
describe("businessDaysBetween", () => {
it("same date returns 0", { timeout: 5000 }, () => {
const d = new Date(2024, 2, 18);
expect(businessDaysBetween(d, d)).toBe(0);
});
it("Mon to Fri = 4 business days (exclusive of end)", {
timeout: 5000,
}, () => {
// [Mon, Fri) = Mon, Tue, Wed, Thu = 4 business days
const mon = new Date(2024, 2, 18);
const fri = new Date(2024, 2, 22);
expect(businessDaysBetween(mon, fri)).toBe(4);
});
it("Mon to Sat = 5 business days (Mon-Fri)", { timeout: 5000 }, () => {
// [Mon, Sat) = Mon, Tue, Wed, Thu, Fri = 5 business days
const mon = new Date(2024, 2, 18);
const sat = new Date(2024, 2, 23);
expect(businessDaysBetween(mon, sat)).toBe(5);
});
it("Fri to Mon = 1 business day (exclusive of end)", {
timeout: 5000,
}, () => {
// [Fri, Mon) = just Fri = 1 business day
const fri = new Date(2024, 2, 15);
const mon = new Date(2024, 2, 18);
expect(businessDaysBetween(fri, mon)).toBe(1);
});
it("end before start returns negative", { timeout: 5000 }, () => {
// [Mon, Fri) = 4, reversed = -4
const mon = new Date(2024, 2, 18);
const fri = new Date(2024, 2, 22);
expect(businessDaysBetween(fri, mon)).toBe(-4);
});
it("excludes holidays", { timeout: 5000 }, () => {
// [Mon, Sat) = 5, minus Wed holiday = 4
const mon = new Date(2024, 2, 18);
const sat = new Date(2024, 2, 23);
const wed = new Date(2024, 2, 20);
expect(businessDaysBetween(mon, sat, { holidays: [wed] })).toBe(4);
});
it("respects abort signal", { timeout: 5000 }, () => {
const controller = new AbortController();
controller.abort();
// Should not throw, just return partial or 0
const start = new Date(2020, 0, 1);
const end = new Date(2025, 0, 1);
const result = businessDaysBetween(start, end, {
signal: controller.signal,
});
expect(typeof result).toBe("number");
});
it("handles custom weekend days", { timeout: 5000 }, () => {
// Only Friday is weekend
const mon = new Date(2024, 2, 18);
const sat = new Date(2024, 2, 23);
// Mon,Tue,Wed,Thu are business (Fri excluded), Sat counts
const count = businessDaysBetween(mon, sat, { weekendDays: [5] });
expect(count).toBe(4); // Mon, Tue, Wed, Thu (Fri excluded)
});
});

View File

@@ -0,0 +1,209 @@
import type { Clock } from "@suaveplan/types";
import { toDate } from "../calendar/calendar.js";
import { recordBusinessDaysBetween } from "../otel/datetime-otel.js";
import type {
BusinessDayOptions,
DateInput,
Weekday,
} from "../types/datetime.types.js";
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
const DEFAULT_WEEKEND: ReadonlyArray<Weekday> = [0, 6]; // Sun, Sat
const MS_IN_DAY = 24 * 60 * 60 * 1000;
/** Strip time portion; return local-midnight epoch for `d`. */
function midnight(d: Date): number {
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
0,
0,
0,
0
).getTime();
}
/** Format a date as "YYYY-M-D" for cheap holiday set membership. */
function dayKey(d: Date): string {
return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
}
/** Build a set of holiday keys from the options list. */
function buildHolidaySet(holidays?: Date[]): Set<string> {
const s = new Set<string>();
for (const h of holidays ?? []) {
s.add(dayKey(h));
}
return s;
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/**
* Returns `true` when `date` is a working day (not a weekend, not a holiday).
*
* @param date - The date to test.
* @param opts - Optional `weekendDays` (default Sun/Sat), `holidays`, `clock`.
*/
export function isBusinessDay(
date: DateInput,
opts?: BusinessDayOptions
): boolean {
const d = toDate(date);
const weekendDays: ReadonlyArray<Weekday> =
opts?.weekendDays ?? DEFAULT_WEEKEND;
const holidays = buildHolidaySet(opts?.holidays);
const dow = d.getDay() as Weekday;
if ((weekendDays as number[]).includes(dow)) return false;
if (holidays.has(dayKey(d))) return false;
return true;
}
/**
* Returns the next business day after `date` (exclusive of `date` itself).
*
* Iterates forward one day at a time until a business day is found.
*/
export function nextBusinessDay(
date: DateInput,
opts?: BusinessDayOptions
): Date {
const weekendDays: ReadonlyArray<Weekday> =
opts?.weekendDays ?? DEFAULT_WEEKEND;
const holidays = buildHolidaySet(opts?.holidays);
let t = midnight(toDate(date)) + MS_IN_DAY;
for (;;) {
const candidate = new Date(t);
const dow = candidate.getDay() as Weekday;
if (
!(weekendDays as number[]).includes(dow) &&
!holidays.has(dayKey(candidate))
) {
return candidate;
}
t += MS_IN_DAY;
}
}
/**
* Returns the previous business day before `date` (exclusive of `date` itself).
*
* Iterates backward one day at a time.
*/
export function previousBusinessDay(
date: DateInput,
opts?: BusinessDayOptions
): Date {
const weekendDays: ReadonlyArray<Weekday> =
opts?.weekendDays ?? DEFAULT_WEEKEND;
const holidays = buildHolidaySet(opts?.holidays);
let t = midnight(toDate(date)) - MS_IN_DAY;
for (;;) {
const candidate = new Date(t);
const dow = candidate.getDay() as Weekday;
if (
!(weekendDays as number[]).includes(dow) &&
!holidays.has(dayKey(candidate))
) {
return candidate;
}
t -= MS_IN_DAY;
}
}
/**
* Advance `date` by exactly `n` business days, skipping weekends and holidays.
*
* Negative `n` moves backward.
*/
export function addBusinessDays(
date: DateInput,
n: number,
opts?: BusinessDayOptions
): Date {
const weekendDays: ReadonlyArray<Weekday> =
opts?.weekendDays ?? DEFAULT_WEEKEND;
const holidays = buildHolidaySet(opts?.holidays);
let t = midnight(toDate(date));
const step = n >= 0 ? MS_IN_DAY : -MS_IN_DAY;
let remaining = Math.abs(n);
while (remaining > 0) {
t += step;
const candidate = new Date(t);
const dow = candidate.getDay() as Weekday;
if (
!(weekendDays as number[]).includes(dow) &&
!holidays.has(dayKey(candidate))
) {
remaining -= 1;
}
}
return new Date(t);
}
/**
* Move `date` backward by exactly `n` business days.
*
* Equivalent to `addBusinessDays(date, -n)`.
*/
export function subtractBusinessDays(
date: DateInput,
n: number,
opts?: BusinessDayOptions
): Date {
return addBusinessDays(date, -n, opts);
}
/**
* Count the number of business days between `start` (inclusive) and `end`
* (exclusive). Returns a negative number when `end` is before `start`.
*
* Checks `opts.signal` every 256 iterations for cooperative cancellation.
*/
export function businessDaysBetween(
start: DateInput,
end: DateInput,
opts?: BusinessDayOptions
): number {
const weekendDays: ReadonlyArray<Weekday> =
opts?.weekendDays ?? DEFAULT_WEEKEND;
const holidays = buildHolidaySet(opts?.holidays);
const signal = opts?.signal;
let t = midnight(toDate(start));
const endT = midnight(toDate(end));
if (t === endT) return 0;
const forward = t < endT;
const step = forward ? MS_IN_DAY : -MS_IN_DAY;
let count = 0;
let iterations = 0;
while (forward ? t < endT : t > endT) {
const candidate = new Date(t);
const dow = candidate.getDay() as Weekday;
if (
!(weekendDays as number[]).includes(dow) &&
!holidays.has(dayKey(candidate))
) {
count += 1;
}
t += step;
iterations += 1;
if (iterations % 256 === 0 && signal?.aborted) break;
}
recordBusinessDaysBetween(iterations);
return forward ? count : -count;
}
// Re-export Clock type for consumers
export type { Clock };

View File

@@ -0,0 +1,9 @@
export {
addBusinessDays,
businessDaysBetween,
type Clock,
isBusinessDay,
nextBusinessDay,
previousBusinessDay,
subtractBusinessDays,
} from "./business-days";

View File

@@ -0,0 +1,99 @@
# calendar-boundary
## Purpose
`calendar-boundary` provides `startOf` and `endOf` functions for `@suaveplan/datetime`, computing the precise first and last moments of any calendar unit (year, month, week, day, hour, minute, second, or millisecond) for a given date. These are the building blocks for date-range queries, fiscal period calculations, and UI calendar display logic.
Both functions are pure and stateless. They return new `Date` objects without mutating their inputs and operate in local time.
## Features
- `startOf` — first moment of the given unit (midnight for day, 00:00:00.000 for hours, etc.)
- `endOf` — last millisecond of the given unit (23:59:59.999 for day)
- Supports all `DurationUnit` values: `years`, `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`, `milliseconds`
- `weeks` uses Sunday as the week start (matching `Date.prototype.getDay()`)
- `BoundaryOptions` interface with optional `clock` for future extension
- `milliseconds` unit returns the date unchanged (identity)
## Usage: Basic Example
```ts
import { startOf, endOf } from "@suaveplan/datetime";
const d = new Date(2024, 2, 15, 14, 30, 45, 500); // Mar 15 2024 14:30:45.500
const dayStart = startOf(d, "days");
// 2024-03-15 00:00:00.000
const monthEnd = endOf(d, "months");
// 2024-03-31 23:59:59.999
```
## Usage: Advanced Example
```ts
import { startOf, endOf } from "@suaveplan/datetime";
// Fiscal year boundaries
const q1Start = startOf("2024-03-15", "years"); // Jan 1 2024
const q1End = endOf("2024-03-31", "months"); // Mar 31 2024 23:59:59.999
// Current week range (Sunday–Saturday)
const today = new Date();
const weekStart = startOf(today, "weeks");
const weekEnd = endOf(today, "weeks");
// Hour slot boundaries
const slotStart = startOf(new Date(2024, 0, 1, 9, 45, 0), "hours");
// 2024-01-01 09:00:00.000
const slotEnd = endOf(new Date(2024, 0, 1, 9, 45, 0), "hours");
// 2024-01-01 09:59:59.999
```
## API Reference
### `BoundaryOptions`
```ts
interface BoundaryOptions {
clock?: Clock;
}
```
Reserved for future use (e.g. timezone-aware boundaries). Currently unused in the function bodies.
### `startOf(date: DateInput, unit: DurationUnit, opts?: BoundaryOptions): Date`
Returns the first moment of the `unit` period containing `date`.
| Unit | Result |
|------|--------|
| `years` | Jan 1 00:00:00.000 |
| `months` | 1st of month 00:00:00.000 |
| `weeks` | Sunday of the week 00:00:00.000 |
| `days` | midnight 00:00:00.000 |
| `hours` | :00:00.000 of the hour |
| `minutes` | :00.000 of the minute |
| `seconds` | .000 of the second |
| `milliseconds` | unchanged |
### `endOf(date: DateInput, unit: DurationUnit, opts?: BoundaryOptions): Date`
Returns the last millisecond of the `unit` period containing `date`.
| Unit | Result |
|------|--------|
| `years` | Dec 31 23:59:59.999 |
| `months` | Last day 23:59:59.999 |
| `weeks` | Saturday of the week 23:59:59.999 |
| `days` | 23:59:59.999 |
| `hours` | :59:59.999 |
| `minutes` | :59.999 |
| `seconds` | .999 |
| `milliseconds` | unchanged |
## Implementation Notes
`startOf("weeks")` subtracts `date.getDay()` days (0 = Sunday) to find the Sunday anchor. `endOf("weeks")` adds `6 - date.getDay()` to reach Saturday. This matches the JavaScript `Date.getDay()` convention of Sunday = 0. Callers needing Monday-start weeks should offset by one day using `addDuration`.
`endOf("months")` calls `daysInMonth` to find the last valid day of the month, correctly handling February on leap years.

View File

@@ -0,0 +1,185 @@
import type { Clock } from "@suaveplan/types";
import type { DateInput, DurationUnit } from "../types/datetime.types.js";
import { daysInMonth, toDate } from "./calendar-core.js";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const DAYS_IN_WEEK = 7;
// ---------------------------------------------------------------------------
// Public: BoundaryOptions
// ---------------------------------------------------------------------------
/** Options for `startOf` / `endOf`. */
export interface BoundaryOptions {
clock?: Clock;
}
// ---------------------------------------------------------------------------
// Public: startOf
// ---------------------------------------------------------------------------
/**
* Returns the start of the given `unit` for `date`.
*
* Supported units: `years`, `months`, `weeks`, `days`, `hours`, `minutes`,
* `seconds`. `milliseconds` returns the date unchanged.
*/
export function startOf(
date: DateInput,
unit: DurationUnit,
_opts?: BoundaryOptions
): Date {
const d = toDate(date);
switch (unit) {
case "years":
return new Date(d.getFullYear(), 0, 1, 0, 0, 0, 0);
case "months":
return new Date(d.getFullYear(), d.getMonth(), 1, 0, 0, 0, 0);
case "weeks": {
const dow = d.getDay(); // 0=Sun
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate() - dow,
0,
0,
0,
0
);
}
case "days":
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
0,
0,
0,
0
);
case "hours":
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
0,
0,
0
);
case "minutes":
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
0,
0
);
case "seconds":
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds(),
0
);
case "milliseconds":
return new Date(d.getTime());
}
}
// ---------------------------------------------------------------------------
// Public: endOf
// ---------------------------------------------------------------------------
/**
* Returns the end of the given `unit` for `date` (last millisecond).
*
* Supported units: `years`, `months`, `weeks`, `days`, `hours`, `minutes`,
* `seconds`. `milliseconds` returns the date unchanged.
*/
export function endOf(
date: DateInput,
unit: DurationUnit,
_opts?: BoundaryOptions
): Date {
const d = toDate(date);
switch (unit) {
case "years":
return new Date(d.getFullYear(), 11, 31, 23, 59, 59, 999);
case "months": {
const lastDay = daysInMonth(d.getFullYear(), d.getMonth() + 1);
return new Date(
d.getFullYear(),
d.getMonth(),
lastDay,
23,
59,
59,
999
);
}
case "weeks": {
const dow = d.getDay();
const daysUntilSat = DAYS_IN_WEEK - 1 - dow;
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate() + daysUntilSat,
23,
59,
59,
999
);
}
case "days":
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
23,
59,
59,
999
);
case "hours":
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
59,
59,
999
);
case "minutes":
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
59,
999
);
case "seconds":
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
d.getHours(),
d.getMinutes(),
d.getSeconds(),
999
);
case "milliseconds":
return new Date(d.getTime());
}
}

View File

@@ -0,0 +1,82 @@
# calendar-core
## Purpose
`calendar-core` provides the foundational date primitives for `@suaveplan/datetime`: coercing heterogeneous `DateInput` values into `Date` objects, predicates for same-day and same-month equality, leap year detection, and days-in-month calculation. These are the lowest-level building blocks consumed by every other calendar sub-module.
All functions are pure and stateless. They accept local-time values and return local-time `Date` objects. There are no side effects and no external dependencies beyond `@suaveplan/error`.
## Features
- `toDate` — coerce `Date | string | number` to `Date`, throws `DatetimeError` for invalid inputs
- `asTimezone` — brands a raw string as the opaque `Timezone` type
- `isLeapYear` — true for proleptic Gregorian leap years
- `daysInMonth` — correct day-count for any month, including February on leap years
- `isSameDay` — calendar equality predicate (year + month + date)
- `isSameMonth` — calendar month equality predicate (year + month)
## Usage: Basic Example
```ts
import { toDate, isLeapYear, daysInMonth, isSameDay } from "@suaveplan/datetime";
const d = toDate("2024-02-15");
console.log(isLeapYear(2024)); // true
console.log(daysInMonth(2024, 2)); // 29
console.log(isSameDay(d, new Date(2024, 1, 15))); // true
```
## Usage: Advanced Example
```ts
import { toDate, isSameMonth, asTimezone } from "@suaveplan/datetime";
const jan1 = toDate(new Date(2024, 0, 1));
const jan31 = toDate("2024-01-31");
const feb1 = toDate(1706745600000); // epoch ms for 2024-02-01
console.log(isSameMonth(jan1, jan31)); // true
console.log(isSameMonth(jan31, feb1)); // false
// Error on invalid input
try {
toDate("not-a-date");
} catch (e) {
console.log((e as { code: string }).code); // DATETIME.PARSE.INVALID_INPUT
}
const tz = asTimezone("America/New_York");
```
## API Reference
### `toDate(input: DateInput): Date`
Coerce `input` to a `Date`. Accepts `Date`, ISO string, or epoch millis.
Throws `DatetimeError("DATETIME.PARSE.INVALID_INPUT")` for unparseable strings or `NaN` inputs.
### `asTimezone(tz: string): Timezone`
Cast `tz` to the branded `Timezone` type. No runtime validation is performed.
### `isLeapYear(year: number): boolean`
Returns `true` for proleptic Gregorian leap years (divisible by 4, not 100, or divisible by 400).
### `daysInMonth(year: number, month: number): number`
Returns the number of days in the given month (1-indexed). Handles February leap-year logic via `new Date(year, month, 0).getDate()`.
### `isSameDay(a: DateInput, b: DateInput): boolean`
Returns `true` when `a` and `b` share the same calendar year, month, and date.
### `isSameMonth(a: DateInput, b: DateInput): boolean`
Returns `true` when `a` and `b` share the same calendar year and month.
## Implementation Notes
`daysInMonth` uses the "day 0 of the following month" trick: `new Date(year, month, 0).getDate()` returns the last day of the prior month, which equals the number of days in that month. This avoids a lookup table and handles leap years correctly via the JavaScript `Date` constructor.
`toDate` copies `Date` inputs (returns `new Date(input.getTime())`) to prevent mutation aliasing. String inputs are passed directly to `new Date()` which follows ISO 8601 parsing rules in all modern runtimes.

View File

@@ -0,0 +1,102 @@
import { DATETIME_CODES, DatetimeError } from "../errors/datetime-error.js";
import type { DateInput, Timezone } from "../types/datetime.types.js";
// ---------------------------------------------------------------------------
// Public: coercion
// ---------------------------------------------------------------------------
/**
* Coerce a `DateInput` (Date | string | number) into a `Date`.
*
* @throws {DatetimeError} `DATETIME.PARSE.INVALID_INPUT` when `input` is a
* string that cannot be parsed into a valid date.
*/
export function toDate(input: DateInput): Date {
if (input instanceof Date) {
if (Number.isNaN(input.getTime())) {
throw new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input",
{ context: { input: String(input) } }
);
}
return new Date(input.getTime());
}
if (typeof input === "number") {
const d = new Date(input);
if (Number.isNaN(d.getTime())) {
throw new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input",
{ context: { input: String(input) } }
);
}
return d;
}
// string
const d = new Date(input);
if (Number.isNaN(d.getTime())) {
throw new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input",
{ context: { input } }
);
}
return d;
}
// ---------------------------------------------------------------------------
// Public: brand helper
// ---------------------------------------------------------------------------
/**
* Cast a raw string to the `Timezone` brand.
* No runtime validation is performed — use when you trust the input.
*/
export function asTimezone(tz: string): Timezone {
return tz as Timezone;
}
// ---------------------------------------------------------------------------
// Public: leap year / days in month
// ---------------------------------------------------------------------------
/** Returns `true` if `year` is a leap year. */
export function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
/**
* Returns the number of days in the given month (1-indexed).
*
* @param year - Full calendar year (e.g. 2024)
* @param month - 1-indexed month (1 = January, 12 = December)
*/
export function daysInMonth(year: number, month: number): number {
// Using day 0 of next month gives last day of current month
return new Date(year, month, 0).getDate();
}
// ---------------------------------------------------------------------------
// Public: same-day / same-month predicates
// ---------------------------------------------------------------------------
/** Returns `true` when `a` and `b` fall on the same calendar day. */
export function isSameDay(a: DateInput, b: DateInput): boolean {
const da = toDate(a);
const db = toDate(b);
return (
da.getFullYear() === db.getFullYear() &&
da.getMonth() === db.getMonth() &&
da.getDate() === db.getDate()
);
}
/** Returns `true` when `a` and `b` fall in the same calendar month and year. */
export function isSameMonth(a: DateInput, b: DateInput): boolean {
const da = toDate(a);
const db = toDate(b);
return (
da.getFullYear() === db.getFullYear() && da.getMonth() === db.getMonth()
);
}

View File

@@ -0,0 +1,73 @@
# calendar-duration
## Purpose
`calendar-duration` provides duration arithmetic for `@suaveplan/datetime`: adding and subtracting `Duration` bags from dates with correct month-end clamping and overflow normalisation. It is the arithmetic engine that powers use cases such as "one month from January 31" and "subtract 90 days".
The module separates year/month arithmetic (done in calendar coordinates to avoid day-count ambiguity) from sub-day arithmetic (done as millisecond offsets on a local-midnight base date).
## Features
- `addDuration` — add a `Duration` bag to a date with month-end clamping
- `subtractDuration` — subtract a `Duration` bag (negates fields, delegates to `addDuration`)
- Handles all `DurationUnit` fields: `years`, `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`, `milliseconds`
- Month overflow/underflow normalisation (e.g. month 13 → January of next year)
- Day clamping prevents invalid dates (e.g. Jan 31 + 1 month = Feb 28/29)
## Usage: Basic Example
```ts
import { addDuration, subtractDuration } from "@suaveplan/datetime";
const jan31 = new Date(2024, 0, 31);
const feb29 = addDuration(jan31, { months: 1 });
console.log(feb29.toDateString()); // Thu Feb 29 2024 (leap year)
const yesterday = subtractDuration(new Date(), { days: 1 });
```
## Usage: Advanced Example
```ts
import { addDuration } from "@suaveplan/datetime";
// Combined duration: 1 year, 2 months, 3 days, 4 hours
const base = new Date(2023, 10, 30, 12, 0, 0, 0); // Nov 30 2023 12:00
const result = addDuration(base, {
years: 1,
months: 2,
days: 3,
hours: 4,
});
// Feb 2, 2025 16:00 — Nov 30 + 1y2m = Jan 30 2025, then +3d = Feb 2, +4h = 16:00
// Month underflow normalisation: subtracting months past January
const dec1 = new Date(2024, 11, 1);
const oct = addDuration(dec1, { months: -2 });
console.log(oct.getMonth()); // 9 (October)
```
## API Reference
### `addDuration(date: DateInput, duration: Duration): Date`
Add `duration` to `date`. Year/month fields are applied first with overflow/underflow normalisation. Day/week/hour/minute/second/millisecond fields are added as a millisecond offset to the clamped local-midnight date.
**Params:**
- `date` — `Date`, ISO string, or epoch number
- `duration` — `Duration` bag; all fields are optional and default to `0`
**Returns:** New `Date` (does not mutate input).
### `subtractDuration(date: DateInput, duration: Duration): Date`
Subtract `duration` from `date`. Internally negates all fields and delegates to `addDuration`.
**Params:** same as `addDuration`.
**Returns:** New `Date`.
## Implementation Notes
Year and month arithmetic is performed in integer calendar coordinates rather than millisecond arithmetic to avoid the 28–31 day ambiguity. After clamping the day to the last valid day of the resulting month, the remaining duration components (weeks, days, hours, minutes, seconds, milliseconds) are totalled as a single millisecond value and added to a local-midnight `Date` object. This approach avoids DST-induced errors that would occur if each component were added sequentially in timestamp space.

View File

@@ -0,0 +1,92 @@
import type {
DateInput,
Duration,
DurationUnit,
} from "../types/datetime.types.js";
import { daysInMonth, toDate } from "./calendar-core.js";
// ---------------------------------------------------------------------------
// Internal constants
// ---------------------------------------------------------------------------
const MS_IN_SECOND = 1000;
const MS_IN_MINUTE = 60 * MS_IN_SECOND;
const MS_IN_HOUR = 60 * MS_IN_MINUTE;
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
/** Clamp `day` to the last valid day of `year`/`month` (1-indexed). */
function clampDay(year: number, month: number, day: number): number {
const max = daysInMonth(year, month);
return day > max ? max : day;
}
// ---------------------------------------------------------------------------
// Public: duration arithmetic
// ---------------------------------------------------------------------------
/**
* Add a `Duration` to a date.
*
* Month arithmetic clamps to the last day of the resulting month so that
* e.g. Jan 31 + 1 month → Feb 28 (or 29 on leap years).
*/
export function addDuration(date: DateInput, duration: Duration): Date {
const d = toDate(date);
let year = d.getFullYear();
let month = d.getMonth() + 1; // 1-indexed
let day = d.getDate();
let ms =
d.getHours() * MS_IN_HOUR +
d.getMinutes() * MS_IN_MINUTE +
d.getSeconds() * MS_IN_SECOND +
d.getMilliseconds();
year += duration.years ?? 0;
month += duration.months ?? 0;
// Normalise month overflow/underflow
while (month > 12) {
month -= 12;
year += 1;
}
while (month < 1) {
month += 12;
year -= 1;
}
day = clampDay(year, month, day);
// Build base date from year/month/day, then add calendar days/weeks
// using setDate so DST transitions are handled correctly.
const base = new Date(year, month - 1, day, 0, 0, 0, 0);
base.setDate(
base.getDate() + (duration.weeks ?? 0) * 7 + (duration.days ?? 0)
);
ms += (duration.hours ?? 0) * MS_IN_HOUR;
ms += (duration.minutes ?? 0) * MS_IN_MINUTE;
ms += (duration.seconds ?? 0) * MS_IN_SECOND;
ms += duration.milliseconds ?? 0;
return new Date(base.getTime() + ms);
}
/**
* Subtract a `Duration` from a date.
*
* Equivalent to negating all duration fields and calling `addDuration`.
*/
export function subtractDuration(date: DateInput, duration: Duration): Date {
const neg: Duration = {};
for (const [key, v] of Object.entries(duration) as [
DurationUnit,
number,
][]) {
neg[key] = -v;
}
return addDuration(date, neg);
}

View File

@@ -0,0 +1,78 @@
# calendar-grid
## Purpose
`calendar-grid` provides `getCalendarMonth`, which builds a full calendar month grid for use in UI calendar components and scheduling displays. It returns a `CalendarMonth` value containing one `CalendarDay` entry per day in the month, each annotated with its day-of-week index, whether it is a weekend, and whether it represents today (driven by an injectable `Clock`).
The module is intentionally narrow: it answers "what are the days in this month and which one is today?" — layout concerns (week rows, leading/trailing days from adjacent months) are left to the consumer.
## Features
- `getCalendarMonth` — builds a `CalendarMonth` grid for a given year and 1-indexed month
- Each `CalendarDay` includes `date`, `dayOfWeek` (0=Sun … 6=Sat), `isWeekend`, and `isToday`
- Injectable `Clock` for deterministic rendering in tests and server-side snapshots
- Zero side effects; all computation is local
## Usage: Basic Example
```ts
import { getCalendarMonth } from "@suaveplan/datetime";
const march = getCalendarMonth(2024, 3);
console.log(march.days.length); // 31
console.log(march.days[0]?.dayOfWeek); // 5 (Friday — Mar 1 2024)
const weekends = march.days.filter((d) => d.isWeekend);
console.log(weekends.length); // 10
```
## Usage: Advanced Example
```ts
import { getCalendarMonth } from "@suaveplan/datetime";
// Deterministic "today" for SSR or snapshot tests
const fakeClock = () => new Date(2024, 2, 15).getTime(); // Mar 15 2024
const march = getCalendarMonth(2024, 3, { clock: fakeClock });
const today = march.days.find((d) => d.isToday);
console.log(today?.date.getDate()); // 15
// Render a simple ASCII calendar header
for (const day of march.days) {
const marker = day.isToday ? "*" : day.isWeekend ? "W" : " ";
process.stdout.write(`${marker}${String(day.date.getDate()).padStart(2)} `);
if (day.dayOfWeek === 6) process.stdout.write("\n");
}
```
## API Reference
### `CalendarMonthOptions`
```ts
interface CalendarMonthOptions {
clock?: Clock;
}
```
- `clock` — injectable `Clock` (returns epoch ms). Defaults to `Date.now`.
### `getCalendarMonth(year: number, month: number, opts?: CalendarMonthOptions): CalendarMonth`
Build a `CalendarMonth` for the given `year` and 1-indexed `month`.
**Params:**
- `year` — full calendar year (e.g. 2024)
- `month` — 1-indexed month (1 = January, 12 = December)
- `opts.clock` — optional injectable clock
**Returns:** `{ year, month, days: CalendarDay[] }` where each `CalendarDay` is:
```ts
{ date: Date; dayOfWeek: Weekday; isWeekend: boolean; isToday: boolean }
```
## Implementation Notes
`isToday` is computed by comparing a `"year-month-date"` string derived from `clock()` to the same string for each grid day. This string comparison avoids UTC/local timezone confusion that would arise from comparing epoch timestamps directly. The `clock` default (`Date.now`) is captured once per call to ensure consistent "today" across all days in the grid.

View File

@@ -0,0 +1,52 @@
import type { Clock } from "@suaveplan/types";
import type { CalendarMonth, Weekday } from "../types/datetime.types.js";
import { daysInMonth } from "./calendar-core.js";
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
const defaultClock: Clock = () => Date.now();
// ---------------------------------------------------------------------------
// Public: CalendarMonthOptions
// ---------------------------------------------------------------------------
/** Options for `getCalendarMonth`. */
export interface CalendarMonthOptions {
clock?: Clock;
}
// ---------------------------------------------------------------------------
// Public: calendar month grid
// ---------------------------------------------------------------------------
/**
* Build a full calendar month grid for the given `year` and 1-indexed `month`.
*
* Each `CalendarDay` includes the date, its day-of-week, whether it is a
* weekend (Sat/Sun), and whether it is today (using `opts.clock` or wall-clock).
*/
export function getCalendarMonth(
year: number,
month: number,
opts?: CalendarMonthOptions
): CalendarMonth {
const clock = opts?.clock ?? defaultClock;
const now = new Date(clock());
const todayStr = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;
const count = daysInMonth(year, month);
const days = [];
for (let d = 1; d <= count; d++) {
const date = new Date(year, month - 1, d, 0, 0, 0, 0);
const dow = date.getDay() as Weekday;
const isWeekend = dow === 0 || dow === 6;
const isToday =
`${date.getFullYear()}-${date.getMonth()}-${date.getDate()}` ===
todayStr;
days.push({ date, dayOfWeek: dow, isWeekend, isToday });
}
return { year, month, days };
}

View File

@@ -0,0 +1,112 @@
# calendar
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
The `calendar` module is the arithmetic core of `@suaveplan/datetime`. It provides the fundamental building blocks for working with dates: coercing heterogeneous `DateInput` values into `Date` objects, adding and subtracting `Duration` bags with correct month-end clamping, computing start-of / end-of boundaries for any time unit, and generating full calendar-month grids with today-awareness injected via a pluggable `Clock`.
All functions are pure and stateless. They accept local-time `Date` objects and return local-time `Date` objects. Timezone conversion (IANA) is not in scope for this module — it belongs to consumer code that formats dates for display.
## Features
- `toDate` — coerce `Date | string | number` to `Date`, throws `DatetimeError` for invalid inputs
- `isLeapYear` — true for proleptic Gregorian leap years
- `daysInMonth` — correct day-count for any month including February on leap years
- `isSameDay` / `isSameMonth` — calendar equality predicates
- `addDuration` / `subtractDuration` — month-clamping arithmetic (Jan 31 + 1 month = Feb 28/29)
- `startOf` / `endOf` — precise boundary computation for years, months, weeks, days, hours, minutes, seconds, milliseconds
- `getCalendarMonth` — full grid of `CalendarDay` entries with `isToday` driven by injected `Clock`
- `asTimezone` — brands a raw string as a `Timezone` opaque type
## Usage: Basic Example
```ts
import { toDate, addDuration, isSameDay } from "@suaveplan/datetime/calendar";
const jan31 = toDate("2024-01-31");
const feb29 = addDuration(jan31, { months: 1 });
console.log(feb29.toISOString()); // 2024-02-29T00:00:00.000Z (leap year)
console.log(isSameDay(feb29, toDate("2024-02-29"))); // true
```
## Usage: Advanced Example
```ts
import {
getCalendarMonth,
startOf,
endOf,
subtractDuration,
} from "@suaveplan/datetime/calendar";
// Inject a fake clock for deterministic "isToday" rendering in tests
const fakeClock = () => new Date("2024-03-15T12:00:00Z").getTime();
const march = getCalendarMonth(2024, 3, { clock: fakeClock });
const today = march.days.find((d) => d.isToday);
console.log(today?.date.getDate()); // 15
// Fiscal quarter boundaries
const q1Start = startOf("2024-03-15", "years"); // 2024-01-01
const q1End = endOf("2024-03-31", "months"); // 2024-03-31T23:59:59.999
// Rolling 90-day window
const ninetyDaysAgo = subtractDuration(new Date(), { days: 90 });
console.log(ninetyDaysAgo.toISOString());
```
## API Reference
### `toDate(input: DateInput): Date`
Coerce `input` to a `Date`. Accepts `Date`, ISO string, or epoch millis.
Throws `DatetimeError("DATETIME.PARSE.INVALID_INPUT")` for unparseable strings or `NaN` inputs.
### `asTimezone(tz: string): Timezone`
Cast `tz` to the branded `Timezone` type. No runtime validation.
### `isLeapYear(year: number): boolean`
Returns `true` for proleptic Gregorian leap years.
### `daysInMonth(year: number, month: number): number`
Returns the number of days in the given month (1-indexed). Handles February leap-year logic.
### `isSameDay(a: DateInput, b: DateInput): boolean`
Returns `true` when `a` and `b` share the same calendar year, month, and day.
### `isSameMonth(a: DateInput, b: DateInput): boolean`
Returns `true` when `a` and `b` share the same calendar year and month.
### `addDuration(date: DateInput, duration: Duration): Date`
Add `duration` to `date`. Year/month fields are applied first with overflow normalisation. Day/week/hour/minute/second/millisecond fields are added as millisecond offsets. Month-end clamping prevents invalid dates (e.g. March 31 - 1 month = Feb 28/29).
### `subtractDuration(date: DateInput, duration: Duration): Date`
Subtract `duration` from `date`. Internally negates all fields and delegates to `addDuration`.
### `startOf(date: DateInput, unit: DurationUnit, opts?: BoundaryOptions): Date`
Returns the first moment of the given `unit` period. For `weeks`, Sunday is the start of the week.
### `endOf(date: DateInput, unit: DurationUnit, opts?: BoundaryOptions): Date`
Returns the last millisecond of the given `unit` period.
### `getCalendarMonth(year: number, month: number, opts?: CalendarMonthOptions): CalendarMonth`
Build a `CalendarMonth` grid. `opts.clock` defaults to `Date.now`. Each `CalendarDay` includes `date`, `dayOfWeek`, `isWeekend`, and `isToday`.
## Implementation Notes
Month arithmetic is performed in calendar coordinates (year/month/day integers) rather than millisecond arithmetic to avoid the 28–31 day ambiguity. Day clamping uses `daysInMonth` to find the last valid day after year/month adjustment, then the remaining sub-day duration components are added as a single millisecond offset to the clamped local-midnight date.
`startOf("weeks")` uses Sunday as the week start (index 0) to match `Date.prototype.getDay()`. Callers that need Monday-start weeks should offset the result by one day.

View File

@@ -0,0 +1,396 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import * as fc from "fast-check";
import {
addDuration,
asTimezone,
daysInMonth,
endOf,
getCalendarMonth,
isLeapYear,
isSameDay,
isSameMonth,
startOf,
subtractDuration,
toDate,
} from "./calendar.js";
describe("toDate", () => {
it("accepts a Date object", { timeout: 5000 }, () => {
const d = new Date("2024-03-15");
expect(toDate(d).getTime()).toBe(d.getTime());
});
it("accepts an ISO string", { timeout: 5000 }, () => {
const d = toDate("2024-03-15T00:00:00Z");
expect(d).toBeInstanceOf(Date);
expect(Number.isNaN(d.getTime())).toBe(false);
});
it("accepts epoch millis", { timeout: 5000 }, () => {
const ms = 1_710_460_800_000;
expect(toDate(ms).getTime()).toBe(ms);
});
it("throws for invalid string", { timeout: 5000 }, () => {
let err: unknown;
try {
toDate("not-a-date");
} catch (e) {
err = e;
}
expect(err).toBeInstanceOf(Error);
expect((err as { code?: string }).code).toBe(
"DATETIME.PARSE.INVALID_INPUT"
);
});
it("throws for NaN date object", { timeout: 5000 }, () => {
expect(() => toDate(new Date("invalid"))).toThrow();
});
it("throws for NaN number", { timeout: 5000 }, () => {
expect(() => toDate(Number.NaN)).toThrow();
});
it("returns a copy not the same reference", { timeout: 5000 }, () => {
const d = new Date("2024-01-01");
const result = toDate(d);
expect(result).not.toBe(d);
});
});
describe("asTimezone", () => {
it("brands the string", { timeout: 5000 }, () => {
const tz = asTimezone("America/New_York");
expect(tz).toBe("America/New_York");
});
});
describe("isLeapYear", () => {
it("2024 is a leap year", { timeout: 5000 }, () => {
expect(isLeapYear(2024)).toBe(true);
});
it("2023 is not a leap year", { timeout: 5000 }, () => {
expect(isLeapYear(2023)).toBe(false);
});
it("1900 is not a leap year (century rule)", { timeout: 5000 }, () => {
expect(isLeapYear(1900)).toBe(false);
});
it("2000 is a leap year (400 rule)", { timeout: 5000 }, () => {
expect(isLeapYear(2000)).toBe(true);
});
});
describe("daysInMonth", () => {
it("February 2024 has 29 days", { timeout: 5000 }, () => {
expect(daysInMonth(2024, 2)).toBe(29);
});
it("February 2023 has 28 days", { timeout: 5000 }, () => {
expect(daysInMonth(2023, 2)).toBe(28);
});
it("January has 31 days", { timeout: 5000 }, () => {
expect(daysInMonth(2024, 1)).toBe(31);
});
it("April has 30 days", { timeout: 5000 }, () => {
expect(daysInMonth(2024, 4)).toBe(30);
});
});
describe("isSameDay", () => {
it("same date is same day", { timeout: 5000 }, () => {
expect(isSameDay("2024-03-15", "2024-03-15")).toBe(true);
});
it("different date is not same day", { timeout: 5000 }, () => {
expect(isSameDay("2024-03-15", "2024-03-16")).toBe(false);
});
});
describe("isSameMonth", () => {
it("same month returns true", { timeout: 5000 }, () => {
expect(isSameMonth("2024-03-01", "2024-03-31")).toBe(true);
});
it("different month returns false", { timeout: 5000 }, () => {
expect(isSameMonth("2024-03-31", "2024-04-01")).toBe(false);
});
});
describe("addDuration", () => {
it("adds days", { timeout: 5000 }, () => {
const result = addDuration("2024-01-01", { days: 5 });
expect(result.getDate()).toBe(6);
});
it("adds months with clamping Jan 31 → Feb 29 (leap)", {
timeout: 5000,
}, () => {
const jan31 = new Date(2024, 0, 31);
const result = addDuration(jan31, { months: 1 });
expect(result.getMonth()).toBe(1); // February
expect(result.getDate()).toBe(29); // leap year
});
it("adds months with clamping Jan 31 → Feb 28 (non-leap)", {
timeout: 5000,
}, () => {
const jan31 = new Date(2023, 0, 31);
const result = addDuration(jan31, { months: 1 });
expect(result.getMonth()).toBe(1);
expect(result.getDate()).toBe(28);
});
it("adds years", { timeout: 5000 }, () => {
const result = addDuration("2020-02-29", { years: 1 });
expect(result.getFullYear()).toBe(2021);
});
it("adds weeks", { timeout: 5000 }, () => {
const result = addDuration("2024-01-01", { weeks: 2 });
expect(result.getDate()).toBe(15);
});
it("adds hours, minutes, seconds, milliseconds", { timeout: 5000 }, () => {
const base = new Date(2024, 0, 1, 0, 0, 0, 0);
const result = addDuration(base, {
hours: 1,
minutes: 30,
seconds: 45,
milliseconds: 500,
});
expect(result.getHours()).toBe(1);
expect(result.getMinutes()).toBe(30);
expect(result.getSeconds()).toBe(45);
expect(result.getMilliseconds()).toBe(500);
});
it("handles month overflow across year boundary", { timeout: 5000 }, () => {
const result = addDuration("2024-11-01", { months: 3 });
expect(result.getFullYear()).toBe(2025);
expect(result.getMonth()).toBe(1); // February
});
it("handles month underflow across year boundary", {
timeout: 5000,
}, () => {
const result = addDuration("2024-02-01", { months: -3 });
expect(result.getFullYear()).toBe(2023);
expect(result.getMonth()).toBe(10); // November
});
it("empty duration returns same date", { timeout: 5000 }, () => {
const base = new Date(2024, 5, 15, 12, 0, 0, 0);
const result = addDuration(base, {});
expect(result.getTime()).toBe(base.getTime());
});
});
describe("subtractDuration", () => {
it("subtracts days", { timeout: 5000 }, () => {
const result = subtractDuration("2024-01-10", { days: 5 });
expect(result.getDate()).toBe(5);
});
it("subtracts months", { timeout: 5000 }, () => {
const result = subtractDuration("2024-03-01", { months: 1 });
expect(result.getMonth()).toBe(1); // February
});
it("subtracts years", { timeout: 5000 }, () => {
const result = subtractDuration("2024-06-15", { years: 2 });
expect(result.getFullYear()).toBe(2022);
});
});
describe("addDuration / subtractDuration property test", () => {
it("add then subtract returns original date (days, weeks)", {
timeout: 30000,
}, () => {
fc.assert(
fc.property(
fc.date({
min: new Date("2000-01-01"),
max: new Date("2030-12-31"),
}),
fc.record({
days: fc.integer({ min: 0, max: 365 }),
weeks: fc.integer({ min: 0, max: 52 }),
}),
(rawDate, duration) => {
// Normalise to local midnight so the property test exercises
// calendar-day arithmetic without DST time-drift artefacts.
const date = new Date(
rawDate.getFullYear(),
rawDate.getMonth(),
rawDate.getDate()
);
const added = addDuration(date, duration);
const subtracted = subtractDuration(added, duration);
expect(subtracted.getFullYear()).toBe(date.getFullYear());
expect(subtracted.getMonth()).toBe(date.getMonth());
expect(subtracted.getDate()).toBe(date.getDate());
}
),
{ numRuns: 200 }
);
});
});
describe("startOf", () => {
it("startOf years", { timeout: 5000 }, () => {
const result = startOf("2024-06-15T14:30:00", "years");
expect(result.getMonth()).toBe(0);
expect(result.getDate()).toBe(1);
expect(result.getHours()).toBe(0);
});
it("startOf months", { timeout: 5000 }, () => {
const result = startOf("2024-06-15", "months");
expect(result.getDate()).toBe(1);
expect(result.getHours()).toBe(0);
});
it("startOf weeks (Sunday)", { timeout: 5000 }, () => {
// 2024-03-20 is a Wednesday (day 3); start of week should be Sunday 2024-03-17
const result = startOf(new Date(2024, 2, 20), "weeks");
expect(result.getDay()).toBe(0);
expect(result.getDate()).toBe(17);
});
it("startOf days", { timeout: 5000 }, () => {
const result = startOf("2024-03-15T14:30:45.123", "days");
expect(result.getHours()).toBe(0);
expect(result.getMinutes()).toBe(0);
expect(result.getSeconds()).toBe(0);
expect(result.getMilliseconds()).toBe(0);
});
it("startOf hours", { timeout: 5000 }, () => {
const result = startOf(new Date(2024, 2, 15, 14, 30, 45, 123), "hours");
expect(result.getHours()).toBe(14);
expect(result.getMinutes()).toBe(0);
expect(result.getSeconds()).toBe(0);
});
it("startOf minutes", { timeout: 5000 }, () => {
const result = startOf(
new Date(2024, 2, 15, 14, 30, 45, 123),
"minutes"
);
expect(result.getMinutes()).toBe(30);
expect(result.getSeconds()).toBe(0);
expect(result.getMilliseconds()).toBe(0);
});
it("startOf seconds", { timeout: 5000 }, () => {
const result = startOf(
new Date(2024, 2, 15, 14, 30, 45, 123),
"seconds"
);
expect(result.getSeconds()).toBe(45);
expect(result.getMilliseconds()).toBe(0);
});
it("startOf milliseconds returns same time", { timeout: 5000 }, () => {
const d = new Date(2024, 2, 15, 14, 30, 45, 123);
const result = startOf(d, "milliseconds");
expect(result.getTime()).toBe(d.getTime());
});
});
describe("endOf", () => {
it("endOf years", { timeout: 5000 }, () => {
const result = endOf("2024-06-15", "years");
expect(result.getMonth()).toBe(11);
expect(result.getDate()).toBe(31);
expect(result.getHours()).toBe(23);
expect(result.getMinutes()).toBe(59);
expect(result.getMilliseconds()).toBe(999);
});
it("endOf months", { timeout: 5000 }, () => {
const result = endOf("2024-02-01", "months");
expect(result.getDate()).toBe(29); // leap year
expect(result.getHours()).toBe(23);
expect(result.getMilliseconds()).toBe(999);
});
it("endOf weeks (Saturday)", { timeout: 5000 }, () => {
// 2024-03-20 is Wednesday; end of week should be Saturday 2024-03-23
const result = endOf(new Date(2024, 2, 20), "weeks");
expect(result.getDay()).toBe(6);
expect(result.getDate()).toBe(23);
expect(result.getMilliseconds()).toBe(999);
});
it("endOf days", { timeout: 5000 }, () => {
const result = endOf("2024-03-15", "days");
expect(result.getHours()).toBe(23);
expect(result.getMinutes()).toBe(59);
expect(result.getSeconds()).toBe(59);
expect(result.getMilliseconds()).toBe(999);
});
it("endOf hours", { timeout: 5000 }, () => {
const result = endOf(new Date(2024, 2, 15, 14, 30, 45, 0), "hours");
expect(result.getMinutes()).toBe(59);
expect(result.getSeconds()).toBe(59);
expect(result.getMilliseconds()).toBe(999);
});
it("endOf minutes", { timeout: 5000 }, () => {
const result = endOf(new Date(2024, 2, 15, 14, 30, 45, 0), "minutes");
expect(result.getSeconds()).toBe(59);
expect(result.getMilliseconds()).toBe(999);
});
it("endOf seconds", { timeout: 5000 }, () => {
const result = endOf(new Date(2024, 2, 15, 14, 30, 45, 0), "seconds");
expect(result.getMilliseconds()).toBe(999);
});
it("endOf milliseconds returns same time", { timeout: 5000 }, () => {
const d = new Date(2024, 2, 15, 14, 30, 45, 500);
const result = endOf(d, "milliseconds");
expect(result.getTime()).toBe(d.getTime());
});
});
describe("getCalendarMonth", () => {
it("returns correct number of days for January 2024", {
timeout: 5000,
}, () => {
const cal = getCalendarMonth(2024, 1);
expect(cal.year).toBe(2024);
expect(cal.month).toBe(1);
expect(cal.days.length).toBe(31);
});
it("marks weekends correctly", { timeout: 5000 }, () => {
const cal = getCalendarMonth(2024, 1);
for (const day of cal.days) {
const expected = day.dayOfWeek === 0 || day.dayOfWeek === 6;
expect(day.isWeekend).toBe(expected);
}
});
it("marks today correctly with clock injection", { timeout: 5000 }, () => {
const clock = () => new Date(2024, 2, 15).getTime(); // March 15 2024
const cal = getCalendarMonth(2024, 3, { clock });
const today = cal.days.filter((d) => d.isToday);
expect(today.length).toBe(1);
expect(today[0]?.date.getDate()).toBe(15);
});
it("no day is today when clock is in different month", {
timeout: 5000,
}, () => {
const clock = () => new Date(2024, 5, 1).getTime(); // June
const cal = getCalendarMonth(2024, 3, { clock }); // March
const today = cal.days.filter((d) => d.isToday);
expect(today.length).toBe(0);
});
it("February 2024 has 29 days (leap year)", { timeout: 5000 }, () => {
const cal = getCalendarMonth(2024, 2);
expect(cal.days.length).toBe(29);
});
});

View File

@@ -0,0 +1,15 @@
// Re-export barrel — keeps all existing import paths valid.
export type { BoundaryOptions } from "./calendar-boundary.js";
export { endOf, startOf } from "./calendar-boundary.js";
export {
asTimezone,
daysInMonth,
isLeapYear,
isSameDay,
isSameMonth,
toDate,
} from "./calendar-core.js";
export { addDuration, subtractDuration } from "./calendar-duration.js";
export type { CalendarMonthOptions } from "./calendar-grid.js";
export { getCalendarMonth } from "./calendar-grid.js";

View File

@@ -0,0 +1,15 @@
export {
addDuration,
asTimezone,
type BoundaryOptions,
type CalendarMonthOptions,
daysInMonth,
endOf,
getCalendarMonth,
isLeapYear,
isSameDay,
isSameMonth,
startOf,
subtractDuration,
toDate,
} from "./calendar";

View File

@@ -0,0 +1,382 @@
/**
* Spec-conformance tests for `@suaveplan/datetime`.
*
* Pins implicit scenarios named in `openspec/specs/datetime/spec.md` that
* existing unit tests touch indirectly: DateInput acceptance, injectable
* Clock determinism, business-day options + abort signal, calendar
* arithmetic correctness, RRULE field parsing, error-code namespacing,
* Zod schemas at the boundary, i18n-keyed relative output, OTel histogram
* surface (duration + size for both hot paths), and `sideEffects: false`.
*/
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "@suaveplan/testing/runner";
import type { Clock } from "@suaveplan/types";
import {
addBusinessDays,
addDuration,
asTimezone,
businessDaysBetween,
businessDaysBetweenDuration,
businessDaysBetweenSize,
businessDaysBetweenTotal,
DATETIME_CODES,
DatetimeError,
daysInMonth,
expandRecurrence,
expandRecurrenceDuration,
expandRecurrenceSize,
formatRelative,
formatRRule,
isBusinessDay,
isLeapYear,
nextBusinessDay,
nextOccurrence,
parseRRule,
previousBusinessDay,
subtractBusinessDays,
subtractDuration,
timeAgo,
timeUntil,
toDate,
} from "./index.js";
import {
CalendarDaySchema,
CalendarMonthSchema,
DateInputSchema,
DurationSchema,
DurationUnitSchema,
FrequencySchema,
RecurrenceRuleSchema,
WeekdaySchema,
} from "./types/datetime.schemas.js";
// ---------------------------------------------------------------------------
// DT-01 — DateInput acceptance
// ---------------------------------------------------------------------------
describe("DT-01 — DateInput acceptance", () => {
it("every entry point accepts Date | ISO string | epoch number", {
timeout: 5000,
}, () => {
const isoStr = "2025-01-15T00:00:00.000Z";
const epoch = Date.parse(isoStr);
const dateObj = new Date(epoch);
for (const input of [dateObj, isoStr, epoch]) {
expect(toDate(input)).toBeInstanceOf(Date);
expect(typeof isBusinessDay(input)).toBe("boolean");
expect(addDuration(input, { days: 1 })).toBeInstanceOf(Date);
expect(typeof formatRelative(input)).toBe("string");
}
});
it("invalid inputs throw DatetimeError(PARSE.INVALID_INPUT)", {
timeout: 5000,
}, () => {
for (const bad of [
"not-a-date",
Number.NaN,
new Date(Number.NaN),
] as const) {
try {
toDate(bad);
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(DatetimeError);
expect((err as DatetimeError).code).toBe(
DATETIME_CODES["PARSE.INVALID_INPUT"]
);
}
}
});
});
// ---------------------------------------------------------------------------
// DT-02 — Injectable clock determinism
// ---------------------------------------------------------------------------
describe("DT-02 — Injectable clock", () => {
it("formatRelative / timeAgo / timeUntil read time from injected clock", {
timeout: 5000,
}, () => {
const fixed = Date.parse("2025-06-01T12:00:00.000Z");
const clock: Clock = () => fixed;
const past = new Date(fixed - 60_000); // 60s ago
const future = new Date(fixed + 60_000); // 60s ahead
expect(formatRelative(past, { clock })).toBe("1 minute ago");
expect(timeAgo(past, { clock })).toBe("1 minute ago");
expect(timeUntil(future, { clock })).toBe("in 1 minute");
});
it("expandRecurrence reads start time from injected clock", {
timeout: 5000,
}, () => {
const fixed = Date.parse("2025-01-01T00:00:00.000Z");
const clock: Clock = () => fixed;
const out = expandRecurrence({ freq: "daily", count: 3 }, { clock });
expect(out).toHaveLength(3);
// Generator yields strictly after the clock-supplied seed.
expect(out[0]?.toISOString().slice(0, 10)).toBe("2025-01-02");
});
});
// ---------------------------------------------------------------------------
// DT-03 — Business-day arithmetic
// ---------------------------------------------------------------------------
describe("DT-03 — Business day arithmetic", () => {
it("all six functions accept BusinessDayOptions with holidays & weekendDays", {
timeout: 5000,
}, () => {
const holidays = [new Date(2025, 0, 1)];
const weekendDays = [5, 6] as const; // Fri, Sat
const monday = new Date(2025, 0, 6);
expect(isBusinessDay(monday, { holidays, weekendDays })).toBe(true);
expect(
nextBusinessDay(monday, { holidays, weekendDays })
).toBeInstanceOf(Date);
expect(
previousBusinessDay(monday, { holidays, weekendDays })
).toBeInstanceOf(Date);
expect(
addBusinessDays(monday, 3, { holidays, weekendDays })
).toBeInstanceOf(Date);
expect(
subtractBusinessDays(monday, 3, { holidays, weekendDays })
).toBeInstanceOf(Date);
expect(
businessDaysBetween(monday, new Date(2025, 0, 31), {
holidays,
weekendDays,
})
).toBeTypeOf("number");
});
it("businessDaysBetween honours pre-aborted signal", {
timeout: 5000,
}, () => {
const ctrl = new AbortController();
ctrl.abort();
// Range large enough to exceed the 256-iteration check window.
const start = new Date(2020, 0, 1);
const end = new Date(2030, 0, 1);
const got = businessDaysBetween(start, end, {
signal: ctrl.signal,
});
// Aborts before counting most days; result well below the
// ~2600 expected business days in the unbroken range.
expect(got).toBeLessThan(500);
});
});
// ---------------------------------------------------------------------------
// DT-04 — Calendar math correctness
// ---------------------------------------------------------------------------
describe("DT-04 — Calendar math correctness", () => {
it("Jan 31 + 1 month clamps to Feb (28 in 2025, 29 in 2024)", {
timeout: 5000,
}, () => {
const got2025 = addDuration(new Date(2025, 0, 31), { months: 1 });
expect(got2025.getMonth()).toBe(1);
expect(got2025.getDate()).toBe(28);
const got2024 = addDuration(new Date(2024, 0, 31), { months: 1 });
expect(got2024.getMonth()).toBe(1);
expect(got2024.getDate()).toBe(29);
});
it("subtractDuration mirrors addDuration", { timeout: 5000 }, () => {
const start = new Date(2025, 5, 15, 12, 0, 0, 0);
const dur = { days: 3, hours: 4 };
const fwd = addDuration(start, dur);
const back = subtractDuration(fwd, dur);
expect(back.getTime()).toBe(start.getTime());
});
it("daysInMonth handles every month including leap February", {
timeout: 5000,
}, () => {
expect(daysInMonth(2024, 2)).toBe(29);
expect(daysInMonth(2023, 2)).toBe(28);
expect(daysInMonth(2025, 1)).toBe(31);
expect(daysInMonth(2025, 4)).toBe(30);
expect(isLeapYear(2024)).toBe(true);
expect(isLeapYear(2023)).toBe(false);
});
});
// ---------------------------------------------------------------------------
// DT-05 — Recurrence rules
// ---------------------------------------------------------------------------
describe("DT-05 — Recurrence rules", () => {
it("parseRRule reads FREQ, INTERVAL, COUNT, UNTIL, BYDAY, BYMONTHDAY", {
timeout: 5000,
}, () => {
const rule = parseRRule(
"FREQ=WEEKLY;INTERVAL=2;COUNT=4;UNTIL=20251231;BYDAY=MO,WE;BYMONTHDAY=1,15"
);
expect(rule.freq).toBe("weekly");
expect(rule.interval).toBe(2);
expect(rule.count).toBe(4);
expect(rule.until).toBeInstanceOf(Date);
expect(rule.byDay).toEqual([1, 3]);
expect(rule.byMonthDay).toEqual([1, 15]);
});
it("expandRecurrence without count/until throws INFINITE_EXPANSION", {
timeout: 5000,
}, () => {
try {
expandRecurrence({ freq: "daily" });
throw new Error("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(DatetimeError);
expect((err as DatetimeError).code).toBe(
DATETIME_CODES["RECURRENCE.INFINITE_EXPANSION"]
);
}
});
it("nextOccurrence + formatRRule round-trip cleanly", {
timeout: 5000,
}, () => {
const rule = parseRRule("FREQ=DAILY;COUNT=10");
const next = nextOccurrence(rule, new Date(2025, 0, 1));
expect(next).toBeInstanceOf(Date);
const reformatted = formatRRule(rule);
expect(reformatted).toContain("FREQ=DAILY");
expect(reformatted).toContain("COUNT=10");
});
});
// ---------------------------------------------------------------------------
// DT-06 — Structured errors
// ---------------------------------------------------------------------------
describe("DT-06 — Structured errors", () => {
it("all DATETIME_CODES are namespaced under DATETIME.*", {
timeout: 5000,
}, () => {
for (const code of Object.values(DATETIME_CODES)) {
expect(code.startsWith("DATETIME.")).toBe(true);
}
});
it("DATETIME_CODES registry is frozen", { timeout: 5000 }, () => {
expect(Object.isFrozen(DATETIME_CODES)).toBe(true);
});
});
// ---------------------------------------------------------------------------
// DT-07 — Zod schemas at the boundary
// ---------------------------------------------------------------------------
describe("DT-07 — Zod schemas", () => {
it("every public runtime type has a sibling Zod schema", {
timeout: 5000,
}, () => {
expect(DateInputSchema.safeParse("2025-01-01").success).toBe(true);
expect(DurationUnitSchema.safeParse("days").success).toBe(true);
expect(DurationSchema.safeParse({ days: 1, hours: 2 }).success).toBe(
true
);
expect(WeekdaySchema.safeParse(3).success).toBe(true);
expect(WeekdaySchema.safeParse(7).success).toBe(false);
expect(FrequencySchema.safeParse("weekly").success).toBe(true);
expect(
CalendarDaySchema.safeParse({
date: new Date(),
dayOfWeek: 1,
isWeekend: false,
isToday: true,
}).success
).toBe(true);
expect(
CalendarMonthSchema.safeParse({
year: 2025,
month: 1,
days: [],
}).success
).toBe(true);
expect(
RecurrenceRuleSchema.safeParse({
freq: "daily",
count: 5,
}).success
).toBe(true);
});
});
// ---------------------------------------------------------------------------
// DT-08 — i18n-ready output
// ---------------------------------------------------------------------------
describe("DT-08 — i18n-ready output", () => {
it("formatRelative output is the English pass-through default", {
timeout: 5000,
}, () => {
const fixed = Date.parse("2025-06-01T12:00:00.000Z");
const clock: Clock = () => fixed;
// Cover the four label variants: just-now, past, future, plural.
expect(formatRelative(new Date(fixed - 1000), { clock })).toBe(
"just now"
);
expect(formatRelative(new Date(fixed - 5 * 60_000), { clock })).toBe(
"5 minutes ago"
);
expect(formatRelative(new Date(fixed + 60_000), { clock })).toBe(
"in 1 minute"
);
});
});
// ---------------------------------------------------------------------------
// DT-09 — OTel instrumentation: histograms for both hot paths
// ---------------------------------------------------------------------------
describe("DT-09 — OTel instrumentation", () => {
it("expandRecurrence + businessDaysBetween expose duration + size histograms", {
timeout: 5000,
}, () => {
for (const inst of [
expandRecurrenceDuration,
expandRecurrenceSize,
businessDaysBetweenDuration,
businessDaysBetweenSize,
]) {
expect(inst).toBeDefined();
expect(typeof inst.record).toBe("function");
}
expect(typeof businessDaysBetweenTotal.add).toBe("function");
});
it("histograms record without an SDK (no-op safe)", {
timeout: 5000,
}, () => {
expect(() =>
expandRecurrence({ freq: "daily", count: 3 })
).not.toThrow();
expect(() =>
businessDaysBetween(new Date(2025, 0, 1), new Date(2025, 0, 31))
).not.toThrow();
});
});
// ---------------------------------------------------------------------------
// DT-10 — sideEffects: false
// ---------------------------------------------------------------------------
describe("DT-10 — sideEffects: false", () => {
it("package.json declares sideEffects: false", { timeout: 5000 }, () => {
const pkg = JSON.parse(
readFileSync(join(__dirname, "..", "package.json"), "utf8")
) as { sideEffects?: boolean };
expect(pkg.sideEffects).toBe(false);
});
it("asTimezone brand helper is pure", { timeout: 5000 }, () => {
expect(asTimezone("America/New_York")).toBe("America/New_York");
});
});

View File

@@ -0,0 +1,91 @@
# datetime-error
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
`DatetimeError` is the typed error class for the entire `@suaveplan/datetime` package. It extends the project-wide `SuaveplanError` base class with a narrow `DatetimeCode` type parameter, allowing callers to discriminate error origins with `instanceof` and narrow the `code` property to one of three categories: `PARSE.INVALID_INPUT`, `RECURRENCE.INFINITE_EXPANSION`, and `TIMEZONE.UNKNOWN`.
Keeping all error definitions in a single, versioned registry (`DATETIME_CODES`) means consumers can exhaustively handle failure modes without consulting documentation or source code.
## Features
- Inherits full `SuaveplanError` surface: `code`, `context`, `timestamp`, `traceId`, `cause`
- Three error codes covering the library's failure surface
- `defineCodes` ensures the registry is frozen and type-inferred at build time
- Compatible with `walkCauses`, `toSpanEvent`, and the `@suaveplan/error` wire format
## Usage: Basic Example
```ts
import { DatetimeError, DATETIME_CODES } from "@suaveplan/datetime/errors";
throw new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input",
{ context: { input: "not-a-date" } }
);
```
## Usage: Advanced Example
```ts
import { DatetimeError, DATETIME_CODES } from "@suaveplan/datetime/errors";
function guardExpansion(hasTerminator: boolean): void {
if (!hasTerminator) {
throw new DatetimeError(
DATETIME_CODES["RECURRENCE.INFINITE_EXPANSION"],
"datetime.recurrence.infinite_expansion",
{
context: { hint: "supply count or until" },
traceId: "abc-123",
}
);
}
}
try {
guardExpansion(false);
} catch (err) {
if (err instanceof DatetimeError) {
// code is narrowed to DatetimeCode
console.error(err.code, err.context);
}
}
```
## API Reference
### `DATETIME_CODES`
`Record<"PARSE.INVALID_INPUT" | "RECURRENCE.INFINITE_EXPANSION" | "TIMEZONE.UNKNOWN", string>`
Frozen registry of all datetime error codes. Values are fully-qualified strings of the form `DATETIME.<reason>`.
### `DatetimeCode`
`type DatetimeCode = (typeof DATETIME_CODES)[keyof typeof DATETIME_CODES]`
Union of all valid datetime error code strings.
### `class DatetimeError extends SuaveplanError<DatetimeCode>`
**Constructor:** `new DatetimeError(code: DatetimeCode, messageKey: string, options?: SuaveplanErrorOptions)`
- `code` — one of the values in `DATETIME_CODES`
- `messageKey` — i18n key passed to `resolveMessage`
- `options` — optional `{ cause, context, clock, traceId }`
**Inherited properties:** `code`, `context`, `timestamp`, `traceId`, `cause`, `name`, `stack`
## Implementation Notes
The three-code surface was chosen to be exhaustive yet minimal:
- Parsing errors cover any `DateInput` coercion failure
- Recurrence expansion errors guard against infinite loops
- Timezone errors are reserved for future IANA name validation
The `defineCodes` helper freezes the registry object, preventing accidental mutation and enabling tree-shaking of unused codes.

View File

@@ -0,0 +1,83 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import { DATETIME_CODES, DatetimeError } from "./datetime-error.js";
describe("DATETIME_CODES", () => {
it("has PARSE.INVALID_INPUT code", { timeout: 5000 }, () => {
expect(DATETIME_CODES["PARSE.INVALID_INPUT"]).toBe(
"DATETIME.PARSE.INVALID_INPUT"
);
});
it("has RECURRENCE.INFINITE_EXPANSION code", { timeout: 5000 }, () => {
expect(DATETIME_CODES["RECURRENCE.INFINITE_EXPANSION"]).toBe(
"DATETIME.RECURRENCE.INFINITE_EXPANSION"
);
});
it("has TIMEZONE.UNKNOWN code", { timeout: 5000 }, () => {
expect(DATETIME_CODES["TIMEZONE.UNKNOWN"]).toBe(
"DATETIME.TIMEZONE.UNKNOWN"
);
});
it("is frozen", { timeout: 5000 }, () => {
expect(Object.isFrozen(DATETIME_CODES)).toBe(true);
});
});
describe("DatetimeError", () => {
it("is instanceof Error and DatetimeError", { timeout: 5000 }, () => {
const err = new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input"
);
expect(err).toBeInstanceOf(Error);
expect(err).toBeInstanceOf(DatetimeError);
});
it("exposes correct code", { timeout: 5000 }, () => {
const err = new DatetimeError(
DATETIME_CODES["RECURRENCE.INFINITE_EXPANSION"],
"datetime.recurrence.infinite_expansion"
);
expect(err.code).toBe("DATETIME.RECURRENCE.INFINITE_EXPANSION");
});
it("exposes name as DatetimeError", { timeout: 5000 }, () => {
const err = new DatetimeError(
DATETIME_CODES["TIMEZONE.UNKNOWN"],
"datetime.timezone.unknown"
);
expect(err.name).toBe("DatetimeError");
});
it("accepts context", { timeout: 5000 }, () => {
const err = new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input",
{ context: { input: "bad" } }
);
expect(err.context?.["input"]).toBe("bad");
});
it("accepts cause", { timeout: 5000 }, () => {
const cause = new Error("original");
const err = new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input",
{ cause }
);
expect(err.cause).toBe(cause);
});
it("has a timestamp", { timeout: 5000 }, () => {
const before = Date.now();
const err = new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input"
);
const after = Date.now();
expect(err.timestamp).toBeGreaterThanOrEqual(before);
expect(err.timestamp).toBeLessThanOrEqual(after);
});
});

View File

@@ -0,0 +1,47 @@
import {
defineCodes,
SuaveplanError,
type SuaveplanErrorOptions,
} from "@suaveplan/error";
/**
* Error code registry for `@suaveplan/datetime`.
*
* Three top-level namespaces:
* - `DATETIME.PARSE.*` — input parsing failures
* - `DATETIME.RECURRENCE.*` — recurrence expansion failures
* - `DATETIME.TIMEZONE.*` — timezone resolution failures
*/
export const DATETIME_CODES = defineCodes("DATETIME", [
"PARSE.INVALID_INPUT",
"RECURRENCE.INFINITE_EXPANSION",
"TIMEZONE.UNKNOWN",
] as const);
export type DatetimeCode = (typeof DATETIME_CODES)[keyof typeof DATETIME_CODES];
/**
* Typed error for all `@suaveplan/datetime` failures.
*
* Extends `SuaveplanError` with a strongly-typed `code` property drawn from
* `DATETIME_CODES`, giving callers narrow `instanceof` discrimination.
*
* @example
* ```ts
* throw new DatetimeError(
* DATETIME_CODES["PARSE.INVALID_INPUT"],
* "datetime.parse.invalid_input",
* { context: { input: "not-a-date" } }
* );
* ```
*/
export class DatetimeError extends SuaveplanError<DatetimeCode> {
// biome-ignore lint/complexity/noUselessConstructor: widens protected base constructor to public
public constructor(
code: DatetimeCode,
messageKey: string,
options?: SuaveplanErrorOptions
) {
super(code, messageKey, options);
}
}

View File

@@ -0,0 +1,5 @@
export {
DATETIME_CODES,
type DatetimeCode,
DatetimeError,
} from "./datetime-error";

View File

@@ -0,0 +1,73 @@
// Types
// Business days
export {
addBusinessDays,
businessDaysBetween,
isBusinessDay,
nextBusinessDay,
previousBusinessDay,
subtractBusinessDays,
} from "./business-days/business-days.js";
export type {
BoundaryOptions,
CalendarMonthOptions,
} from "./calendar/calendar.js";
// Calendar
export {
addDuration,
asTimezone,
daysInMonth,
endOf,
getCalendarMonth,
isLeapYear,
isSameDay,
isSameMonth,
startOf,
subtractDuration,
toDate,
} from "./calendar/calendar.js";
export type { DatetimeCode } from "./errors/datetime-error.js";
// Errors
export { DATETIME_CODES, DatetimeError } from "./errors/datetime-error.js";
// OTel
export {
businessDaysBetweenDuration,
businessDaysBetweenSize,
businessDaysBetweenTotal,
expandRecurrenceDuration,
expandRecurrenceSize,
recordBusinessDaysBetween,
recordExpandRecurrence,
} from "./otel/datetime-otel.js";
// Recurrence
export {
expandRecurrence,
formatRRule,
nextOccurrence,
parseRRule,
} from "./recurrence/recurrence.js";
// Relative
export {
diffInUnits,
formatRelative,
timeAgo,
timeUntil,
} from "./relative/relative.js";
export type {
BusinessDayOptions,
CalendarDay,
CalendarMonth,
DateInput,
DayAbbreviation,
Duration,
DurationUnit,
Frequency,
RecurrenceOptions,
RecurrenceRule,
RelativeTimeOptions,
Timezone,
Weekday,
} from "./types/datetime.types.js";

View File

@@ -0,0 +1,69 @@
# datetime-otel
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
`datetime-otel` provides lightweight OpenTelemetry instrumentation for the `@suaveplan/datetime` package. It registers a histogram for `expandRecurrence` call durations and a counter for `businessDaysBetween` interval evaluations. Both instruments are initialised lazily via `metrics.getMeter()`, which is a no-op when no global `MeterProvider` is configured, ensuring zero overhead in environments without observability infrastructure.
The module exposes thin wrapper functions (`recordExpandRecurrence`, `recordBusinessDaysBetween`) so the hot-path modules do not need to import `@opentelemetry/api` directly.
## Features
- `datetime.expand_recurrence.duration_ms` histogram (unit: `ms`)
- `datetime.business_days_between.total` counter (unit: `{days}`)
- Zero-overhead when no OTel SDK is configured
- Named meter `@suaveplan/datetime` for easy filtering in dashboards
## Usage: Basic Example
```ts
import { recordExpandRecurrence } from "@suaveplan/datetime/otel";
const start = Date.now();
// ... run expandRecurrence ...
recordExpandRecurrence(Date.now() - start);
```
## Usage: Advanced Example
```ts
import { MeterProvider } from "@opentelemetry/sdk-metrics";
import { recordBusinessDaysBetween } from "@suaveplan/datetime/otel";
// Wire up an SDK meter provider before the first import of datetime modules
const provider = new MeterProvider();
// metrics.setGlobalMeterProvider(provider); // done at app startup
// Later, inside businessDaysBetween implementation:
recordBusinessDaysBetween(365); // records 365 day-intervals evaluated
```
## API Reference
### `expandRecurrenceDuration`
`Histogram` — OpenTelemetry histogram for `expandRecurrence` durations.
### `businessDaysBetweenTotal`
`Counter` — OpenTelemetry counter for `businessDaysBetween` day-intervals.
### `recordExpandRecurrence(durationMs: number): void`
Records a single `expandRecurrence` call duration. Call immediately after the expansion completes.
- `durationMs` — wall-clock elapsed time in milliseconds
### `recordBusinessDaysBetween(count: number): void`
Increments the `businessDaysBetween` counter by the number of calendar days evaluated.
- `count` — number of calendar-day intervals walked during the call
## Implementation Notes
`metrics.getMeter()` is called once at module initialisation. The returned `Meter` instance is cached for the lifetime of the process. In environments without a registered `MeterProvider`, all record/add calls are no-ops at the OTel SDK level, incurring only a function-call overhead.
The histogram uses millisecond granularity, which is sufficient for typical recurrence expansions (tens to hundreds of milliseconds). For sub-millisecond benchmarks, use the `mitata` benchmark suite instead.

View File

@@ -0,0 +1,39 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import {
businessDaysBetweenTotal,
expandRecurrenceDuration,
recordBusinessDaysBetween,
recordExpandRecurrence,
} from "./datetime-otel.js";
describe("datetime-otel", () => {
it("exports expandRecurrenceDuration histogram", { timeout: 5000 }, () => {
expect(expandRecurrenceDuration).toBeDefined();
expect(typeof expandRecurrenceDuration.record).toBe("function");
});
it("exports businessDaysBetweenTotal counter", { timeout: 5000 }, () => {
expect(businessDaysBetweenTotal).toBeDefined();
expect(typeof businessDaysBetweenTotal.add).toBe("function");
});
it("recordExpandRecurrence does not throw", { timeout: 5000 }, () => {
expect(() => recordExpandRecurrence(42)).not.toThrow();
});
it("recordBusinessDaysBetween does not throw", { timeout: 5000 }, () => {
expect(() => recordBusinessDaysBetween(100)).not.toThrow();
});
it("recordExpandRecurrence with 0 does not throw", {
timeout: 5000,
}, () => {
expect(() => recordExpandRecurrence(0)).not.toThrow();
});
it("recordBusinessDaysBetween with 0 does not throw", {
timeout: 5000,
}, () => {
expect(() => recordBusinessDaysBetween(0)).not.toThrow();
});
});

View File

@@ -0,0 +1,83 @@
import { metrics } from "@opentelemetry/api";
const meter = metrics.getMeter("@suaveplan/datetime");
/**
* Histogram tracking the wall-clock duration of `expandRecurrence` calls in
* milliseconds. Use this to detect expensive recurrence expansions in production.
*/
export const expandRecurrenceDuration = meter.createHistogram(
"datetime.expand_recurrence.duration_ms",
{
description: "Duration of expandRecurrence() calls in milliseconds",
unit: "ms",
}
);
/**
* Histogram tracking the size (number of dates emitted) by
* `expandRecurrence`. Pairs with {@link expandRecurrenceDuration} to
* correlate output size with latency.
*/
export const expandRecurrenceSize = meter.createHistogram(
"datetime.expand_recurrence.size",
{
description: "Number of dates emitted by expandRecurrence()",
unit: "{dates}",
}
);
/**
* Histogram tracking the wall-clock duration of `businessDaysBetween` calls
* in milliseconds.
*/
export const businessDaysBetweenDuration = meter.createHistogram(
"datetime.business_days_between.duration_ms",
{
description: "Duration of businessDaysBetween() calls in milliseconds",
unit: "ms",
}
);
/**
* Histogram tracking the calendar-day span evaluated by
* `businessDaysBetween` calls.
*/
export const businessDaysBetweenSize = meter.createHistogram(
"datetime.business_days_between.size",
{
description: "Calendar-day span evaluated by businessDaysBetween()",
unit: "{days}",
}
);
/**
* Counter tracking the cumulative number of intervals evaluated by
* `businessDaysBetween`. Use this to monitor workload distribution.
*/
export const businessDaysBetweenTotal = meter.createCounter(
"datetime.business_days_between.total",
{
description:
"Cumulative number of day-intervals evaluated by businessDaysBetween()",
unit: "{days}",
}
);
/**
* Record a `businessDaysBetween` observation.
*
* @param count - Number of calendar days evaluated in the call.
*/
export function recordBusinessDaysBetween(count: number): void {
businessDaysBetweenTotal.add(count);
}
/**
* Record an `expandRecurrence` duration observation.
*
* @param durationMs - Elapsed milliseconds for the expansion call.
*/
export function recordExpandRecurrence(durationMs: number): void {
expandRecurrenceDuration.record(durationMs);
}

View File

@@ -0,0 +1,9 @@
export {
businessDaysBetweenDuration,
businessDaysBetweenSize,
businessDaysBetweenTotal,
expandRecurrenceDuration,
expandRecurrenceSize,
recordBusinessDaysBetween,
recordExpandRecurrence,
} from "./datetime-otel";

View File

@@ -0,0 +1,25 @@
export {
expandRecurrence,
formatRRule,
generateCandidates,
nextOccurrence,
parseRRule,
} from "./recurrence";
export {
generateDaily,
generateMonthly,
generateWeekly,
generateYearly,
} from "./recurrence-generate";
export {
addDays,
addMonths,
addYears,
DAY_INDEX,
DAY_NAME,
daysInMonth,
FREQ_MAP,
FREQ_RRULE,
fromRRuleDate,
toRRuleDate,
} from "./recurrence-helpers";

View File

@@ -0,0 +1,95 @@
# recurrence-generate
## Purpose
`recurrence-generate` provides the internal generator functions that produce infinite sequences of candidate dates for each recurrence frequency supported by `@suaveplan/datetime`. Each generator yields dates strictly after a given `from` anchor, and the `generateCandidates` dispatcher routes to the correct generator based on `RecurrenceRule.freq`.
This module is an internal implementation detail. Public callers should use `expandRecurrence` and `nextOccurrence` from `recurrence.ts`.
## Features
- `generateDaily` — daily step with optional `BYDAY` weekday filter
- `generateWeekly` — weekly step, either plain (same weekday) or with `BYDAY` multi-day selection
- `generateMonthly` — monthly step supporting `BYMONTHDAY`, `BYDAY`, or plain monthly recurrence
- `generateYearly` — yearly step supporting `BYMONTHDAY`, `BYDAY`, or plain yearly recurrence
- `generateCandidates` — dispatcher that routes to the correct generator from `RecurrenceRule.freq`
- All generators are infinite; termination is enforced by callers (`count` / `until` / `AbortSignal`)
## Usage: Basic Example
```ts
import { generateCandidates } from "./recurrence-generate.js";
const rule = { freq: "daily" as const, count: 5 };
const from = new Date(2024, 0, 1);
const gen = generateCandidates(rule, from);
for (let i = 0; i < 5; i++) {
console.log(gen.next().value?.toDateString());
}
// Tue Jan 02 2024 … Sat Jan 06 2024
```
## Usage: Advanced Example
```ts
import { generateCandidates } from "./recurrence-generate.js";
// Monthly with BYMONTHDAY — yields the 15th of each month
const rule = {
freq: "monthly" as const,
byMonthDay: [15],
};
const from = new Date(2024, 0, 1);
const gen = generateCandidates(rule, from);
const first = gen.next().value!;
console.log(first.toDateString()); // Mon Jan 15 2024
const second = gen.next().value!;
console.log(second.toDateString()); // Thu Feb 15 2024
// Weekly with BYDAY — yields Mon/Wed/Fri
const weeklyRule = {
freq: "weekly" as const,
byDay: [1, 3, 5] as const,
};
const weeklyGen = generateCandidates(weeklyRule, new Date(2024, 2, 11));
console.log(weeklyGen.next().value?.getDay()); // 3 (Wed Mar 13)
```
## API Reference
### `generateCandidates(rule: RecurrenceRule, from: Date): Generator<Date>`
Unified dispatcher. Routes to the frequency-specific generator based on `rule.freq`. All yielded dates are strictly after `from`.
### `generateDaily(rule, from, interval): Generator<Date>`
Steps `interval` days at a time. If `rule.byDay` is set, only yields dates whose `getDay()` is in the list.
### `generateWeekly(rule, from, interval): Generator<Date>`
If `rule.byDay` is set: anchors to the Sunday of the current week, then emits the specified weekdays in sorted order each `interval * 7` days. Without `byDay`: yields the same weekday every `interval * 7` days.
### `generateMonthly(rule, from, interval): Generator<Date>`
Three modes:
1. `byMonthDay` — emits the specified day-of-month values (sorted) in each month, skipping months where a day exceeds `daysInMonth`.
2. `byDay` — scans each month and emits all days matching the weekday list.
3. Plain — yields the same day-of-month each `interval` months using `addMonths` clamping.
### `generateYearly(rule, from, interval): Generator<Date>`
Three modes:
1. `byMonthDay` — emits specified day-of-month values in each year.
2. `byDay` — advances one day at a time from the year anchor, yielding matching weekdays.
3. Plain — yields the same date each `interval` years using `addYears`.
## Implementation Notes
All generators are implemented as native ES `Generator` functions (`function*`) to enable lazy evaluation. They produce an infinite sequence; the caller (`expandRecurrence`, `nextOccurrence`) is responsible for applying `count`, `until`, and `AbortSignal` termination conditions.
The `generateWeekly` with `BYDAY` mode anchors to the start of the week (Sunday) on the first iteration, which means it may emit dates in the current week before advancing. Dates before or equal to `from` are filtered out with a `candidate > from` guard.

View File

@@ -0,0 +1,185 @@
import type { RecurrenceRule } from "../types/datetime.types.js";
import {
addDays,
addMonths,
addYears,
daysInMonth,
} from "./recurrence-helpers.js";
// ---------------------------------------------------------------------------
// Internal: per-frequency generators
// ---------------------------------------------------------------------------
/** Generate candidates for FREQ=DAILY, stepping `interval` days at a time. */
export function* generateDaily(
rule: RecurrenceRule,
from: Date,
interval: number
): Generator<Date> {
let cur = addDays(from, interval);
for (;;) {
if (
!rule.byDay?.length ||
(rule.byDay as number[]).includes(cur.getDay())
) {
yield cur;
}
cur = addDays(cur, interval);
}
}
/** Generate candidates for FREQ=WEEKLY. */
export function* generateWeekly(
rule: RecurrenceRule,
from: Date,
interval: number
): Generator<Date> {
if (rule.byDay && rule.byDay.length > 0) {
let weekStart = new Date(
from.getFullYear(),
from.getMonth(),
from.getDate() - from.getDay(),
0,
0,
0,
0
);
for (;;) {
const days = (rule.byDay as number[]).slice().sort((a, b) => a - b);
for (const dow of days) {
const candidate = addDays(weekStart, dow);
if (candidate > from) yield candidate;
}
weekStart = addDays(weekStart, interval * 7);
}
} else {
let cur = addDays(from, interval * 7);
for (;;) {
yield cur;
cur = addDays(cur, interval * 7);
}
}
}
/** Generate candidates for FREQ=MONTHLY. */
export function* generateMonthly(
rule: RecurrenceRule,
from: Date,
interval: number
): Generator<Date> {
if (rule.byMonthDay && rule.byMonthDay.length > 0) {
let year = from.getFullYear();
let month = from.getMonth() + 1;
for (;;) {
const days = (rule.byMonthDay as number[])
.slice()
.sort((a, b) => a - b);
for (const d of days) {
const maxDay = daysInMonth(year, month);
if (d > maxDay) continue;
const candidate = new Date(year, month - 1, d, 0, 0, 0, 0);
if (candidate > from) yield candidate;
}
month += interval;
while (month > 12) {
month -= 12;
year += 1;
}
}
} else if (rule.byDay && rule.byDay.length > 0) {
let year = from.getFullYear();
let month = from.getMonth() + 1;
for (;;) {
const count = daysInMonth(year, month);
for (let d = 1; d <= count; d++) {
const candidate = new Date(year, month - 1, d, 0, 0, 0, 0);
if (
candidate > from &&
(rule.byDay as number[]).includes(candidate.getDay())
) {
yield candidate;
}
}
month += interval;
while (month > 12) {
month -= 12;
year += 1;
}
}
} else {
let cur = addMonths(from, interval);
for (;;) {
yield cur;
cur = addMonths(cur, interval);
}
}
}
/** Generate candidates for FREQ=YEARLY. */
export function* generateYearly(
rule: RecurrenceRule,
from: Date,
interval: number
): Generator<Date> {
if (rule.byMonthDay && rule.byMonthDay.length > 0) {
let cur = addYears(from, interval);
for (;;) {
const days = (rule.byMonthDay as number[])
.slice()
.sort((a, b) => a - b);
for (const d of days) {
const candidate = new Date(
cur.getFullYear(),
cur.getMonth(),
d,
0,
0,
0,
0
);
yield candidate;
}
cur = addYears(cur, interval);
}
} else if (rule.byDay && rule.byDay.length > 0) {
let cur = addYears(from, interval);
for (;;) {
if ((rule.byDay as number[]).includes(cur.getDay())) yield cur;
cur = addDays(cur, 1);
}
} else {
let cur = addYears(from, interval);
for (;;) {
yield cur;
cur = addYears(cur, interval);
}
}
}
// ---------------------------------------------------------------------------
// Public: unified candidate generator
// ---------------------------------------------------------------------------
/**
* Generate candidate dates for a rule starting strictly after `from`.
*
* For FREQ=DAILY/WEEKLY: step the base date and optionally filter by BYDAY.
* For FREQ=MONTHLY + BYMONTHDAY: emit the specified day-of-month in each month.
* For FREQ=MONTHLY + BYDAY: emit the specified weekdays found in each month.
* For FREQ=YEARLY: step by year, apply optional filters.
*/
export function* generateCandidates(
rule: RecurrenceRule,
from: Date
): Generator<Date> {
const interval = rule.interval ?? 1;
if (rule.freq === "daily") {
yield* generateDaily(rule, from, interval);
} else if (rule.freq === "weekly") {
yield* generateWeekly(rule, from, interval);
} else if (rule.freq === "monthly") {
yield* generateMonthly(rule, from, interval);
} else {
yield* generateYearly(rule, from, interval);
}
}

View File

@@ -0,0 +1,98 @@
# recurrence-helpers
## Purpose
`recurrence-helpers` provides the internal constants and low-level date arithmetic utilities shared across the recurrence sub-modules of `@suaveplan/datetime`. It contains the frequency/day-name mappings used by the RRULE parser and formatter, and the `addDays`, `addMonths`, `addYears`, `daysInMonth`, `toRRuleDate`, and `fromRRuleDate` helpers used by the candidate generators.
This module is an internal implementation detail. All public API is exposed through `recurrence.ts`. Direct imports are supported but not part of the documented public surface.
## Features
- `FREQ_MAP` — maps RRULE `FREQ` strings to `Frequency` values
- `FREQ_RRULE` — maps `Frequency` values back to RRULE strings
- `DAY_NAME` / `DAY_INDEX` — bidirectional weekday ↔ abbreviation maps
- `toRRuleDate` — format a `Date` as `YYYYMMDD`
- `fromRRuleDate` — parse `YYYYMMDD` (or `YYYYMMDDTHHmmssZ`) into a `Date`
- `daysInMonth` — days in a 1-indexed month (local copy for recurrence module independence)
- `addDays` / `addMonths` / `addYears` — safe date arithmetic with month-end clamping
## Usage: Basic Example
```ts
import { toRRuleDate, fromRRuleDate, addDays } from "./recurrence-helpers.js";
const d = new Date(2024, 0, 31);
console.log(toRRuleDate(d)); // "20240131"
const parsed = fromRRuleDate("20241231");
console.log(parsed.getMonth()); // 11 (December)
const next = addDays(d, 7);
console.log(next.getDate()); // 7 (Feb 7 2024)
```
## Usage: Advanced Example
```ts
import { addMonths, addYears, daysInMonth } from "./recurrence-helpers.js";
// Month-end clamping: Jan 31 + 1 month = Feb 29 (leap year 2024)
const jan31 = new Date(2024, 0, 31);
const feb = addMonths(jan31, 1);
console.log(feb.getDate()); // 29
// Year addition uses addMonths internally
const twoYearsLater = addYears(jan31, 2);
console.log(twoYearsLater.getFullYear()); // 2026
// Days in February 2024 (leap year)
console.log(daysInMonth(2024, 2)); // 29
```
## API Reference
### `FREQ_MAP: Record<string, Frequency>`
Maps uppercase RRULE frequency strings (`"DAILY"`, `"WEEKLY"`, `"MONTHLY"`, `"YEARLY"`) to their `Frequency` type values.
### `FREQ_RRULE: Record<Frequency, string>`
Inverse of `FREQ_MAP`. Maps `Frequency` type values back to uppercase RRULE strings.
### `DAY_NAME: Record<Weekday, string>`
Maps weekday indices (0–6) to two-letter RRULE abbreviations (`"SU"` … `"SA"`).
### `DAY_INDEX: Record<string, Weekday>`
Maps RRULE day abbreviations to weekday indices.
### `toRRuleDate(d: Date): string`
Format `d` as `YYYYMMDD` with zero-padded year, month, and day.
### `fromRRuleDate(s: string): Date`
Parse `s` (either `YYYYMMDD` or `YYYYMMDDTHHmmssZ`) into a local-midnight `Date`. The time and timezone suffix are stripped.
### `daysInMonth(year: number, month: number): number`
Returns the number of days in the given 1-indexed month. Mirrors the implementation in `calendar-core` to keep this module self-contained.
### `addDays(d: Date, n: number): Date`
Add `n` days to `d` using millisecond arithmetic.
### `addMonths(d: Date, n: number): Date`
Add `n` months with day clamping to the last valid day of the resulting month.
### `addYears(d: Date, n: number): Date`
Add `n` years by delegating to `addMonths(d, n * 12)`.
## Implementation Notes
`addMonths` is the source of truth for month-end clamping in the recurrence engine. It handles month overflow (month > 12 rolls the year forward) and clamps the day to `daysInMonth(year, month)` using `Math.min`, ensuring that e.g. Jan 31 + 1 month → Feb 28/29 rather than Mar 2/3.
`daysInMonth` is intentionally duplicated from `calendar-core` rather than imported, to keep `recurrence-helpers` self-contained and free of cross-category imports.

View File

@@ -0,0 +1,89 @@
import type { Frequency, Weekday } from "../types/datetime.types.js";
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
export const FREQ_MAP: Record<string, Frequency> = {
DAILY: "daily",
WEEKLY: "weekly",
MONTHLY: "monthly",
YEARLY: "yearly",
};
export const FREQ_RRULE: Record<Frequency, string> = {
daily: "DAILY",
weekly: "WEEKLY",
monthly: "MONTHLY",
yearly: "YEARLY",
};
export const DAY_NAME: Record<Weekday, string> = {
0: "SU",
1: "MO",
2: "TU",
3: "WE",
4: "TH",
5: "FR",
6: "SA",
};
export const DAY_INDEX: Record<string, Weekday> = {
SU: 0,
MO: 1,
TU: 2,
WE: 3,
TH: 4,
FR: 5,
SA: 6,
};
// ---------------------------------------------------------------------------
// Date arithmetic helpers
// ---------------------------------------------------------------------------
/** Format a Date as `YYYYMMDD` (used inside RRULE UNTIL). */
export function toRRuleDate(d: Date): string {
const y = String(d.getFullYear()).padStart(4, "0");
const m = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
return `${y}${m}${day}`;
}
/** Parse a `YYYYMMDD` (or `YYYYMMDDTHHmmssZ`) string into a Date. */
export function fromRRuleDate(s: string): Date {
// Support both YYYYMMDD and YYYYMMDDTHHmmssZ
const clean = s.replace("T", "").replace("Z", "");
const y = Number(clean.slice(0, 4));
const mo = Number(clean.slice(4, 6)) - 1;
const d = Number(clean.slice(6, 8));
return new Date(y, mo, d, 0, 0, 0, 0);
}
/** Days in a given month (1-indexed). */
export function daysInMonth(year: number, month: number): number {
return new Date(year, month, 0).getDate();
}
/** Add months with day clamping (n must be positive). */
export function addMonths(d: Date, n: number): Date {
let year = d.getFullYear();
let month = d.getMonth() + 1 + n; // 1-indexed
while (month > 12) {
month -= 12;
year += 1;
}
const maxDay = daysInMonth(year, month);
const day = Math.min(d.getDate(), maxDay);
return new Date(year, month - 1, day, 0, 0, 0, 0);
}
/** Add years. */
export function addYears(d: Date, n: number): Date {
return addMonths(d, n * 12);
}
/** Add days. */
export function addDays(d: Date, n: number): Date {
return new Date(d.getTime() + n * 24 * 60 * 60 * 1000);
}

View File

@@ -0,0 +1,288 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import { expandRecurrence, parseRRule } from "./recurrence.js";
describe("expandRecurrence", () => {
it("throws INFINITE_EXPANSION when no count or until", {
timeout: 5000,
}, () => {
const rule = parseRRule("FREQ=DAILY");
let err: unknown;
try {
expandRecurrence(rule);
} catch (e) {
err = e;
}
expect((err as { code?: string }).code).toBe(
"DATETIME.RECURRENCE.INFINITE_EXPANSION"
);
});
it("expands COUNT=5 daily", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=DAILY;COUNT=5");
const clock = () => new Date(2024, 0, 1).getTime();
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(5);
expect(dates[0]?.getDate()).toBe(2);
expect(dates[4]?.getDate()).toBe(6);
});
it("expands UNTIL bound", { timeout: 5000 }, () => {
const clock = () => new Date(2024, 0, 1).getTime();
const rule = parseRRule("FREQ=DAILY;UNTIL=20240105");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(4); // Jan 2,3,4,5
});
it("expands daily with BYDAY filter (skips non-matching weekdays)", {
timeout: 5000,
}, () => {
// FREQ=DAILY;BYDAY=MO generates only Mondays, skipping Tue–Sun
const clock = () => new Date(2024, 2, 11).getTime(); // Mon Mar 11
const rule = parseRRule("FREQ=DAILY;BYDAY=MO;COUNT=2");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(2);
for (const d of dates) {
expect(d.getDay()).toBe(1); // Monday
}
// Verify next Monday is Mar 18 (7 days later, not 1 day)
expect(dates[0]?.getDate()).toBe(18);
});
it("expands weekly BYDAY", { timeout: 5000 }, () => {
const clock = () => new Date(2024, 2, 11).getTime(); // Mon
const rule = parseRRule("FREQ=WEEKLY;BYDAY=MO,WE,FR;COUNT=6");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(6);
for (const d of dates) {
expect([1, 3, 5]).toContain(d.getDay());
}
});
it("expands monthly BYMONTHDAY", { timeout: 5000 }, () => {
const clock = () => new Date(2024, 0, 1).getTime();
const rule = parseRRule("FREQ=MONTHLY;BYMONTHDAY=15;COUNT=3");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(3);
for (const d of dates) {
expect(d.getDate()).toBe(15);
}
});
it("expands monthly BYMONTHDAY multiple days (exercises sort)", {
timeout: 5000,
}, () => {
const clock = () => new Date(2024, 0, 1).getTime();
const rule = parseRRule("FREQ=MONTHLY;BYMONTHDAY=10,20;COUNT=4");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(4);
// Should be Jan 10, Jan 20, Feb 10, Feb 20
expect(dates[0]?.getDate()).toBe(10);
expect(dates[1]?.getDate()).toBe(20);
});
it("expands monthly BYMONTHDAY crossing year boundary", {
timeout: 5000,
}, () => {
// Start in December, interval=1, crosses to January next year
const clock = () => new Date(2024, 11, 1).getTime(); // Dec 1 2024
const rule = parseRRule("FREQ=MONTHLY;BYMONTHDAY=15;COUNT=3");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(3);
// Dec 15 2024, Jan 15 2025, Feb 15 2025
expect(dates[0]?.getMonth()).toBe(11); // December
expect(dates[1]?.getFullYear()).toBe(2025);
expect(dates[1]?.getMonth()).toBe(0); // January
});
it("expands monthly BYDAY crossing year boundary", {
timeout: 5000,
}, () => {
// Start in December, get Mondays in each month for 2 months (crosses to Jan 2025)
const clock = () => new Date(2024, 11, 30).getTime(); // Dec 30 2024
const rule = {
freq: "monthly" as const,
byDay: [1 as const],
count: 4,
interval: 1,
};
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(4);
for (const d of dates) {
expect(d.getDay()).toBe(1); // Monday
}
// Month rolls from Dec to Jan — should see 2025
const years = new Set(dates.map((d) => d.getFullYear()));
expect(years.size).toBeGreaterThanOrEqual(1);
});
it("respects abort signal", { timeout: 5000 }, () => {
const controller = new AbortController();
controller.abort();
const rule = parseRRule("FREQ=DAILY;COUNT=1000");
const clock = () => new Date(2024, 0, 1).getTime();
const dates = expandRecurrence(rule, {
clock,
signal: controller.signal,
});
// Should return empty or partial since aborted immediately
expect(Array.isArray(dates)).toBe(true);
});
it("checks signal at 64-occurrence boundary", { timeout: 5000 }, () => {
// Abort after 64 occurrences by using a counter inside the signal check
const controller = new AbortController();
const rule = parseRRule("FREQ=DAILY;COUNT=200");
const clock = () => new Date(2024, 0, 1).getTime();
// Abort signal immediately to confirm expansion terminates before 200
controller.abort();
const dates = expandRecurrence(rule, {
clock,
signal: controller.signal,
});
// Since signal is already aborted, the loop breaks on first check
expect(dates.length).toBeLessThanOrEqual(200);
// Should be 0 since we abort before the loop body
expect(dates.length).toBe(0);
});
it("expands yearly COUNT=3", { timeout: 5000 }, () => {
const clock = () => new Date(2024, 0, 1).getTime();
const rule = parseRRule("FREQ=YEARLY;COUNT=3");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(3);
expect(dates[0]?.getFullYear()).toBe(2025);
expect(dates[1]?.getFullYear()).toBe(2026);
expect(dates[2]?.getFullYear()).toBe(2027);
});
it("expands yearly BYMONTHDAY", { timeout: 5000 }, () => {
const clock = () => new Date(2024, 0, 1).getTime();
const rule = parseRRule("FREQ=YEARLY;BYMONTHDAY=1;COUNT=2");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(2);
expect(dates[0]?.getFullYear()).toBe(2025);
expect(dates[0]?.getDate()).toBe(1);
});
it("expands yearly BYDAY (first matching weekday in each year)", {
timeout: 5000,
}, () => {
// Expand 2 years forward, finding Mondays
const clock = () => new Date(2024, 0, 1).getTime();
const rule = { freq: "yearly" as const, byDay: [1 as const], count: 2 };
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(2);
for (const d of dates) {
expect(d.getDay()).toBe(1); // Monday
}
});
it("expands monthly BYDAY (weekdays in each month)", {
timeout: 5000,
}, () => {
const clock = () => new Date(2024, 0, 1).getTime();
// Emit all Mondays in each month, get first 4
const rule = {
freq: "monthly" as const,
byDay: [1 as const],
count: 4,
};
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(4);
for (const d of dates) {
expect(d.getDay()).toBe(1); // Monday
}
});
it("expands yearly BYMONTHDAY (multiple day-of-months)", {
timeout: 5000,
}, () => {
const clock = () => new Date(2024, 0, 1).getTime();
const rule = parseRRule("FREQ=YEARLY;BYMONTHDAY=1,15;COUNT=4");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(4);
// 2025-01-01, 2025-01-15, 2026-01-01, 2026-01-15 (roughly)
for (const d of dates) {
expect([1, 15]).toContain(d.getDate());
}
});
it("expands weekly plain (no BYDAY)", { timeout: 5000 }, () => {
const clock = () => new Date(2024, 2, 11).getTime(); // Mon
const rule = parseRRule("FREQ=WEEKLY;COUNT=4");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(4);
for (const d of dates) {
expect(d.getDay()).toBe(1); // Always Monday (same dow as start)
}
});
it("expands monthly plain (no BYMONTHDAY or BYDAY)", {
timeout: 5000,
}, () => {
const clock = () => new Date(2024, 0, 15).getTime();
const rule = parseRRule("FREQ=MONTHLY;COUNT=3");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(3);
for (const d of dates) {
expect(d.getDate()).toBe(15);
}
});
it("uses wall clock when no clock provided", { timeout: 5000 }, () => {
// No clock option — uses Date.now()
const rule = parseRRule("FREQ=DAILY;COUNT=3");
const dates = expandRecurrence(rule);
expect(dates.length).toBe(3);
});
it("monthly BYMONTHDAY=31 skips months with fewer days", {
timeout: 5000,
}, () => {
// Feb doesn't have day 31, so should be skipped
const clock = () => new Date(2024, 0, 1).getTime(); // Jan 2024
const rule = parseRRule("FREQ=MONTHLY;BYMONTHDAY=31;COUNT=3");
const dates = expandRecurrence(rule, { clock });
// Jan 31, Mar 31, May 31 (Feb and Apr skipped)
expect(dates.length).toBe(3);
expect(dates[0]?.getDate()).toBe(31);
// None should be in February or April
const months = dates.map((d) => d.getMonth());
expect(months).not.toContain(1); // February
});
it("respects signal abort at 64-occurrence boundary", {
timeout: 5000,
}, () => {
const controller = new AbortController();
const clock = () => new Date(2024, 0, 1).getTime();
const rule = parseRRule("FREQ=DAILY;COUNT=200");
// Abort after 65 occurrences — the check at `generated % 64 === 0` fires at 64
const count = 0;
const signal = controller.signal;
const results = expandRecurrence(rule, {
clock,
signal,
});
// With signal NOT aborted, get full 200
expect(results.length).toBe(200);
// Now test with pre-aborted signal at boundary
const ctrl2 = new AbortController();
// Abort immediately; the check at line 411 fires before first candidate
ctrl2.abort();
const results2 = expandRecurrence(parseRRule("FREQ=DAILY;COUNT=200"), {
clock,
signal: ctrl2.signal,
});
expect(results2.length).toBe(0);
void count;
});
it("expandRecurrence with UNTIL bound (yearly)", { timeout: 5000 }, () => {
const clock = () => new Date(2023, 0, 1).getTime();
const rule = parseRRule("FREQ=YEARLY;UNTIL=20250101");
const dates = expandRecurrence(rule, { clock });
expect(dates.length).toBe(2); // 2024 and 2025
});
});

View File

@@ -0,0 +1,102 @@
# recurrence
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
The `recurrence` module implements a simplified iCalendar-compatible recurrence rule engine for `@suaveplan/datetime`. It provides parsing, formatting, and expansion of RRULE-style recurrence rules covering the most common scheduling patterns: daily, weekly, monthly, and yearly recurrences with interval, count, until, by-day-of-week, and by-day-of-month filters.
The design prioritises correctness and safety over exhaustiveness: it deliberately excludes the more exotic RFC 5545 features (BYSETPOS, BYHOUR, EXDATE, etc.) in order to maintain a clear, auditable code path that cannot produce runaway expansions.
## Features
- `parseRRule` — parse RRULE string into a typed `RecurrenceRule`
- `formatRRule` — serialise `RecurrenceRule` back to RRULE string (round-trippable)
- `nextOccurrence` — compute the next single occurrence after a given date
- `expandRecurrence` — expand all occurrences with `count` or `until` bound (required)
- Cooperative cancellation via `AbortSignal` (checked every 64 occurrences)
- OTel histogram integration via `recordExpandRecurrence`
- `clock` injection for deterministic tests
## Usage: Basic Example
```ts
import { parseRRule, expandRecurrence } from "@suaveplan/datetime/recurrence";
const rule = parseRRule("FREQ=WEEKLY;BYDAY=MO,WE,FR;COUNT=6");
const dates = expandRecurrence(rule);
console.log(dates.length); // 6
console.log(dates[0].toDateString()); // next Monday/Wednesday/Friday
```
## Usage: Advanced Example
```ts
import {
parseRRule,
formatRRule,
nextOccurrence,
expandRecurrence,
} from "@suaveplan/datetime/recurrence";
// Round-trip an RRULE string
const raw = "FREQ=MONTHLY;BYMONTHDAY=15;COUNT=3";
const rule = parseRRule(raw);
const formatted = formatRRule(rule);
console.log(formatted === raw); // true
// Deterministic expansion with a fake clock and abort signal
const clock = () => new Date("2024-01-01T00:00:00Z").getTime();
const controller = new AbortController();
const dates = expandRecurrence(
parseRRule("FREQ=DAILY;COUNT=365"),
{ clock, signal: controller.signal }
);
console.log(dates.length); // 365
// Next weekly occurrence on Mondays
const next = nextOccurrence(
parseRRule("FREQ=WEEKLY;BYDAY=MO"),
new Date("2024-03-13") // Wednesday
);
console.log(next?.toDateString()); // Mon Mar 18 2024
```
## API Reference
### `parseRRule(input: string): RecurrenceRule`
Parse a semicolon-delimited RRULE string. Supported fields:
- `FREQ` (required): `DAILY | WEEKLY | MONTHLY | YEARLY`
- `INTERVAL`: positive integer, defaults to 1
- `COUNT`: positive integer
- `UNTIL`: `YYYYMMDD` or `YYYYMMDDTHHmmssZ`
- `BYDAY`: comma-separated `SU|MO|TU|WE|TH|FR|SA`
- `BYMONTHDAY`: comma-separated integers 1–31
Throws `DatetimeError("DATETIME.PARSE.INVALID_INPUT")` when `FREQ` is missing or unrecognised.
### `formatRRule(rule: RecurrenceRule): string`
Serialise a `RecurrenceRule` to an RRULE string. Output is round-trippable through `parseRRule`.
### `nextOccurrence(rule: RecurrenceRule, from: DateInput): Date | null`
Returns the first occurrence strictly after `from` that matches all filters. Returns `null` when the rule terminates (`until` exceeded or `count` exhausted) before generating a match.
### `expandRecurrence(rule: RecurrenceRule, opts?: RecurrenceOptions): Date[]`
Expand all occurrences into a `Date[]`. Requires `rule.count` or `rule.until`; throws `DatetimeError("DATETIME.RECURRENCE.INFINITE_EXPANSION")` when neither is set.
- `opts.clock` — injectable `Clock` to set the expansion start point (default: `Date.now`)
- `opts.signal` — `AbortSignal` checked every 64 occurrences
## Implementation Notes
The expansion loop uses an internal safety limit of `count * 10 + 10000` to guard against degenerate filter combinations (e.g. `FREQ=MONTHLY;BYMONTHDAY=31;COUNT=100` in months shorter than 31 days). In practice this limit is never reached for well-formed rules.
Month arithmetic uses the same clamping strategy as `calendar.addDuration`, so `FREQ=MONTHLY;BYMONTHDAY=31` in February produces no occurrence for that month rather than overflowing into March.
`nextOccurrence` does not require `count` or `until` since it only generates a single result, but it applies a 3,650-iteration safety cap (~10 years of daily occurrences) before returning `null`.

View File

@@ -0,0 +1,68 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import { nextOccurrence, parseRRule } from "./recurrence.js";
describe("nextOccurrence", () => {
it("returns next daily occurrence", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=DAILY;COUNT=10");
const from = new Date(2024, 0, 1);
const next = nextOccurrence(rule, from);
expect(next?.getDate()).toBe(2);
});
it("returns next weekly occurrence on correct day", {
timeout: 5000,
}, () => {
// From Wednesday, next Monday
const rule = parseRRule("FREQ=WEEKLY;BYDAY=MO");
const from = new Date(2024, 2, 13); // Wed
const next = nextOccurrence(rule, from);
expect(next?.getDay()).toBe(1); // Monday
expect(next?.getDate()).toBe(18);
});
it("returns null when until exceeded before match", {
timeout: 5000,
}, () => {
const rule = parseRRule("FREQ=WEEKLY;BYDAY=MO;UNTIL=20240315");
const from = new Date(2024, 2, 14); // Thu - next Mon would be Mar 18, after until
const next = nextOccurrence(rule, from);
expect(next).toBeNull();
});
it("returns next monthly occurrence", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=MONTHLY;BYMONTHDAY=15;COUNT=3");
const from = new Date(2024, 0, 15);
const next = nextOccurrence(rule, from);
expect(next?.getDate()).toBe(15);
expect(next?.getMonth()).toBe(1); // February
});
it("returns next yearly occurrence", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=YEARLY;COUNT=3");
const from = new Date(2024, 0, 1);
const next = nextOccurrence(rule, from);
expect(next?.getFullYear()).toBe(2025);
});
it("returns null when no match found within safety limit", {
timeout: 5000,
}, () => {
// BYMONTHDAY=31 on a MONTHLY rule — most months won't match
// but eventually one will (any month with 31 days)
// Let's test count exhaustion scenario
const _rule = parseRRule("FREQ=DAILY;COUNT=1");
// from = already at the only count (manually set an expired until)
const until = new Date(2024, 0, 1);
const ruleWithUntil = { freq: "daily" as const, until };
const from = new Date(2024, 0, 2);
const next = nextOccurrence(ruleWithUntil, from);
expect(next).toBeNull();
});
it("BYDAY=[] filter matches any weekday", { timeout: 5000 }, () => {
const rule = { freq: "weekly" as const, count: 3 };
const from = new Date(2024, 2, 13); // Wed
const next = nextOccurrence(rule, from);
expect(next).not.toBeNull();
});
});

View File

@@ -0,0 +1,157 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import * as fc from "fast-check";
import { formatRRule, parseRRule } from "./recurrence.js";
describe("parseRRule", () => {
it("parses FREQ=DAILY", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=DAILY");
expect(rule.freq).toBe("daily");
});
it("parses FREQ=WEEKLY", { timeout: 5000 }, () => {
expect(parseRRule("FREQ=WEEKLY").freq).toBe("weekly");
});
it("parses FREQ=MONTHLY", { timeout: 5000 }, () => {
expect(parseRRule("FREQ=MONTHLY").freq).toBe("monthly");
});
it("parses FREQ=YEARLY", { timeout: 5000 }, () => {
expect(parseRRule("FREQ=YEARLY").freq).toBe("yearly");
});
it("parses INTERVAL", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=WEEKLY;INTERVAL=2");
expect(rule.interval).toBe(2);
});
it("parses COUNT", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=DAILY;COUNT=5");
expect(rule.count).toBe(5);
});
it("parses UNTIL (YYYYMMDD)", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=DAILY;UNTIL=20241231");
expect(rule.until?.getFullYear()).toBe(2024);
expect(rule.until?.getMonth()).toBe(11);
expect(rule.until?.getDate()).toBe(31);
});
it("parses UNTIL with time suffix", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=DAILY;UNTIL=20241231T000000Z");
expect(rule.until?.getFullYear()).toBe(2024);
});
it("parses BYDAY", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=WEEKLY;BYDAY=MO,WE,FR");
expect(rule.byDay).toEqual([1, 3, 5]);
});
it("parses BYMONTHDAY", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=MONTHLY;BYMONTHDAY=15");
expect(rule.byMonthDay).toEqual([15]);
});
it("ignores parts without '=' sign", { timeout: 5000 }, () => {
// Covers the `if (eq === -1) continue` branch in the parser loop
const rule = parseRRule("FREQ=DAILY;BADPART;COUNT=3");
expect(rule.freq).toBe("daily");
expect(rule.count).toBe(3);
});
it("throws for missing FREQ", { timeout: 5000 }, () => {
let err: unknown;
try {
parseRRule("INTERVAL=2");
} catch (e) {
err = e;
}
expect((err as { code?: string }).code).toBe(
"DATETIME.PARSE.INVALID_INPUT"
);
});
it("throws for unknown FREQ", { timeout: 5000 }, () => {
let err: unknown;
try {
parseRRule("FREQ=HOURLY");
} catch (e) {
err = e;
}
expect((err as { code?: string }).code).toBe(
"DATETIME.PARSE.INVALID_INPUT"
);
});
it("handles all day abbreviations", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=WEEKLY;BYDAY=SU,MO,TU,WE,TH,FR,SA");
expect(rule.byDay).toEqual([0, 1, 2, 3, 4, 5, 6]);
});
});
describe("formatRRule", () => {
it("formats basic rule", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=DAILY;COUNT=5");
expect(formatRRule(rule)).toBe("FREQ=DAILY;COUNT=5");
});
it("formats UNTIL", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=WEEKLY;UNTIL=20241231");
const formatted = formatRRule(rule);
expect(formatted).toContain("UNTIL=20241231");
});
it("formats BYDAY", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=WEEKLY;BYDAY=MO,WE,FR;COUNT=6");
const formatted = formatRRule(rule);
expect(formatted).toContain("BYDAY=MO,WE,FR");
expect(formatted).toContain("FR");
});
it("formats all day abbreviations round-trip", { timeout: 5000 }, () => {
const rule = parseRRule(
"FREQ=WEEKLY;BYDAY=SU,MO,TU,WE,TH,FR,SA;COUNT=1"
);
const formatted = formatRRule(rule);
expect(formatted).toContain("SU");
expect(formatted).toContain("MO");
expect(formatted).toContain("TU");
expect(formatted).toContain("WE");
expect(formatted).toContain("TH");
expect(formatted).toContain("FR");
expect(formatted).toContain("SA");
});
it("formats BYMONTHDAY", { timeout: 5000 }, () => {
const rule = parseRRule("FREQ=MONTHLY;BYMONTHDAY=15;COUNT=3");
expect(formatRRule(rule)).toContain("BYMONTHDAY=15");
});
it("formats INTERVAL", { timeout: 5000 }, () => {
// Ensures the `if (rule.interval !== undefined)` branch is taken
const rule = parseRRule("FREQ=WEEKLY;INTERVAL=2;COUNT=4");
const formatted = formatRRule(rule);
expect(formatted).toContain("INTERVAL=2");
});
it("parseRRule → formatRRule → parseRRule identity (property test)", {
timeout: 30000,
}, () => {
const freqs = ["DAILY", "WEEKLY", "MONTHLY", "YEARLY"] as const;
fc.assert(
fc.property(
fc.constantFrom(...freqs),
fc.integer({ min: 1, max: 10 }),
(freq, count) => {
const input = `FREQ=${freq};COUNT=${count}`;
const parsed = parseRRule(input);
const formatted = formatRRule(parsed);
const reparsed = parseRRule(formatted);
expect(reparsed.freq).toBe(parsed.freq);
expect(reparsed.count).toBe(parsed.count);
}
),
{ numRuns: 100 }
);
});
});

View File

@@ -0,0 +1,172 @@
import { toDate } from "../calendar/calendar.js";
import { DATETIME_CODES, DatetimeError } from "../errors/datetime-error.js";
import { recordExpandRecurrence } from "../otel/datetime-otel.js";
import type {
DateInput,
RecurrenceOptions,
RecurrenceRule,
Weekday,
} from "../types/datetime.types.js";
import { generateCandidates } from "./recurrence-generate.js";
import {
DAY_INDEX,
DAY_NAME,
FREQ_MAP,
FREQ_RRULE,
fromRRuleDate,
toRRuleDate,
} from "./recurrence-helpers.js";
// Re-export sub-module symbols so all existing import paths keep working.
export { generateCandidates } from "./recurrence-generate.js";
// ---------------------------------------------------------------------------
// Public: parse / format
// ---------------------------------------------------------------------------
/**
* Parse a simplified RRULE string into a `RecurrenceRule`.
*
* Supported fields: `FREQ`, `INTERVAL`, `COUNT`, `UNTIL`, `BYDAY`, `BYMONTHDAY`.
*
* @example `"FREQ=WEEKLY;INTERVAL=2;BYDAY=MO,WE,FR;COUNT=10"`
*/
export function parseRRule(input: string): RecurrenceRule {
const parts = input.trim().split(";");
const map: Record<string, string> = {};
for (const part of parts) {
const eq = part.indexOf("=");
if (eq === -1) continue;
map[part.slice(0, eq).toUpperCase()] = part.slice(eq + 1);
}
const freqRaw = map["FREQ"];
if (freqRaw === undefined) {
throw new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input",
{ context: { input, reason: "FREQ is required" } }
);
}
const freq = FREQ_MAP[freqRaw.toUpperCase()];
if (freq === undefined) {
throw new DatetimeError(
DATETIME_CODES["PARSE.INVALID_INPUT"],
"datetime.parse.invalid_input",
{ context: { input, reason: `unknown FREQ: ${freqRaw}` } }
);
}
const rule: RecurrenceRule = { freq };
if (map["INTERVAL"] !== undefined) {
rule.interval = Number.parseInt(map["INTERVAL"], 10);
}
if (map["COUNT"] !== undefined) {
rule.count = Number.parseInt(map["COUNT"], 10);
}
if (map["UNTIL"] !== undefined) {
rule.until = fromRRuleDate(map["UNTIL"]);
}
if (map["BYDAY"] !== undefined) {
rule.byDay = map["BYDAY"]
.split(",")
.map((s) => {
const key = s.trim().toUpperCase().slice(-2);
return DAY_INDEX[key] as Weekday;
})
.filter((d) => d !== undefined);
}
if (map["BYMONTHDAY"] !== undefined) {
rule.byMonthDay = map["BYMONTHDAY"]
.split(",")
.map((s) => Number.parseInt(s.trim(), 10));
}
return rule;
}
/**
* Serialise a `RecurrenceRule` back into an RRULE string.
*
* The output can be round-tripped through `parseRRule`.
*/
export function formatRRule(rule: RecurrenceRule): string {
const parts: string[] = [`FREQ=${FREQ_RRULE[rule.freq]}`];
if (rule.interval !== undefined) parts.push(`INTERVAL=${rule.interval}`);
if (rule.count !== undefined) parts.push(`COUNT=${rule.count}`);
if (rule.until !== undefined)
parts.push(`UNTIL=${toRRuleDate(rule.until)}`);
if (rule.byDay !== undefined && rule.byDay.length > 0) {
parts.push(`BYDAY=${rule.byDay.map((d) => DAY_NAME[d]).join(",")}`);
}
if (rule.byMonthDay !== undefined && rule.byMonthDay.length > 0) {
parts.push(`BYMONTHDAY=${rule.byMonthDay.join(",")}`);
}
return parts.join(";");
}
// ---------------------------------------------------------------------------
// Public: next occurrence
// ---------------------------------------------------------------------------
/**
* Returns the next occurrence of `rule` strictly after `from`, or `null` when
* the rule terminates before generating another occurrence.
*/
export function nextOccurrence(
rule: RecurrenceRule,
from: DateInput
): Date | null {
const fromDate = toDate(from);
const candidate = generateCandidates(rule, fromDate).next().value as Date;
if (rule.until !== undefined && candidate > rule.until) return null;
return candidate;
}
// ---------------------------------------------------------------------------
// Public: full expansion
// ---------------------------------------------------------------------------
/**
* Expand all occurrences of `rule`.
*
* Requires exactly one of `rule.count` or `rule.until`; throws
* `DatetimeError(DATETIME.RECURRENCE.INFINITE_EXPANSION)` when neither is set.
*
* Checks `opts.signal` every iteration for cooperative cancellation.
*/
export function expandRecurrence(
rule: RecurrenceRule,
opts?: RecurrenceOptions
): Date[] {
if (rule.count === undefined && rule.until === undefined) {
throw new DatetimeError(
DATETIME_CODES["RECURRENCE.INFINITE_EXPANSION"],
"datetime.recurrence.infinite_expansion",
{ context: { rule: formatRRule(rule) } }
);
}
const signal = opts?.signal;
const results: Date[] = [];
const start = new Date((opts?.clock ?? (() => Date.now()))());
const t0 = Date.now();
let generated = 0;
for (const candidate of generateCandidates(rule, start)) {
if (signal?.aborted) break;
if (rule.until !== undefined && candidate > rule.until) break;
results.push(candidate);
generated += 1;
if (rule.count !== undefined && generated >= rule.count) break;
}
recordExpandRecurrence(Date.now() - t0);
return results;
}

View File

@@ -0,0 +1 @@
export { diffInUnits, formatRelative, timeAgo, timeUntil } from "./relative";

View File

@@ -0,0 +1,84 @@
# relative
<!-- begin:auto-docs -->
_(no submodules)_
<!-- end:auto-docs -->
## Purpose
The `relative` module provides human-readable relative-time formatting for `@suaveplan/datetime`. It converts the distance between two moments into concise English phrases like `"3 days ago"`, `"in 2 hours"`, or `"just now"`. The `clock` injection point makes all functions deterministic in tests, while the unified `formatRelative` entry point subsumes the common `timeAgo` / `timeUntil` aliases.
The module also exposes `diffInUnits`, a lower-level utility that returns the signed numeric difference between two `DateInput` values in any `DurationUnit`. This is useful when callers need the raw integer delta rather than a formatted string.
## Features
- `diffInUnits` — signed numeric difference in any `DurationUnit`
- `formatRelative` — threshold-based English string (past and future)
- `timeAgo` — convenience alias for past-relative formatting
- `timeUntil` — convenience alias for future-relative formatting
- Pluggable `Clock` for deterministic rendering in tests
- `"just now"` threshold for differences under 45 seconds
## Usage: Basic Example
```ts
import { timeAgo, timeUntil } from "@suaveplan/datetime/relative";
// Using wall clock
console.log(timeAgo(new Date(Date.now() - 3 * 60_000))); // "3 minutes ago"
console.log(timeUntil(new Date(Date.now() + 2 * 3600_000))); // "in 2 hours"
```
## Usage: Advanced Example
```ts
import { diffInUnits, formatRelative } from "@suaveplan/datetime/relative";
// Deterministic with a fake clock
const clock = () => new Date("2024-06-01T12:00:00Z").getTime();
const pastDate = "2024-05-28T12:00:00Z";
console.log(formatRelative(pastDate, { clock })); // "4 days ago"
console.log(diffInUnits(pastDate, "2024-06-01T12:00:00Z", "days")); // 4
// Sub-unit precision
const oneHourAgo = new Date(clock() - 3723_000); // 1h 2m 3s ago
console.log(formatRelative(oneHourAgo, { clock })); // "1 hour ago"
console.log(diffInUnits(oneHourAgo, new Date(clock()), "seconds")); // 3723
```
## API Reference
### `diffInUnits(a: DateInput, b: DateInput, unit: DurationUnit): number`
Returns `floor((b − a) / unitMs)` truncated toward zero. Positive when `b > a`.
- `a` — start date (any `DateInput`)
- `b` — end date (any `DateInput`)
- `unit` — one of the `DurationUnit` values
### `formatRelative(date: DateInput, opts?: RelativeTimeOptions): string`
Format the difference between `date` and `opts.clock()` (default: `Date.now()`).
- Distances under 45 seconds → `"just now"`
- Distances under 45 minutes → `"N seconds ago"` / `"in N seconds"`
- Distances under 22 hours → `"N minutes ago"` / `"in N minutes"`
- Distances under 26 days → `"N hours ago"` / `"in N hours"`
- Distances under 11 months → `"N days ago"` / `"in N days"`
- Otherwise → `"N months ago"` / `"in N months"` or `"N years ago"` / `"in N years"`
### `timeAgo(date: DateInput, opts?: RelativeTimeOptions): string`
Alias for `formatRelative`. Intended for past dates, but works symmetrically.
### `timeUntil(date: DateInput, opts?: RelativeTimeOptions): string`
Alias for `formatRelative`. Intended for future dates, but works symmetrically.
## Implementation Notes
Average month (30.4375 days) and average year (365.25 days) constants are used for the coarse `months` / `years` thresholds. These are approximations intentionally — precise calendar arithmetic for display strings would add complexity without improving user experience. Use `diffInUnits("months")` together with calendar arithmetic when you need exact month counts.
The threshold table mirrors the conventions used by popular libraries like `date-fns` and `moment.js` so that migrating code produces the same user-visible strings.
The `precision` field in `RelativeTimeOptions` is reserved for future use to cap the label at a specific unit (e.g. only show up to "days", never "hours"). Currently it is accepted but not applied in the implementation.

View File

@@ -0,0 +1,181 @@
import { describe, expect, it } from "@suaveplan/testing/runner";
import { diffInUnits, formatRelative, timeAgo, timeUntil } from "./relative.js";
const clock = (isoDate: string) => () => new Date(isoDate).getTime();
describe("diffInUnits", () => {
it("milliseconds", { timeout: 5000 }, () => {
expect(
diffInUnits(
"2024-01-01T00:00:00.000Z",
"2024-01-01T00:00:01.000Z",
"milliseconds"
)
).toBe(1000);
});
it("seconds", { timeout: 5000 }, () => {
expect(
diffInUnits(
"2024-01-01T00:00:00Z",
"2024-01-01T00:01:00Z",
"seconds"
)
).toBe(60);
});
it("minutes", { timeout: 5000 }, () => {
expect(
diffInUnits(
"2024-01-01T00:00:00Z",
"2024-01-01T01:00:00Z",
"minutes"
)
).toBe(60);
});
it("hours", { timeout: 5000 }, () => {
expect(
diffInUnits("2024-01-01T00:00:00Z", "2024-01-02T00:00:00Z", "hours")
).toBe(24);
});
it("days", { timeout: 5000 }, () => {
expect(diffInUnits("2024-01-01Z", "2024-01-08Z", "days")).toBe(7);
});
it("weeks", { timeout: 5000 }, () => {
expect(diffInUnits("2024-01-01Z", "2024-01-15Z", "weeks")).toBe(2);
});
it("months (approximate)", { timeout: 5000 }, () => {
// 365 days ≈ 12 months
const diff = diffInUnits("2024-01-01Z", "2025-01-01Z", "months");
expect(diff).toBeGreaterThanOrEqual(11);
expect(diff).toBeLessThanOrEqual(12);
});
it("years (approximate)", { timeout: 5000 }, () => {
const diff = diffInUnits("2024-01-01Z", "2026-01-01Z", "years");
// 2 years is approximately 730 days / 365.25 = 1.998... truncated = 1
// but actual ms is 2 * 365.25 * 86400000 which is exactly 2 years
expect(diff).toBeGreaterThanOrEqual(1);
expect(diff).toBeLessThanOrEqual(2);
});
it("negative when b < a", { timeout: 5000 }, () => {
expect(diffInUnits("2024-01-08Z", "2024-01-01Z", "days")).toBe(-7);
});
});
describe("formatRelative", () => {
it("'just now' for < 45s difference", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() - 30_000); // 30s ago
expect(formatRelative(d, { clock: clock(now) })).toBe("just now");
});
it("future 'just now' for < 45s", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() + 30_000);
expect(formatRelative(d, { clock: clock(now) })).toBe("just now");
});
it("'N seconds ago'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() - 120_000); // 2 min ago
expect(formatRelative(d, { clock: clock(now) })).toBe("2 minutes ago");
});
it("'in N seconds'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() + 90_000);
expect(formatRelative(d, { clock: clock(now) })).toBe("in 2 minutes");
});
it("'N hours ago'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() - 3 * 3_600_000);
expect(formatRelative(d, { clock: clock(now) })).toBe("3 hours ago");
});
it("'in N hours'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() + 5 * 3_600_000);
expect(formatRelative(d, { clock: clock(now) })).toBe("in 5 hours");
});
it("'N days ago'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() - 4 * 86_400_000);
expect(formatRelative(d, { clock: clock(now) })).toBe("4 days ago");
});
it("'in N days'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() + 10 * 86_400_000);
expect(formatRelative(d, { clock: clock(now) })).toBe("in 10 days");
});
it("'N months ago'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() - 60 * 86_400_000); // ~2 months
expect(formatRelative(d, { clock: clock(now) })).toBe("2 months ago");
});
it("'in N months'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() + 90 * 86_400_000); // ~3 months
expect(formatRelative(d, { clock: clock(now) })).toBe("in 3 months");
});
it("'N years ago'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() - 400 * 86_400_000); // > 11 months
expect(formatRelative(d, { clock: clock(now) })).toBe("1 year ago");
});
it("'in N years'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() + 800 * 86_400_000);
expect(formatRelative(d, { clock: clock(now) })).toBe("in 2 years");
});
it("singular 'minute'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() - 60_000);
expect(formatRelative(d, { clock: clock(now) })).toBe("1 minute ago");
});
it("singular 'hour'", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() - 3_600_000);
expect(formatRelative(d, { clock: clock(now) })).toBe("1 hour ago");
});
it("uses wall clock when no clock provided", { timeout: 5000 }, () => {
const d = new Date(Date.now() - 5000);
const result = formatRelative(d);
expect(result).toBe("just now");
});
});
describe("timeAgo", () => {
it("delegates to formatRelative", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() - 4 * 86_400_000);
expect(timeAgo(d, { clock: clock(now) })).toBe(
formatRelative(d, { clock: clock(now) })
);
});
});
describe("timeUntil", () => {
it("delegates to formatRelative", { timeout: 5000 }, () => {
const now = "2024-06-01T12:00:00.000Z";
const d = new Date(new Date(now).getTime() + 4 * 86_400_000);
expect(timeUntil(d, { clock: clock(now) })).toBe(
formatRelative(d, { clock: clock(now) })
);
});
});

View File

@@ -0,0 +1,146 @@
import { toDate } from "../calendar/calendar.js";
import type {
DateInput,
DurationUnit,
RelativeTimeOptions,
} from "../types/datetime.types.js";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
const MS = 1;
const SECOND = 1000 * MS;
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const WEEK = 7 * DAY;
const MONTH = 30.4375 * DAY; // average month in ms
const YEAR = 365.25 * DAY; // average year in ms
function nowMs(opts?: RelativeTimeOptions): number {
return opts?.clock !== undefined ? opts.clock() : Date.now();
}
// ---------------------------------------------------------------------------
// Public: diffInUnits
// ---------------------------------------------------------------------------
/**
* Return the signed difference between `a` and `b` in the given `unit`.
*
* Result is truncated toward zero (not rounded). Positive means `b > a`.
*/
export function diffInUnits(
a: DateInput,
b: DateInput,
unit: DurationUnit
): number {
const da = toDate(a).getTime();
const db = toDate(b).getTime();
const diffMs = db - da;
switch (unit) {
case "milliseconds":
return diffMs;
case "seconds":
return Math.trunc(diffMs / SECOND);
case "minutes":
return Math.trunc(diffMs / MINUTE);
case "hours":
return Math.trunc(diffMs / HOUR);
case "days":
return Math.trunc(diffMs / DAY);
case "weeks":
return Math.trunc(diffMs / WEEK);
case "months":
return Math.trunc(diffMs / MONTH);
case "years":
return Math.trunc(diffMs / YEAR);
}
}
// ---------------------------------------------------------------------------
// Internal: threshold-based label
// ---------------------------------------------------------------------------
/** Thresholds in ascending order. The last entry captures all remaining values. */
const STEPS: Array<{
maxMs: number;
singular: string;
plural: string;
divisor: number;
}> = [
{
maxMs: 45 * SECOND,
singular: "second",
plural: "seconds",
divisor: SECOND,
},
{
maxMs: 45 * MINUTE,
singular: "minute",
plural: "minutes",
divisor: MINUTE,
},
{ maxMs: 22 * HOUR, singular: "hour", plural: "hours", divisor: HOUR },
{ maxMs: 26 * DAY, singular: "day", plural: "days", divisor: DAY },
{ maxMs: 11 * MONTH, singular: "month", plural: "months", divisor: MONTH },
];
function buildRelativeLabel(diffMs: number, _precision?: DurationUnit): string {
const abs = Math.abs(diffMs);
const past = diffMs < 0;
if (abs < 45 * SECOND) {
return "just now";
}
for (const { maxMs, singular, plural, divisor } of STEPS) {
if (abs < maxMs) {
const count = Math.round(abs / divisor);
const unit = count === 1 ? singular : plural;
return past ? `${count} ${unit} ago` : `in ${count} ${unit}`;
}
}
// Anything beyond 11 months → years
const count = Math.round(abs / YEAR);
const unit = count === 1 ? "year" : "years";
return past ? `${count} ${unit} ago` : `in ${count} ${unit}`;
}
// ---------------------------------------------------------------------------
// Public: formatRelative
// ---------------------------------------------------------------------------
/**
* Format the difference between `date` and the current time (from `opts.clock`)
* as a human-readable relative string such as `"3 days ago"` or `"in 2 hours"`.
*/
export function formatRelative(
date: DateInput,
opts?: RelativeTimeOptions
): string {
const now = nowMs(opts);
const then = toDate(date).getTime();
return buildRelativeLabel(then - now, opts?.precision);
}
/**
* Convenience alias: format `date` as a past relative string.
*
* Equivalent to `formatRelative` when `date` is in the past.
*/
export function timeAgo(date: DateInput, opts?: RelativeTimeOptions): string {
return formatRelative(date, opts);
}
/**
* Convenience alias: format `date` as a future relative string.
*
* Equivalent to `formatRelative` when `date` is in the future.
*/
export function timeUntil(date: DateInput, opts?: RelativeTimeOptions): string {
return formatRelative(date, opts);
}

View File

@@ -0,0 +1,67 @@
import z from "zod";
/** Zod schema for `DateInput` — accepts Date, ISO string, or epoch millis. */
export const DateInputSchema = z.union([z.date(), z.string(), z.number()]);
/** Zod schema for `DurationUnit`. */
export const DurationUnitSchema = z.enum([
"years",
"months",
"weeks",
"days",
"hours",
"minutes",
"seconds",
"milliseconds",
]);
/** Zod schema for `Duration`. */
export const DurationSchema = z.object({
years: z.number().optional(),
months: z.number().optional(),
weeks: z.number().optional(),
days: z.number().optional(),
hours: z.number().optional(),
minutes: z.number().optional(),
seconds: z.number().optional(),
milliseconds: z.number().optional(),
});
/** Zod schema for `Weekday` (0–6). */
export const WeekdaySchema = z.union([
z.literal(0),
z.literal(1),
z.literal(2),
z.literal(3),
z.literal(4),
z.literal(5),
z.literal(6),
]);
/** Zod schema for `Frequency`. */
export const FrequencySchema = z.enum(["daily", "weekly", "monthly", "yearly"]);
/** Zod schema for `CalendarDay`. */
export const CalendarDaySchema = z.object({
date: z.date(),
dayOfWeek: WeekdaySchema,
isWeekend: z.boolean(),
isToday: z.boolean(),
});
/** Zod schema for `CalendarMonth`. */
export const CalendarMonthSchema = z.object({
year: z.number().int(),
month: z.number().int().min(1).max(12),
days: z.array(CalendarDaySchema),
});
/** Zod schema for `RecurrenceRule`. */
export const RecurrenceRuleSchema = z.object({
freq: FrequencySchema,
interval: z.number().int().positive().optional(),
count: z.number().int().positive().optional(),
until: z.date().optional(),
byDay: z.array(WeekdaySchema).optional(),
byMonthDay: z.array(z.number().int().min(1).max(31)).optional(),
});

View File

@@ -0,0 +1,69 @@
# datetime.types
## Purpose
Shared type definitions for the `@suaveplan/datetime` package. This module is the single source of truth for the shapes that flow through business-day arithmetic, calendar math, recurrence expansion, and relative-time formatting. Co-locating these definitions in one flat file keeps the feature modules focused on behaviour and keeps cross-module contracts obvious at a glance.
## Features
- Zero runtime cost — all exports are pure TypeScript types
- Branded `Timezone` string for IANA names that prevents accidental raw-string injection
- `DurationUnit` union aligned with the full `years | months | weeks | days | hours | minutes | seconds | milliseconds` vocabulary used across the library
- `BusinessDayOptions` and `RelativeTimeOptions` carry a pluggable `Clock` from `@suaveplan/types` so every consumer can be driven by a deterministic fake in tests
- `RecurrenceRule` subset aligned with the iCalendar/RRULE vocabulary (`freq`, `interval`, `count`, `until`, `byDay`, `byMonthDay`) without the full RFC 5545 complexity
## Usage: Basic Example
```ts
import type { Duration, Frequency, Weekday } from "@suaveplan/datetime/types/datetime.types";
const oneWeek: Duration = { days: 7 };
const monday: Weekday = 1;
const rule: Frequency = "weekly";
```
## Usage: Advanced Example
```ts
import type {
BusinessDayOptions,
RecurrenceRule,
Timezone,
} from "@suaveplan/datetime/types/datetime.types";
const businessOptions: BusinessDayOptions = {
holidays: [new Date("2026-01-01")],
weekendDays: [0, 6],
clock: () => Date.UTC(2026, 0, 1),
};
const weeklyStandup: RecurrenceRule = {
freq: "weekly",
interval: 1,
byDay: [1, 3, 5],
count: 52,
};
const nycTz = "America/New_York" as Timezone;
```
## API Reference
- `DateInput` — union of `Date | string | number`; accepted by parser helpers.
- `DurationUnit` — named calendar/time units.
- `Duration` — partial record of `DurationUnit → number`.
- `Weekday` — numeric index `0..6` matching `Date.prototype.getDay()`.
- `DayAbbreviation` — three-letter English abbreviations.
- `Frequency` — `"daily" | "weekly" | "monthly" | "yearly"` recurrence cadence.
- `Timezone` — branded IANA-name string.
- `CalendarDay` / `CalendarMonth` — grid shapes returned by `getCalendarMonth`.
- `BusinessDayOptions` — options bundle for business-day arithmetic with optional holidays, custom weekend days, clock injection, and `AbortSignal`.
- `RelativeTimeOptions` — locale, clock, and precision knobs for `formatRelativeTime`.
- `RecurrenceRule` — RRULE-like shape consumed by `expandRecurrence`.
- `RecurrenceOptions` — signal + clock bundle for the expansion loop.
## Implementation Notes
All interfaces deliberately avoid class-based modelling so they can round-trip through JSON and be used as wire-format types by downstream services. The `Timezone` brand is enforced only at compile time; runtime validation lives in `asTimezone()` in the calendar module, which checks against `Intl.supportedValuesOf('timeZone')`. Consumers should never cast a raw `string` to `Timezone` — always construct via the validator.
The `Clock` and `Rng` injections come from `@suaveplan/types` (the types-only foundation package) rather than being redefined here, which prevents structural drift between `datetime`, `timing`, `retry`, and every other package that takes a clock.

View File

@@ -0,0 +1,86 @@
import type { Clock } from "@suaveplan/types";
/** Any value that can be coerced into a `Date`. */
export type DateInput = Date | string | number;
/** Time unit names used throughout the library. */
export type DurationUnit =
| "years"
| "months"
| "weeks"
| "days"
| "hours"
| "minutes"
| "seconds"
| "milliseconds";
/** A bag of duration components; all fields optional, all non-negative by convention. */
export type Duration = Partial<Record<DurationUnit, number>>;
/** Day-of-week numeric index: 0 = Sunday … 6 = Saturday (matches `Date.prototype.getDay()`). */
export type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6;
/** Short day abbreviation. */
export type DayAbbreviation =
| "Sun"
| "Mon"
| "Tue"
| "Wed"
| "Thu"
| "Fri"
| "Sat";
/** Recurrence frequency. */
export type Frequency = "daily" | "weekly" | "monthly" | "yearly";
/**
* Branded string representing an IANA timezone name (e.g. `"America/New_York"`).
* Use `asTimezone()` from the calendar module to construct safely.
*/
export type Timezone = string & { readonly __brand: "Timezone" };
/** A single day entry inside a calendar grid. */
export interface CalendarDay {
date: Date;
dayOfWeek: Weekday;
isWeekend: boolean;
isToday: boolean;
}
/** A full calendar month grid. */
export interface CalendarMonth {
year: number;
month: number;
days: CalendarDay[];
}
/** Options shared by business-day functions. */
export interface BusinessDayOptions {
holidays?: Date[];
weekendDays?: Weekday[];
clock?: Clock;
signal?: AbortSignal;
}
/** Options for relative-time formatting functions. */
export interface RelativeTimeOptions {
locale?: string;
clock?: Clock;
precision?: DurationUnit;
}
/** An iCalendar-like recurrence rule. */
export interface RecurrenceRule {
freq: Frequency;
interval?: number;
count?: number;
until?: Date;
byDay?: Weekday[];
byMonthDay?: number[];
}
/** Options for recurrence expansion. */
export interface RecurrenceOptions {
signal?: AbortSignal;
clock?: Clock;
}

View File

@@ -0,0 +1,25 @@
export {
CalendarDaySchema,
CalendarMonthSchema,
DateInputSchema,
DurationSchema,
DurationUnitSchema,
FrequencySchema,
RecurrenceRuleSchema,
WeekdaySchema,
} from "./datetime.schemas";
export type {
BusinessDayOptions,
CalendarDay,
CalendarMonth,
DateInput,
DayAbbreviation,
Duration,
DurationUnit,
Frequency,
RecurrenceOptions,
RecurrenceRule,
RelativeTimeOptions,
Timezone,
Weekday,
} from "./datetime.types";