@northguild/gmt
Version:
Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.
342 lines (340 loc) • 10.9 kB
JavaScript
import { Temporal } from "./temporal.js";
// src/internal/recurrenceRuleText.ts
const partName = /^(?:FREQ|UNTIL|COUNT|INTERVAL|BYSECOND|BYMINUTE|BYHOUR|BYDAY|BYMONTHDAY|BYYEARDAY|BYWEEKNO|BYMONTH|BYSETPOS|WKST)$/i;
const frequencyText = /^(?:YEARLY|MONTHLY|WEEKLY|DAILY|HOURLY|MINUTELY|SECONDLY)$/i;
const weekdayText = /^(?:MO|TU|WE|TH|FR|SA|SU)$/i;
const untilText = /^(\d{4})(\d{2})(\d{2})(?:T(\d{2})(\d{2})(\d{2})(Z)?)?$/;
const dayEntryText = /^(?:([+-]?)(\d{1,2}))?(MO|TU|WE|TH|FR|SA|SU)$/i;
/** RFC 5545 §3.3.10 `weekday` ABNF, mapped to `IsoWeekday`. */
const weekdayNumbers = {
MO: 1,
TU: 2,
WE: 3,
TH: 4,
FR: 5,
SA: 6,
SU: 7
};
/** Digit-count grammars of the numeric parts (`1*2DIGIT`, `1*3DIGIT`, ...; `[+/-]` where signed). */
const listGrammar = {
BYSECOND: /^\d{1,2}$/,
BYMINUTE: /^\d{1,2}$/,
BYHOUR: /^\d{1,2}$/,
BYMONTHDAY: /^[+-]?\d{1,2}$/,
BYYEARDAY: /^[+-]?\d{1,3}$/,
BYWEEKNO: /^[+-]?\d{1,2}$/,
BYMONTH: /^\d{1,2}$/,
BYSETPOS: /^[+-]?\d{1,3}$/
};
const listMember = {
BYSECOND: "bySecond",
BYMINUTE: "byMinute",
BYHOUR: "byHour",
BYMONTHDAY: "byMonthDay",
BYYEARDAY: "byYearDay",
BYWEEKNO: "byWeekNo",
BYMONTH: "byMonth",
BYSETPOS: "bySetPosition"
};
/** RFC 5545 §3.3.10 value ranges. A signed range allows ±min..max and never 0. */
const listRanges = {
bySecond: [
0,
60,
false
],
byMinute: [
0,
59,
false
],
byHour: [
0,
23,
false
],
byMonthDay: [
1,
31,
true
],
byYearDay: [
1,
366,
true
],
byWeekNo: [
1,
53,
true
],
byMonth: [
1,
12,
false
],
bySetPosition: [
1,
366,
true
]
};
const listOrder = [
"bySecond",
"byMinute",
"byHour",
"byDay",
"byMonthDay",
"byYearDay",
"byWeekNo",
"byMonth",
"bySetPosition"
];
const frequencies = /* @__PURE__ */ new Set([
"yearly",
"monthly",
"weekly",
"daily",
"hourly",
"minutely",
"secondly"
]);
function isRecord(value) {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function signedInteger(token) {
return Number(token.startsWith("+") ? token.slice(1) : token);
}
function readList(name, value) {
const grammar = listGrammar[name];
const out = [];
for (const item of value.split(",")) {
if (!grammar.test(item)) return null;
out.push(signedInteger(item));
}
return out;
}
function readDayEntry(item) {
const match = dayEntryText.exec(item);
if (match === null) return null;
const day = weekdayNumbers[match[3].toUpperCase()];
if (match[2] === void 0) return { day };
return {
day,
nthOfPeriod: Number(match[2]) * (match[1] === "-" ? -1 : 1)
};
}
function readByDay(value) {
const out = [];
for (const item of value.split(",")) {
const entry = readDayEntry(item);
if (entry === null) return null;
out.push(entry);
}
return out;
}
/** Rebuild an `UNTIL` value as ISO and let Temporal read it whole; null when it is not real. */
function readUntil(value) {
const match = untilText.exec(value);
if (match === null) return null;
const [, year, month, day, hour, minute, second, zone] = match;
const date = `${year}-${month}-${day}`;
if (hour === void 0) return canonicalUntil(date);
if (second === "60") return null;
const iso = `${date}T${hour}:${minute}:${second}`;
return canonicalUntil(zone === void 0 ? iso : `${iso}Z`);
}
/**
* Temporal's canonical string for an ISO `UNTIL` form, or null when Temporal rejects it.
* Second 60 is refused by the caller first: Temporal would clamp it to 59.
*/
function canonicalUntil(iso) {
try {
return iso.endsWith("Z") ? Temporal.Instant.from(iso).toString() : iso.includes("T") ? Temporal.PlainDateTime.from(iso, { overflow: "reject" }).toString() : Temporal.PlainDate.from(iso, { overflow: "reject" }).toString();
} catch {
return null;
}
}
/** The one `Temporal` read of a canonical `until`: true when the string is a real, canonical form. */
function isCanonicalUntil(value) {
if (typeof value !== "string") return false;
if (!/^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}Z?)?$/.test(value)) return false;
return canonicalUntil(value) === value;
}
function readPositiveInteger(value) {
if (!/^\d+$/.test(value)) return null;
return Number(value);
}
/** Store `value` under `key` and report whether it read; an unread value is stored as absent. */
function keep(record, key, read) {
record[key] = read ?? void 0;
return read !== null;
}
function storeScalarPart(record, name, value) {
switch (name) {
case "FREQ": return keep(record, "frequency", frequencyText.test(value) ? value.toLowerCase() : null);
case "WKST": return keep(record, "firstDayOfWeek", weekdayText.test(value) ? weekdayNumbers[value.toUpperCase()] : null);
case "UNTIL": return keep(record, "until", readUntil(value));
case "COUNT": return keep(record, "count", readPositiveInteger(value));
default: return keep(record, "interval", readPositiveInteger(value));
}
}
/** Store one `NAME=VALUE` part in `record`; false when the value breaks the part's grammar. */
function storePart(record, name, value) {
if (name === "BYDAY") return keep(record, "byDay", readByDay(value));
const member = listMember[name];
if (member !== void 0) return keep(record, member, readList(name, value));
return storeScalarPart(record, name, value);
}
/**
* Read a RECUR value (the text after `RRULE:`) into a checked rule, or null when the text breaks
* the grammar or a §3.3.10 rule. Never reads a part twice, never accepts whitespace or an empty
* part.
*/
function readRecurrenceRule(text) {
if (typeof text !== "string") return null;
const record = {
interval: 1,
firstDayOfWeek: 1
};
const seen = /* @__PURE__ */ new Set();
for (const part of text.split(";")) {
const equals = part.indexOf("=");
if (equals < 0) return null;
const rawName = part.slice(0, equals);
if (!partName.test(rawName)) return null;
const name = rawName.toUpperCase();
if (seen.has(name)) return null;
seen.add(name);
if (!storePart(record, name, part.slice(equals + 1))) return null;
}
return checkRecurrenceRule(record);
}
function sortedUnique(values) {
return [...new Set(values.map((value) => value + 0))].sort((a, b) => a - b);
}
function checkedList(value, [min, max, signed]) {
if (!Array.isArray(value) || value.length === 0) return null;
for (const item of value) {
if (typeof item !== "number" || !Number.isInteger(item)) return null;
const magnitude = signed ? Math.abs(item) : item;
if (magnitude < min || magnitude > max) return null;
}
return sortedUnique(value);
}
function isWeekday(value) {
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 7;
}
function checkedDay(value) {
if (!isRecord(value) || !isWeekday(value["day"])) return null;
const nth = value["nthOfPeriod"];
if (nth === void 0) return { day: value["day"] };
if (typeof nth !== "number" || !Number.isInteger(nth) || nth === 0 || Math.abs(nth) > 53) return null;
return {
day: value["day"],
nthOfPeriod: nth
};
}
/** Ascending by weekday, then by ordinal, an absent ordinal first; duplicates dropped. */
function checkedDays(value) {
if (!Array.isArray(value) || value.length === 0) return null;
const days = [];
for (const item of value) {
const day = checkedDay(item);
if (day === null) return null;
days.push(day);
}
const order = (entry) => entry.day * 1e3 + (entry.nthOfPeriod === void 0 ? 0 : entry.nthOfPeriod + 100);
return [...new Map(days.map((entry) => [order(entry), entry])).entries()].sort(([a], [b]) => a - b).map(([, entry]) => entry);
}
function isPositiveSafeInteger(value) {
return typeof value === "number" && Number.isSafeInteger(value) && value >= 1;
}
/** The four rule-wide members, or null when any is missing or out of range. */
function checkedScalars(rule) {
const frequency = rule["frequency"];
const { interval, firstDayOfWeek } = rule;
if (typeof frequency !== "string" || !frequencies.has(frequency)) return null;
if (!isPositiveSafeInteger(interval) || !isWeekday(firstDayOfWeek)) return null;
return {
frequency,
interval,
firstDayOfWeek
};
}
/** `until` and `count`, at most one (§3.3.10: "UNTIL or COUNT ... MUST NOT occur in the same"). */
function checkedEnd(rule) {
const { until, count } = rule;
if (until !== void 0 && count !== void 0) return null;
if (until !== void 0) return isCanonicalUntil(until) ? { until } : null;
if (count !== void 0) return isPositiveSafeInteger(count) ? { count } : null;
return {};
}
/** The nine BYxxx members, checked and normalised; null when any is invalid. */
function checkedParts(rule) {
const out = {};
for (const member of listOrder) {
const value = rule[member];
if (value === void 0) continue;
const checked = member === "byDay" ? checkedDays(value) : checkedList(value, listRanges[member]);
if (checked === null) return null;
out[member] = checked;
}
return out;
}
/** BYDAY: a numeric value only with MONTHLY or YEARLY, and not with BYWEEKNO when YEARLY. */
function respectsByDay(rule) {
const { frequency, byDay, byWeekNo } = rule;
if (byDay?.some((entry) => entry.nthOfPeriod !== void 0) !== true) return true;
if (frequency !== "monthly" && frequency !== "yearly") return false;
return !(frequency === "yearly" && byWeekNo !== void 0);
}
/** The BYMONTHDAY, BYYEARDAY and BYWEEKNO "MUST NOT" sentences of §3.3.10. */
function respectsDayParts(rule) {
const { frequency, byMonthDay, byYearDay, byWeekNo } = rule;
if (byMonthDay !== void 0 && frequency === "weekly") return false;
if (byYearDay !== void 0 && [
"daily",
"weekly",
"monthly"
].includes(frequency)) return false;
return byWeekNo === void 0 || frequency === "yearly";
}
/** The §3.3.10 "MUST NOT" and "only" sentences that tie a BYxxx member to `FREQ`. */
function respectsFrequency(rule) {
if (!respectsByDay(rule) || !respectsDayParts(rule)) return false;
return rule.bySetPosition === void 0 || listOrder.some((member) => member !== "bySetPosition" && rule[member] !== void 0);
}
/**
* Check a rule against RFC 5545 §3.3.10 and return a fresh, frozen, normalised record (lists
* sorted ascending and deduplicated, `byDay` ordered by weekday then ordinal), or null. The input
* is never mutated. Never throws.
*/
function checkRecurrenceRule(rule) {
try {
if (!isRecord(rule)) return null;
const scalars = checkedScalars(rule);
const end = checkedEnd(rule);
const parts = checkedParts(rule);
if (scalars === null || end === null || parts === null) return null;
const checked = {
...scalars,
...end,
...parts
};
if (!respectsFrequency(checked)) return null;
return deepFreeze(checked);
} catch {
return null;
}
}
function deepFreeze(rule) {
for (const member of listOrder) {
const list = rule[member];
if (list === void 0) continue;
for (const entry of list) if (typeof entry === "object") Object.freeze(entry);
Object.freeze(list);
}
return Object.freeze(rule);
}
export { checkRecurrenceRule, readRecurrenceRule };