{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "weekly-hours",
  "title": "Weekly Hours",
  "description": "Opening or working hours per weekday, with split shifts, copy to other days and overlap checks.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "utils",
    "button",
    "@drift-ui/time-field",
    "@drift-ui/use-controllable-state",
    "@drift-ui/shape"
  ],
  "files": [
    {
      "path": "registry/default/ui/weekly-hours.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { CopyIcon, PlusIcon, XIcon } from \"lucide-react\"\n\nimport { useControllableState } from \"@/registry/default/hooks/use-controllable-state\"\nimport type { HourCycle } from \"@/registry/default/lib/time-segments\"\nimport { cn } from \"@/registry/default/lib/utils\"\nimport {\n  addRange,\n  copyDayToAvailableDays,\n  getDayRanges,\n  getNextRange,\n  getRangeError,\n  removeRange,\n  setDayAvailable,\n  updateRange,\n  WEEKDAY_NAMES,\n  WEEKDAYS,\n  type TimeRange,\n  type Weekday,\n  type WeeklyHoursRange,\n} from \"@/registry/default/lib/weekly-hours-utils\"\nimport { Button } from \"@/registry/default/ui/button\"\nimport { TimeField } from \"@/registry/default/ui/time-field\"\n\nconst EMPTY: WeeklyHoursRange[] = []\nconst NINE_TO_FIVE: TimeRange = { start: \"09:00\", end: \"17:00\" }\n\nexport type WeeklyHoursProps = Omit<\n  React.ComponentProps<\"div\">,\n  \"defaultValue\" | \"onChange\"\n> & {\n  value?: WeeklyHoursRange[]\n  defaultValue?: WeeklyHoursRange[]\n  onValueChange?: (value: WeeklyHoursRange[]) => void\n  weekdays?: Weekday[]\n  defaultRange?: TimeRange\n  hourCycle?: HourCycle\n  minuteStep?: number\n  disabled?: boolean\n  unavailableLabel?: string\n}\n\nfunction WeeklyHours({\n  value,\n  defaultValue = EMPTY,\n  onValueChange,\n  weekdays = WEEKDAYS,\n  defaultRange = NINE_TO_FIVE,\n  hourCycle = 24,\n  minuteStep = 15,\n  disabled = false,\n  unavailableLabel = \"Unavailable\",\n  className,\n  ...props\n}: WeeklyHoursProps) {\n  const { value: ranges = EMPTY, setValue: setRanges } = useControllableState({\n    value,\n    defaultValue,\n    onChange: onValueChange,\n  })\n  const id = React.useId()\n\n  return (\n    <div\n      role=\"group\"\n      data-slot=\"weekly-hours\"\n      className={cn(\"grid divide-y\", className)}\n      {...props}\n    >\n      {weekdays.map((day) => {\n        const dayName = WEEKDAY_NAMES[day]\n        const dayRanges = getDayRanges(ranges, day)\n        const isAvailable = dayRanges.length > 0\n        const canAdd = getNextRange(dayRanges, defaultRange) !== null\n        const canCopy =\n          isAvailable &&\n          weekdays.some(\n            (other) => other !== day && getDayRanges(ranges, other).length > 0\n          )\n        const checkboxId = `${id}-${day}`\n\n        return (\n          <div\n            key={day}\n            data-slot=\"weekly-hours-day\"\n            data-available={isAvailable || undefined}\n            className=\"flex flex-wrap items-start gap-x-4 gap-y-2 py-3\"\n          >\n            <label\n              htmlFor={checkboxId}\n              className=\"flex h-control w-28 shrink-0 items-center gap-2.5 text-sm font-medium\"\n            >\n              <input\n                id={checkboxId}\n                type=\"checkbox\"\n                checked={isAvailable}\n                disabled={disabled}\n                onChange={(event) =>\n                  setRanges(\n                    setDayAvailable(\n                      ranges,\n                      day,\n                      event.target.checked,\n                      defaultRange\n                    )\n                  )\n                }\n                className=\"size-4 accent-primary\"\n              />\n              {dayName}\n            </label>\n\n            <div className=\"grid min-w-0 flex-1 gap-2\">\n              {isAvailable ? (\n                dayRanges.map((range, index) => {\n                  const error = getRangeError(dayRanges, index)\n                  const errorId = `${checkboxId}-${index}-error`\n                  const label =\n                    dayRanges.length > 1\n                      ? `${dayName}, range ${index + 1}`\n                      : dayName\n                  return (\n                    <div\n                      key={index}\n                      data-slot=\"weekly-hours-range\"\n                      className=\"grid gap-1\"\n                    >\n                      <div className=\"flex items-center gap-2\">\n                        <TimeField\n                          aria-label={`${label} start`}\n                          aria-invalid={error ? true : undefined}\n                          aria-describedby={error ? errorId : undefined}\n                          value={range.start}\n                          onValueChange={(start) =>\n                            setRanges(\n                              updateRange(ranges, day, index, { start })\n                            )\n                          }\n                          hourCycle={hourCycle}\n                          minuteStep={minuteStep}\n                          disabled={disabled}\n                        />\n                        <span aria-hidden className=\"text-muted-foreground\">\n                          –\n                        </span>\n                        <TimeField\n                          aria-label={`${label} end`}\n                          aria-invalid={error ? true : undefined}\n                          aria-describedby={error ? errorId : undefined}\n                          value={range.end}\n                          onValueChange={(end) =>\n                            setRanges(updateRange(ranges, day, index, { end }))\n                          }\n                          hourCycle={hourCycle}\n                          minuteStep={minuteStep}\n                          disabled={disabled}\n                        />\n                        <Button\n                          type=\"button\"\n                          variant=\"ghost\"\n                          size=\"icon\"\n                          aria-label={`Remove ${label}`}\n                          disabled={disabled}\n                          onClick={() =>\n                            setRanges(removeRange(ranges, day, index))\n                          }\n                        >\n                          <XIcon />\n                        </Button>\n                      </div>\n                      {error && (\n                        <p id={errorId} className=\"text-xs text-destructive\">\n                          {error}\n                        </p>\n                      )}\n                    </div>\n                  )\n                })\n              ) : (\n                <p className=\"flex h-control items-center text-sm text-muted-foreground\">\n                  {unavailableLabel}\n                </p>\n              )}\n            </div>\n\n            <div className=\"flex shrink-0 items-center\">\n              <Button\n                type=\"button\"\n                variant=\"ghost\"\n                size=\"icon\"\n                aria-label={`Add hours on ${dayName}`}\n                title=\"Add hours\"\n                disabled={disabled || !canAdd}\n                onClick={() => setRanges(addRange(ranges, day, defaultRange))}\n              >\n                <PlusIcon />\n              </Button>\n              <Button\n                type=\"button\"\n                variant=\"ghost\"\n                size=\"icon\"\n                aria-label={`Copy ${dayName} hours to every available day`}\n                title=\"Copy to every available day\"\n                disabled={disabled || !canCopy}\n                onClick={() =>\n                  setRanges(copyDayToAvailableDays(ranges, day, weekdays))\n                }\n              >\n                <CopyIcon />\n              </Button>\n            </div>\n          </div>\n        )\n      })}\n    </div>\n  )\n}\n\nexport { WeeklyHours }\nexport type { TimeRange, Weekday, WeeklyHoursRange }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/default/lib/weekly-hours-utils.ts",
      "content": "import {\n  WEEKDAYS,\n  WEEKDAY_NAMES,\n  type Weekday,\n} from \"@/registry/default/lib/recurrence\"\n\nexport type { Weekday }\nexport { WEEKDAYS, WEEKDAY_NAMES }\n\nexport type WeeklyHoursRange = { day: Weekday; start: string; end: string }\n\nexport type TimeRange = { start: string; end: string }\n\nconst LAST_MINUTE = 23 * 60 + 59\n\nexport function toMinutes(time: string): number | null {\n  const match = /^(\\d{2}):(\\d{2})$/.exec(time)\n  if (!match || Number(match[2]) > 59) return null\n  const minutes = Number(match[1]) * 60 + Number(match[2])\n  return minutes > LAST_MINUTE ? null : minutes\n}\n\nexport function fromMinutes(minutes: number): string {\n  const clamped = Math.max(0, Math.min(LAST_MINUTE, minutes))\n  const hours = Math.floor(clamped / 60)\n  return `${String(hours).padStart(2, \"0\")}:${String(clamped % 60).padStart(2, \"0\")}`\n}\n\nexport function getDayRanges(\n  value: WeeklyHoursRange[],\n  day: Weekday\n): WeeklyHoursRange[] {\n  return value.filter((range) => range.day === day)\n}\n\nfunction replaceDay(\n  value: WeeklyHoursRange[],\n  day: Weekday,\n  ranges: TimeRange[]\n): WeeklyHoursRange[] {\n  return [\n    ...value.filter((range) => range.day !== day),\n    ...ranges.map(({ start, end }) => ({ day, start, end })),\n  ].sort((a, b) => WEEKDAYS.indexOf(a.day) - WEEKDAYS.indexOf(b.day))\n}\n\nexport function getNextRange(\n  dayRanges: TimeRange[],\n  defaultRange: TimeRange\n): TimeRange | null {\n  if (dayRanges.length === 0) return defaultRange\n  const ends = dayRanges.map((range) => toMinutes(range.end))\n  if (ends.some((end) => end === null)) return null\n  const latestEnd = Math.max(...(ends as number[]))\n  const start = latestEnd + 60\n  if (start >= LAST_MINUTE) return null\n  return { start: fromMinutes(start), end: fromMinutes(start + 60) }\n}\n\nexport function setDayAvailable(\n  value: WeeklyHoursRange[],\n  day: Weekday,\n  available: boolean,\n  defaultRange: TimeRange\n): WeeklyHoursRange[] {\n  return replaceDay(value, day, available ? [defaultRange] : [])\n}\n\nexport function addRange(\n  value: WeeklyHoursRange[],\n  day: Weekday,\n  defaultRange: TimeRange\n): WeeklyHoursRange[] {\n  const dayRanges = getDayRanges(value, day)\n  const next = getNextRange(dayRanges, defaultRange)\n  if (!next) return value\n  return replaceDay(value, day, [...dayRanges, next])\n}\n\nexport function updateRange(\n  value: WeeklyHoursRange[],\n  day: Weekday,\n  index: number,\n  patch: Partial<TimeRange>\n): WeeklyHoursRange[] {\n  const dayRanges = getDayRanges(value, day).map((range, i) =>\n    i === index ? { ...range, ...patch } : range\n  )\n  return replaceDay(value, day, dayRanges)\n}\n\nexport function removeRange(\n  value: WeeklyHoursRange[],\n  day: Weekday,\n  index: number\n): WeeklyHoursRange[] {\n  return replaceDay(\n    value,\n    day,\n    getDayRanges(value, day).filter((_, i) => i !== index)\n  )\n}\n\nexport function copyDayToAvailableDays(\n  value: WeeklyHoursRange[],\n  fromDay: Weekday,\n  days: Weekday[]\n): WeeklyHoursRange[] {\n  const source = getDayRanges(value, fromDay)\n  return days.reduce(\n    (next, day) =>\n      day === fromDay || getDayRanges(next, day).length === 0\n        ? next\n        : replaceDay(next, day, source),\n    value\n  )\n}\n\nexport function getRangeError(\n  dayRanges: TimeRange[],\n  index: number\n): string | null {\n  const range = dayRanges[index]\n  const start = toMinutes(range.start)\n  const end = toMinutes(range.end)\n  if (start === null || end === null) return \"Enter a start and end time\"\n  if (end <= start) return \"End time must be after the start time\"\n  const overlaps = dayRanges.some((other, i) => {\n    if (i === index) return false\n    const otherStart = toMinutes(other.start)\n    const otherEnd = toMinutes(other.end)\n    if (otherStart === null || otherEnd === null) return false\n    return start < otherEnd && otherStart < end\n  })\n  return overlaps ? \"Overlaps another time range\" : null\n}\n",
      "type": "registry:lib"
    },
    {
      "path": "registry/default/lib/recurrence.ts",
      "content": "export type Frequency = \"DAILY\" | \"WEEKLY\" | \"MONTHLY\" | \"YEARLY\"\n\nexport type Weekday = \"MO\" | \"TU\" | \"WE\" | \"TH\" | \"FR\" | \"SA\" | \"SU\"\n\nexport type WeekdayRule = { weekday: Weekday; ordinal?: number }\n\nexport type Recurrence = {\n  frequency: Frequency\n  interval: number\n  byDay: WeekdayRule[]\n  byMonthDay: number[]\n  byMonth?: number[]\n  bySetPos?: number[]\n  count?: number\n  until?: Date\n  exdates?: Date[]\n  tzid?: string\n  unknownParts?: Record<string, string>\n}\n\nexport const FREQUENCIES: Frequency[] = [\"DAILY\", \"WEEKLY\", \"MONTHLY\", \"YEARLY\"]\n\nexport const WEEKDAYS: Weekday[] = [\"MO\", \"TU\", \"WE\", \"TH\", \"FR\", \"SA\", \"SU\"]\n\nexport const WEEKDAY_NAMES: Record<Weekday, string> = {\n  MO: \"Monday\",\n  TU: \"Tuesday\",\n  WE: \"Wednesday\",\n  TH: \"Thursday\",\n  FR: \"Friday\",\n  SA: \"Saturday\",\n  SU: \"Sunday\",\n}\n\nexport const MONTH_NAMES: Record<number, string> = {\n  1: \"January\",\n  2: \"February\",\n  3: \"March\",\n  4: \"April\",\n  5: \"May\",\n  6: \"June\",\n  7: \"July\",\n  8: \"August\",\n  9: \"September\",\n  10: \"October\",\n  11: \"November\",\n  12: \"December\",\n}\n\nconst UNITS: Record<Frequency, string> = {\n  DAILY: \"day\",\n  WEEKLY: \"week\",\n  MONTHLY: \"month\",\n  YEARLY: \"year\",\n}\n\nconst ADVERBS: Record<Frequency, string> = {\n  DAILY: \"Daily\",\n  WEEKLY: \"Weekly\",\n  MONTHLY: \"Monthly\",\n  YEARLY: \"Yearly\",\n}\n\nconst ORDINALS: Record<number, string> = {\n  1: \"first\",\n  2: \"second\",\n  3: \"third\",\n  4: \"fourth\",\n  5: \"fifth\",\n  [-1]: \"last\",\n  [-2]: \"second to last\",\n}\n\nconst BY_DAY = /^([+-]?\\d{1,2})?(MO|TU|WE|TH|FR|SA|SU)$/\nconst UNTIL = /^(\\d{4})(\\d{2})(\\d{2})(?:T(\\d{2})(\\d{2})(\\d{2})(Z)?)?$/\nconst DAY_MS = 86_400_000\nconst SEARCH_LIMIT_DAYS = 366 * 100\nconst SUMMARY_DATE = new Intl.DateTimeFormat(\"en-US\", { dateStyle: \"medium\" })\n\nconst KNOWN_KEYS = new Set([\n  \"FREQ\",\n  \"INTERVAL\",\n  \"BYDAY\",\n  \"BYMONTHDAY\",\n  \"BYMONTH\",\n  \"BYSETPOS\",\n  \"COUNT\",\n  \"UNTIL\",\n  \"EXDATE\",\n  \"TZID\",\n])\n\nfunction positiveInteger(text: string | undefined) {\n  const parsed = Number(text)\n  return Number.isInteger(parsed) && parsed > 0 ? parsed : undefined\n}\n\nfunction parseByDay(text = \"\"): WeekdayRule[] {\n  return text.split(\",\").flatMap((part) => {\n    const match = BY_DAY.exec(part.trim().toUpperCase())\n    if (!match) return []\n    const [, ordinal, weekday] = match\n    return [\n      ordinal\n        ? { weekday: weekday as Weekday, ordinal: Number(ordinal) }\n        : { weekday: weekday as Weekday },\n    ]\n  })\n}\n\nfunction getZonedDateTimeParts(date: Date, timeZone?: string) {\n  if (!timeZone) {\n    return {\n      year: date.getFullYear(),\n      month: date.getMonth(),\n      day: date.getDate(),\n      hour: date.getHours(),\n      minute: date.getMinutes(),\n      second: date.getSeconds(),\n    }\n  }\n  const formatter = new Intl.DateTimeFormat(\"en-US\", {\n    timeZone,\n    year: \"numeric\",\n    month: \"numeric\",\n    day: \"numeric\",\n    hour: \"numeric\",\n    minute: \"numeric\",\n    second: \"numeric\",\n    hour12: false,\n  })\n  const parts = formatter.formatToParts(date)\n  const map: Record<string, number> = {}\n  for (const part of parts) {\n    if (part.type !== \"literal\") {\n      map[part.type] = Number(part.value)\n    }\n  }\n  return {\n    year: map.year ?? date.getFullYear(),\n    month: (map.month ?? 1) - 1,\n    day: map.day ?? 1,\n    hour: (map.hour ?? 0) % 24,\n    minute: map.minute ?? 0,\n    second: map.second ?? 0,\n  }\n}\n\nfunction makeZonedDate(\n  year: number,\n  month: number,\n  day: number,\n  hour: number,\n  minute: number,\n  second: number,\n  timeZone?: string\n): Date | null {\n  if (!timeZone) {\n    const d = new Date(year, month, day, hour, minute, second)\n    if (d.getHours() !== hour || d.getMinutes() !== minute) return null\n    return d\n  }\n\n  const utcGuess = Date.UTC(year, month, day, hour, minute, second)\n  const formatter = new Intl.DateTimeFormat(\"en-US\", {\n    timeZone,\n    year: \"numeric\",\n    month: \"numeric\",\n    day: \"numeric\",\n    hour: \"numeric\",\n    minute: \"numeric\",\n    second: \"numeric\",\n    hour12: false,\n  })\n\n  function getParts(ts: number) {\n    const p = formatter.formatToParts(new Date(ts))\n    const m: Record<string, number> = {}\n    for (const part of p) {\n      if (part.type !== \"literal\") m[part.type] = Number(part.value)\n    }\n    return {\n      year: m.year,\n      month: (m.month ?? 1) - 1,\n      day: m.day,\n      hour: (m.hour ?? 0) % 24,\n      minute: m.minute ?? 0,\n      second: m.second ?? 0,\n    }\n  }\n\n  let cur = getParts(utcGuess)\n  let curUtc = Date.UTC(\n    cur.year,\n    cur.month,\n    cur.day,\n    cur.hour,\n    cur.minute,\n    cur.second\n  )\n  let offset = curUtc - utcGuess\n  const targetTs = utcGuess - offset\n\n  cur = getParts(targetTs)\n  if (\n    cur.hour !== hour ||\n    cur.minute !== minute ||\n    cur.day !== day ||\n    cur.month !== month ||\n    cur.year !== year\n  ) {\n    curUtc = Date.UTC(\n      cur.year,\n      cur.month,\n      cur.day,\n      cur.hour,\n      cur.minute,\n      cur.second\n    )\n    offset = curUtc - targetTs\n    const refinedTs = utcGuess - offset\n    const refinedParts = getParts(refinedTs)\n    if (\n      refinedParts.hour !== hour ||\n      refinedParts.minute !== minute ||\n      refinedParts.day !== day\n    ) {\n      return null\n    }\n    return new Date(refinedTs)\n  }\n  return new Date(targetTs)\n}\n\ntype DateWithPrecision = Date & {\n  isDateOnly?: boolean\n  dateOnlyYMD?: string\n}\n\nfunction markDateOnly(\n  date: Date,\n  value: boolean,\n  ymd?: string\n): DateWithPrecision {\n  const tagged = date as DateWithPrecision\n  tagged.isDateOnly = value\n  if (ymd !== undefined) {\n    tagged.dateOnlyYMD = ymd\n  }\n  return tagged\n}\n\nfunction isDateOnly(date: Date): boolean {\n  if (\n    \"isDateOnly\" in date &&\n    typeof (date as DateWithPrecision).isDateOnly === \"boolean\"\n  ) {\n    return Boolean((date as DateWithPrecision).isDateOnly)\n  }\n  return (\n    date.getHours() === 0 &&\n    date.getMinutes() === 0 &&\n    date.getSeconds() === 0 &&\n    date.getMilliseconds() === 0\n  )\n}\n\nfunction isValidDate(year: number, month: number, day: number): boolean {\n  if (month < 0 || month > 11 || day < 1 || day > 31) return false\n  const check = new Date(Date.UTC(year, month, day))\n  return (\n    check.getUTCFullYear() === year &&\n    check.getUTCMonth() === month &&\n    check.getUTCDate() === day\n  )\n}\n\nfunction parseIcalDate(\n  text = \"\",\n  tzid?: string\n): DateWithPrecision | undefined {\n  const trimmed = text.trim()\n  const match = UNTIL.exec(trimmed)\n  if (!match) {\n    const parsed = new Date(trimmed)\n    if (Number.isNaN(parsed.getTime())) return undefined\n    if (!trimmed.includes(\"T\") && !/\\d{1,2}:\\d{2}/.test(trimmed)) {\n      const ymdMatch = /^(\\d{4})[-/]?(\\d{2})[-/]?(\\d{2})/.exec(trimmed)\n      if (ymdMatch) {\n        const y = Number(ymdMatch[1])\n        const m = Number(ymdMatch[2]) - 1\n        const d = Number(ymdMatch[3])\n        if (!isValidDate(y, m, d)) return undefined\n        markDateOnly(parsed, true, `${ymdMatch[1]}${ymdMatch[2]}${ymdMatch[3]}`)\n      } else {\n        markDateOnly(parsed, true)\n      }\n    }\n    return parsed as DateWithPrecision\n  }\n  const [, year, month, day, hours, minutes, seconds, utc] = match\n  const y = Number(year)\n  const m = Number(month) - 1\n  const d = Number(day)\n\n  if (!isValidDate(y, m, d)) return undefined\n\n  if (hours === undefined) {\n    const date =\n      makeZonedDate(y, m, d, 0, 0, 0, tzid) ?? new Date(y, m, d, 0, 0, 0)\n    return markDateOnly(date, true, `${year}${month}${day}`)\n  }\n\n  const h = Number(hours)\n  const min = Number(minutes)\n  const sec = Number(seconds)\n  if (h < 0 || h > 23 || min < 0 || min > 59 || sec < 0 || sec > 60) {\n    return undefined\n  }\n\n  if (utc) {\n    const date = new Date(Date.UTC(y, m, d, h, min, sec))\n    return markDateOnly(date, false)\n  }\n\n  const date =\n    makeZonedDate(y, m, d, h, min, sec, tzid) ?? new Date(y, m, d, h, min, sec)\n  return markDateOnly(date, false)\n}\n\nfunction parseUntil(text = \"\", tzid?: string): DateWithPrecision | undefined {\n  const trimmed = text.trim()\n  const match = UNTIL.exec(trimmed)\n  if (!match) return parseIcalDate(trimmed, tzid)\n\n  const [, year, month, day, hours, minutes, seconds, utc] = match\n  const y = Number(year)\n  const m = Number(month) - 1\n  const d = Number(day)\n\n  if (!isValidDate(y, m, d)) return undefined\n\n  if (hours === undefined) {\n    const date =\n      makeZonedDate(y, m, d, 23, 59, 59, tzid) ?? new Date(y, m, d, 23, 59, 59)\n    return markDateOnly(date, true, `${year}${month}${day}`)\n  }\n\n  const h = Number(hours)\n  const min = Number(minutes)\n  const sec = Number(seconds)\n  if (h < 0 || h > 23 || min < 0 || min > 59 || sec < 0 || sec > 60) {\n    return undefined\n  }\n\n  const date = utc\n    ? new Date(Date.UTC(y, m, d, h, min, sec))\n    : (makeZonedDate(y, m, d, h, min, sec, tzid) ??\n      new Date(y, m, d, h, min, sec))\n  return markDateOnly(date, false)\n}\n\nfunction formatIcalDate(date: Date, tzid?: string) {\n  if (isDateOnly(date)) {\n    const ymd = (date as DateWithPrecision).dateOnlyYMD\n    if (ymd) {\n      return ymd\n    }\n    if (tzid) {\n      try {\n        const parts = new Intl.DateTimeFormat(\"en-US\", {\n          timeZone: tzid,\n          year: \"numeric\",\n          month: \"2-digit\",\n          day: \"2-digit\",\n        }).formatToParts(date)\n        const y = parts.find((p) => p.type === \"year\")?.value\n        const m = parts.find((p) => p.type === \"month\")?.value\n        const d = parts.find((p) => p.type === \"day\")?.value\n        if (y && m && d) return `${y}${m}${d}`\n      } catch {\n        // Fall back to host-local fields if tzid is invalid\n      }\n    }\n    const y = date.getFullYear()\n    const m = String(date.getMonth() + 1).padStart(2, \"0\")\n    const d = String(date.getDate()).padStart(2, \"0\")\n    return `${y}${m}${d}`\n  }\n  return date\n    .toISOString()\n    .replace(/[-:]/g, \"\")\n    .replace(/\\.\\d{3}/, \"\")\n}\n\nexport function parseRRule(rule: string): Recurrence {\n  const lines = rule\n    .split(/\\r?\\n/)\n    .map((line) => line.trim())\n    .filter(Boolean)\n\n  let rruleLine = \"\"\n  const exdates: Date[] = []\n  let tzid: string | undefined\n\n  for (const line of lines) {\n    if (/^RRULE:/i.test(line)) {\n      rruleLine = line.replace(/^RRULE:/i, \"\")\n    } else if (/^EXDATE/i.test(line)) {\n      const colonIdx = line.indexOf(\":\")\n      if (colonIdx !== -1) {\n        const header = line.slice(0, colonIdx)\n        const dateStr = line.slice(colonIdx + 1)\n        const tzMatch = /TZID=([^;:]+)/i.exec(header)\n        const lineTzid = tzMatch ? tzMatch[1] : undefined\n        if (lineTzid && !tzid) {\n          tzid = lineTzid\n        }\n        for (const item of dateStr.split(\",\")) {\n          const d = parseIcalDate(item, lineTzid ?? tzid)\n          if (d) exdates.push(d)\n        }\n      }\n    } else if (/^DTSTART/i.test(line)) {\n      const tzMatch = /TZID=([^;:]+)/i.exec(line)\n      if (tzMatch && !tzid) {\n        tzid = tzMatch[1]\n      }\n    } else if (!rruleLine) {\n      if (/^RRULE:/i.test(line)) {\n        rruleLine = line.replace(/^RRULE:/i, \"\")\n      } else {\n        rruleLine = line\n      }\n    }\n  }\n\n  if (!rruleLine) {\n    rruleLine = rule.trim()\n    if (/^RRULE:/i.test(rruleLine)) {\n      rruleLine = rruleLine.replace(/^RRULE:/i, \"\")\n    }\n  }\n\n  const parts = new Map<string, string>()\n  for (const part of rruleLine.split(\";\")) {\n    const eqIdx = part.indexOf(\"=\")\n    if (eqIdx === -1) continue\n    const key = part.slice(0, eqIdx).trim().toUpperCase()\n    const value = part.slice(eqIdx + 1).trim()\n    if (key) parts.set(key, value)\n  }\n\n  if (parts.has(\"TZID\") && !tzid) {\n    tzid = parts.get(\"TZID\")\n  }\n\n  if (parts.has(\"EXDATE\")) {\n    const val = parts.get(\"EXDATE\") ?? \"\"\n    for (const item of val.split(\",\")) {\n      const d = parseIcalDate(item, tzid)\n      if (d) exdates.push(d)\n    }\n  }\n\n  const unknownParts: Record<string, string> = {}\n  for (const [key, value] of parts.entries()) {\n    if (!KNOWN_KEYS.has(key)) {\n      unknownParts[key] = value\n    }\n  }\n\n  const frequency = parts.get(\"FREQ\")?.toUpperCase() as Frequency\n  const byMonthDay = (parts.get(\"BYMONTHDAY\") ?? \"\")\n    .split(\",\")\n    .map(Number)\n    .filter((day) => Number.isInteger(day) && day !== 0 && Math.abs(day) <= 31)\n\n  const byMonth = (parts.get(\"BYMONTH\") ?? \"\")\n    .split(\",\")\n    .map(Number)\n    .filter((m) => Number.isInteger(m) && m >= 1 && m <= 12)\n\n  const bySetPos = (parts.get(\"BYSETPOS\") ?? \"\")\n    .split(\",\")\n    .map(Number)\n    .filter((pos) => Number.isInteger(pos) && pos !== 0 && Math.abs(pos) <= 366)\n\n  const recurrence: Recurrence = {\n    frequency: FREQUENCIES.includes(frequency) ? frequency : \"WEEKLY\",\n    interval: positiveInteger(parts.get(\"INTERVAL\")) ?? 1,\n    byDay: parseByDay(parts.get(\"BYDAY\")),\n    byMonthDay,\n    count: positiveInteger(parts.get(\"COUNT\")),\n    until: parseUntil(parts.get(\"UNTIL\"), tzid),\n  }\n\n  if (byMonth.length > 0) recurrence.byMonth = byMonth\n  if (bySetPos.length > 0) recurrence.bySetPos = bySetPos\n  if (exdates.length > 0) recurrence.exdates = exdates\n  if (tzid) recurrence.tzid = tzid\n  if (Object.keys(unknownParts).length > 0)\n    recurrence.unknownParts = unknownParts\n\n  return recurrence\n}\n\nexport function formatRRule(\n  recurrence: Recurrence,\n  options?: { prefix?: boolean; multiline?: boolean }\n): string {\n  const {\n    frequency,\n    interval,\n    byDay,\n    byMonthDay,\n    byMonth,\n    bySetPos,\n    count,\n    until,\n    unknownParts,\n    exdates,\n  } = recurrence\n\n  const parts = [`FREQ=${frequency}`]\n  if (interval > 1) parts.push(`INTERVAL=${interval}`)\n  if (byMonth && byMonth.length > 0) parts.push(`BYMONTH=${byMonth.join(\",\")}`)\n  if (byDay.length > 0) {\n    parts.push(\n      `BYDAY=${byDay.map((rule) => `${rule.ordinal ?? \"\"}${rule.weekday}`).join(\",\")}`\n    )\n  }\n  if (byMonthDay.length > 0) parts.push(`BYMONTHDAY=${byMonthDay.join(\",\")}`)\n  if (bySetPos && bySetPos.length > 0)\n    parts.push(`BYSETPOS=${bySetPos.join(\",\")}`)\n  if (count) parts.push(`COUNT=${count}`)\n  else if (until) {\n    parts.push(`UNTIL=${formatIcalDate(until, recurrence.tzid)}`)\n  }\n\n  if (unknownParts) {\n    for (const [key, value] of Object.entries(unknownParts)) {\n      if (value !== undefined && value !== \"\") {\n        parts.push(`${key}=${value}`)\n      }\n    }\n  }\n\n  if (options?.multiline) {\n    const rruleBody = parts.join(\";\")\n    const firstLine = options?.prefix ? `RRULE:${rruleBody}` : rruleBody\n    const lines = [firstLine]\n    if (exdates && exdates.length > 0) {\n      lines.push(\n        `EXDATE:${exdates.map((d) => formatIcalDate(d, recurrence.tzid)).join(\",\")}`\n      )\n    }\n    return lines.join(\"\\n\")\n  }\n\n  if (exdates && exdates.length > 0) {\n    parts.push(\n      `EXDATE=${exdates.map((d) => formatIcalDate(d, recurrence.tzid)).join(\",\")}`\n    )\n  }\n\n  const finalBody = parts.join(\";\")\n  return options?.prefix ? `RRULE:${finalBody}` : finalBody\n}\n\nexport function weekdayOf(date: Date): Weekday {\n  return WEEKDAYS[(date.getDay() + 6) % 7]\n}\n\nexport function ordinalWeekOf(date: Date) {\n  return Math.ceil(date.getDate() / 7)\n}\n\nexport function isLastWeekOf(date: Date) {\n  return date.getDate() + 7 > daysInMonth(date)\n}\n\nfunction daysInMonth(date: Date) {\n  return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate()\n}\n\nfunction dayNumber(date: Date) {\n  return Math.round(\n    Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / DAY_MS\n  )\n}\n\nfunction weekdaysOf(recurrence: Recurrence, start: Date) {\n  return recurrence.byDay.length > 0\n    ? recurrence.byDay.map((rule) => rule.weekday)\n    : [weekdayOf(start)]\n}\n\nfunction resolveSetPos<T>(items: T[], setPos: number[]): T[] {\n  const result: T[] = []\n  for (const pos of setPos) {\n    if (pos > 0 && pos <= items.length) {\n      result.push(items[pos - 1])\n    } else if (pos < 0 && Math.abs(pos) <= items.length) {\n      result.push(items[items.length + pos])\n    }\n  }\n  return result\n}\n\nfunction weekdayOrdinalInYear(date: Date): {\n  fromStart: number\n  fromEnd: number\n} {\n  const year = date.getFullYear()\n  const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0\n  const totalDays = isLeap ? 366 : 365\n\n  const jan1 = new Date(year, 0, 1)\n  const jan1Day = (jan1.getDay() + 6) % 7\n  const targetDay = (date.getDay() + 6) % 7\n  const daysToFirst = (targetDay - jan1Day + 7) % 7\n\n  const diffTime =\n    Date.UTC(year, date.getMonth(), date.getDate()) - Date.UTC(year, 0, 1)\n  const dayOfYear = Math.round(diffTime / DAY_MS)\n  const fromStart = Math.floor((dayOfYear - daysToFirst) / 7) + 1\n\n  const dec31 = new Date(year, 11, 31)\n  const dec31Day = (dec31.getDay() + 6) % 7\n  const daysFromLast = (dec31Day - targetDay + 7) % 7\n  const lastDayOfYear = totalDays - 1 - daysFromLast\n  const fromEnd = -Math.floor((lastDayOfYear - dayOfYear) / 7) - 1\n\n  return { fromStart, fromEnd }\n}\n\nfunction matchesDayRules(\n  recurrence: Recurrence,\n  date: Date,\n  period: \"month\" | \"year\" = \"month\"\n) {\n  const lastDay = daysInMonth(date)\n  let dayMatches = true\n\n  if (recurrence.byDay.length > 0) {\n    if (\n      period === \"year\" &&\n      (!recurrence.byMonth || recurrence.byMonth.length === 0)\n    ) {\n      const { fromStart, fromEnd } = weekdayOrdinalInYear(date)\n      dayMatches = recurrence.byDay.some(\n        (rule) =>\n          rule.weekday === weekdayOf(date) &&\n          (rule.ordinal === undefined ||\n            rule.ordinal === fromStart ||\n            rule.ordinal === fromEnd)\n      )\n    } else {\n      const fromEnd = -Math.ceil((lastDay - date.getDate() + 1) / 7)\n      dayMatches = recurrence.byDay.some(\n        (rule) =>\n          rule.weekday === weekdayOf(date) &&\n          (rule.ordinal === undefined ||\n            rule.ordinal === ordinalWeekOf(date) ||\n            rule.ordinal === fromEnd)\n      )\n    }\n  }\n\n  let monthDayMatches = true\n  if (recurrence.byMonthDay.length > 0) {\n    monthDayMatches = recurrence.byMonthDay.some(\n      (day) => date.getDate() === (day > 0 ? day : lastDay + day + 1)\n    )\n  }\n\n  return dayMatches && monthDayMatches\n}\n\nfunction matchesSetPos(\n  recurrence: Recurrence,\n  date: Date,\n  period: \"month\" | \"year\"\n): boolean {\n  if (!recurrence.bySetPos || recurrence.bySetPos.length === 0) return true\n\n  if (period === \"month\") {\n    const totalDays = daysInMonth(date)\n    const candidates: number[] = []\n    for (let day = 1; day <= totalDays; day++) {\n      const d = new Date(date.getFullYear(), date.getMonth(), day)\n      if (matchesDayRules(recurrence, d, \"month\")) {\n        candidates.push(day)\n      }\n    }\n    const selectedDays = resolveSetPos(candidates, recurrence.bySetPos)\n    return selectedDays.includes(date.getDate())\n  }\n\n  const year = date.getFullYear()\n  const isLeap = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0\n  const totalYearDays = isLeap ? 366 : 365\n  const cur = new Date(year, 0, 1)\n  const matchingDates: number[] = []\n\n  for (let i = 0; i < totalYearDays; i++) {\n    const month = cur.getMonth() + 1\n    if (\n      (!recurrence.byMonth || recurrence.byMonth.includes(month)) &&\n      matchesDayRules(\n        recurrence,\n        cur,\n        recurrence.byMonth && recurrence.byMonth.length > 0 ? \"month\" : \"year\"\n      )\n    ) {\n      matchingDates.push(cur.getTime())\n    }\n    cur.setDate(cur.getDate() + 1)\n  }\n\n  const selectedTimestamps = resolveSetPos(matchingDates, recurrence.bySetPos)\n  const target = new Date(\n    date.getFullYear(),\n    date.getMonth(),\n    date.getDate()\n  ).getTime()\n  return selectedTimestamps.includes(target)\n}\n\nfunction matchesDayOfMonth(recurrence: Recurrence, start: Date, date: Date) {\n  if (recurrence.bySetPos && recurrence.bySetPos.length > 0) {\n    return matchesSetPos(recurrence, date, \"month\")\n  }\n\n  if (recurrence.byDay.length > 0 || recurrence.byMonthDay.length > 0) {\n    return matchesDayRules(recurrence, date, \"month\")\n  }\n\n  return date.getDate() === start.getDate()\n}\n\nfunction matches(recurrence: Recurrence, start: Date, date: Date) {\n  const { frequency, interval } = recurrence\n  const days = dayNumber(date) - dayNumber(start)\n  const months =\n    (date.getFullYear() - start.getFullYear()) * 12 +\n    date.getMonth() -\n    start.getMonth()\n\n  if (recurrence.byMonth && recurrence.byMonth.length > 0) {\n    if (!recurrence.byMonth.includes(date.getMonth() + 1)) {\n      return false\n    }\n  }\n\n  switch (frequency) {\n    case \"DAILY\":\n      return days % interval === 0\n    case \"WEEKLY\": {\n      const weeks = Math.floor((days + ((start.getDay() + 6) % 7)) / 7)\n      return (\n        weeks % interval === 0 &&\n        weekdaysOf(recurrence, start).includes(weekdayOf(date))\n      )\n    }\n    case \"MONTHLY\":\n      return (\n        months % interval === 0 && matchesDayOfMonth(recurrence, start, date)\n      )\n    case \"YEARLY\": {\n      const years = date.getFullYear() - start.getFullYear()\n      if (years % interval !== 0) return false\n\n      if (\n        !recurrence.byMonth &&\n        recurrence.byDay.length === 0 &&\n        recurrence.byMonthDay.length === 0 &&\n        date.getMonth() !== start.getMonth()\n      ) {\n        return false\n      }\n\n      if (recurrence.bySetPos && recurrence.bySetPos.length > 0) {\n        return matchesSetPos(recurrence, date, \"year\")\n      }\n\n      if (recurrence.byDay.length > 0 || recurrence.byMonthDay.length > 0) {\n        return matchesDayRules(\n          recurrence,\n          date,\n          recurrence.byMonth && recurrence.byMonth.length > 0 ? \"month\" : \"year\"\n        )\n      }\n\n      return date.getDate() === start.getDate()\n    }\n  }\n}\n\nfunction isSameDayOrTime(\n  exdate: Date,\n  occurrence: Date,\n  timeZone?: string\n): boolean {\n  if (exdate.getTime() === occurrence.getTime()) return true\n\n  if (isDateOnly(exdate)) {\n    const occParts = getZonedDateTimeParts(occurrence, timeZone)\n    const exParts = getZonedDateTimeParts(exdate, timeZone)\n    return (\n      occParts.year === exParts.year &&\n      occParts.month === exParts.month &&\n      occParts.day === exParts.day\n    )\n  }\n\n  return false\n}\n\nexport function occurrences(\n  recurrence: Recurrence,\n  start: Date,\n  limit: number,\n  options?: { exdates?: (Date | string)[]; tzid?: string }\n): Date[] {\n  if (limit <= 0) return []\n  const found: Date[] = []\n  const timeZone = options?.tzid ?? recurrence.tzid\n  const startParts = getZonedDateTimeParts(start, timeZone)\n\n  const parsedOptionExdates = (options?.exdates ?? [])\n    .map((item) =>\n      item instanceof Date ? item : parseIcalDate(item, timeZone)\n    )\n    .filter(Boolean) as Date[]\n\n  const allExdates = [...(recurrence.exdates ?? []), ...parsedOptionExdates]\n\n  let generatedCount = 0\n\n  for (let dayOffset = 0; dayOffset < SEARCH_LIMIT_DAYS; dayOffset++) {\n    const refDate = new Date(\n      Date.UTC(startParts.year, startParts.month, startParts.day + dayOffset)\n    )\n    const curYear = refDate.getUTCFullYear()\n    const curMonth = refDate.getUTCMonth()\n    const curDay = refDate.getUTCDate()\n\n    const anchorDate = new Date(\n      startParts.year,\n      startParts.month,\n      startParts.day\n    )\n    const testDate = new Date(curYear, curMonth, curDay)\n\n    if (matches(recurrence, anchorDate, testDate)) {\n      const occurrence = makeZonedDate(\n        curYear,\n        curMonth,\n        curDay,\n        startParts.hour,\n        startParts.minute,\n        startParts.second,\n        timeZone\n      )\n\n      if (!occurrence) {\n        continue\n      }\n\n      if (recurrence.until && occurrence > recurrence.until) {\n        break\n      }\n\n      generatedCount++\n\n      const isExcluded = allExdates.some((exdate) =>\n        isSameDayOrTime(exdate, occurrence, timeZone)\n      )\n\n      if (!isExcluded) {\n        found.push(occurrence)\n      }\n\n      if (found.length >= limit) {\n        break\n      }\n\n      if (recurrence.count && generatedCount >= recurrence.count) {\n        break\n      }\n    }\n  }\n\n  return found\n}\n\nfunction joinWords(words: string[]) {\n  if (words.length < 2) return words.join(\"\")\n  return `${words.slice(0, -1).join(\", \")} and ${words.at(-1)}`\n}\n\nfunction ordinalWord(ordinal: number) {\n  return ORDINALS[ordinal] ?? String(ordinal)\n}\n\nfunction isWorkweekDays(byDay: WeekdayRule[]) {\n  return (\n    byDay.length === 5 &&\n    WEEKDAYS.slice(0, 5).every((w) => byDay.some((r) => r.weekday === w))\n  )\n}\n\nfunction isWeekendDays(byDay: WeekdayRule[]) {\n  return (\n    byDay.length === 2 &&\n    [\"SA\", \"SU\"].every((w) => byDay.some((r) => r.weekday === w))\n  )\n}\n\nexport function describeDays(recurrence: Recurrence, start: Date): string {\n  switch (recurrence.frequency) {\n    case \"WEEKLY\": {\n      const weekdays = weekdaysOf(recurrence, start)\n      return `on ${joinWords(\n        WEEKDAYS.filter((weekday) => weekdays.includes(weekday)).map(\n          (weekday) => WEEKDAY_NAMES[weekday]\n        )\n      )}`\n    }\n    case \"MONTHLY\": {\n      if (recurrence.bySetPos && recurrence.bySetPos.length > 0) {\n        const posText = joinWords(recurrence.bySetPos.map(ordinalWord))\n        if (isWorkweekDays(recurrence.byDay)) {\n          return `on the ${posText} weekday`\n        }\n        if (isWeekendDays(recurrence.byDay)) {\n          return `on the ${posText} weekend day`\n        }\n        if (recurrence.byDay.length > 0) {\n          const daysText = joinWords(\n            recurrence.byDay.map((r) => WEEKDAY_NAMES[r.weekday])\n          )\n          return `on the ${posText} ${daysText}`\n        }\n        return `on the ${posText} day`\n      }\n\n      if (recurrence.byDay.length > 0) {\n        return `on ${joinWords(\n          recurrence.byDay.map((rule) =>\n            rule.ordinal === undefined\n              ? `every ${WEEKDAY_NAMES[rule.weekday]}`\n              : `the ${ordinalWord(rule.ordinal)} ${WEEKDAY_NAMES[rule.weekday]}`\n          )\n        )}`\n      }\n      return `on ${joinWords(\n        (recurrence.byMonthDay.length > 0\n          ? recurrence.byMonthDay\n          : [start.getDate()]\n        ).map((day) => (day > 0 ? `day ${day}` : `the ${ordinalWord(day)} day`))\n      )}`\n    }\n    case \"YEARLY\": {\n      const monthPrefix =\n        recurrence.byMonth && recurrence.byMonth.length > 0\n          ? `in ${joinWords(recurrence.byMonth.map((m) => MONTH_NAMES[m] ?? `month ${m}`))}`\n          : \"\"\n\n      if (recurrence.bySetPos && recurrence.bySetPos.length > 0) {\n        const posText = joinWords(recurrence.bySetPos.map(ordinalWord))\n        const dayDesc = isWorkweekDays(recurrence.byDay)\n          ? `${posText} weekday`\n          : recurrence.byDay.length > 0\n            ? `${posText} ${joinWords(recurrence.byDay.map((r) => WEEKDAY_NAMES[r.weekday]))}`\n            : `${posText} day`\n\n        return monthPrefix\n          ? `${monthPrefix} on the ${dayDesc}`\n          : `on the ${dayDesc}`\n      }\n\n      if (recurrence.byDay.length > 0) {\n        const dayDesc = joinWords(\n          recurrence.byDay.map((rule) =>\n            rule.ordinal === undefined\n              ? `every ${WEEKDAY_NAMES[rule.weekday]}`\n              : `the ${ordinalWord(rule.ordinal)} ${WEEKDAY_NAMES[rule.weekday]}`\n          )\n        )\n        return monthPrefix ? `${monthPrefix} on ${dayDesc}` : `on ${dayDesc}`\n      }\n\n      if (recurrence.byMonthDay.length > 0) {\n        const dayDesc = joinWords(\n          recurrence.byMonthDay.map((d) =>\n            d > 0 ? `day ${d}` : `the ${ordinalWord(d)} day`\n          )\n        )\n        return monthPrefix ? `${monthPrefix} on ${dayDesc}` : `on ${dayDesc}`\n      }\n\n      if (monthPrefix) {\n        return `${monthPrefix} on day ${start.getDate()}`\n      }\n\n      return `on ${start.toLocaleDateString(\"en-US\", { month: \"long\", day: \"numeric\" })}`\n    }\n    default:\n      return \"\"\n  }\n}\n\nfunction formatSummaryUntil(until: Date, tzid?: string): string {\n  if (tzid) {\n    try {\n      return new Intl.DateTimeFormat(\"en-US\", {\n        dateStyle: \"medium\",\n        timeZone: tzid,\n      }).format(until)\n    } catch {\n      // Fall back if tzid is invalid or unsupported\n    }\n  }\n  return SUMMARY_DATE.format(until)\n}\n\nexport function describeRecurrence(recurrence: Recurrence, start: Date) {\n  const { frequency, interval, byDay, count, until } = recurrence\n  const isWorkweek =\n    frequency === \"WEEKLY\" &&\n    interval === 1 &&\n    byDay.length === 5 &&\n    WEEKDAYS.slice(0, 5).every((weekday) =>\n      byDay.some((rule) => rule.weekday === weekday)\n    )\n  const base = isWorkweek\n    ? \"Every weekday\"\n    : interval === 1\n      ? ADVERBS[frequency]\n      : `Every ${interval} ${UNITS[frequency]}s`\n  const days = isWorkweek ? \"\" : describeDays(recurrence, start)\n  const end = count\n    ? count === 1\n      ? \", once\"\n      : `, ${count} times`\n    : until\n      ? ` until ${formatSummaryUntil(until, recurrence.tzid)}`\n      : \"\"\n  return `${[base, days].filter(Boolean).join(\" \")}${end}`\n}\n",
      "type": "registry:lib"
    }
  ],
  "type": "registry:ui"
}