{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "parse-date",
  "title": "parseDate",
  "description": "Forgiving parsers for dates people type: \"tomorrow\", \"next fri\", \"in 3 weeks\", \"mar 14\", \"14 March 2027\", \"3/14\", \"2026-03-14\", and ranges such as \"Oct 1 – 8, 2026\" or \"last 30 days\".",
  "registryDependencies": [
    "@cubby-ui/date-utils"
  ],
  "files": [
    {
      "path": "registry/default/lib/parse-date.ts",
      "content": "/**\n * Forgiving parsers for dates people type: \"tomorrow\", \"next fri\", \"in 3\n * weeks\", \"mar 14\", \"14 March 2027\", \"3/14\", \"2026-03-14\", and ranges such as\n * \"Oct 1 – 8, 2026\" or \"last 30 days\". Numeric dates follow the locale's\n * day/month order. Everything resolves to local midnight.\n */\n\nimport { makeDate, startOfDay } from \"@/registry/default/lib/date-utils\";\n\nexport interface ParseDateOptions {\n  /** The \"today\" that relative input resolves against. Defaults to now. */\n  referenceDate?: Date;\n  /** BCP 47 locale for month and weekday names and numeric order. */\n  locale?: string;\n}\n\nexport interface ParsedDateRange {\n  from: Date;\n  to: Date;\n}\n\ninterface DateParts {\n  year?: number;\n  month?: number;\n  day?: number;\n}\n\ntype Parsed = { date: Date } | { parts: DateParts };\n\ntype Unit = \"day\" | \"week\" | \"month\" | \"year\";\n\nconst UNITS: Record<string, Unit> = {\n  d: \"day\",\n  day: \"day\",\n  days: \"day\",\n  w: \"week\",\n  wk: \"week\",\n  wks: \"week\",\n  week: \"week\",\n  weeks: \"week\",\n  mo: \"month\",\n  mos: \"month\",\n  month: \"month\",\n  months: \"month\",\n  y: \"year\",\n  yr: \"year\",\n  yrs: \"year\",\n  year: \"year\",\n  years: \"year\",\n};\n\nconst KEYWORDS: Record<string, number> = {\n  today: 0,\n  tod: 0,\n  now: 0,\n  tomorrow: 1,\n  tmr: 1,\n  tmrw: 1,\n  tom: 1,\n  yesterday: -1,\n  yday: -1,\n};\n\n/** Own entries only, so names like \"constructor\" aren't found on Object. */\nfunction unitOf(name: string): Unit | undefined {\n  return Object.hasOwn(UNITS, name) ? UNITS[name] : undefined;\n}\n\nfunction keywordOf(name: string): number | undefined {\n  return Object.hasOwn(KEYWORDS, name) ? KEYWORDS[name] : undefined;\n}\n\nconst MIN_YEAR = 1;\nconst MAX_YEAR = 9999;\n\n/**\n * Null for out-of-range years and Invalid Date, which huge input like\n * \"in 99999999 years\" produces and which throws when formatted.\n */\nfunction valid(date: Date | null): Date | null {\n  if (!date || Number.isNaN(date.getTime())) return null;\n  const year = date.getFullYear();\n  return year >= MIN_YEAR && year <= MAX_YEAR ? date : null;\n}\n\nconst RANGE_SEPARATOR = /\\s+(?:-|to|until|till|through|thru)\\s+|\\s*[–—]\\s*/;\n\n/* -------------------------------------------------------------------------------------------------\n * Date arithmetic\n * -------------------------------------------------------------------------------------------------*/\n\nfunction daysInMonth(year: number, month: number): number {\n  return makeDate(year, month + 1, 0).getDate();\n}\n\n/** Adds whole units. Months and years clamp to the end of a shorter month. */\nfunction add(date: Date, amount: number, unit: Unit): Date {\n  if (unit === \"day\" || unit === \"week\") {\n    const days = unit === \"week\" ? amount * 7 : amount;\n    return makeDate(date.getFullYear(), date.getMonth(), date.getDate() + days);\n  }\n  const months = unit === \"year\" ? amount * 12 : amount;\n  const target = makeDate(date.getFullYear(), date.getMonth() + months, 1);\n  const day = Math.min(\n    date.getDate(),\n    daysInMonth(target.getFullYear(), target.getMonth()),\n  );\n  return makeDate(target.getFullYear(), target.getMonth(), day);\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Locale names\n * -------------------------------------------------------------------------------------------------*/\n\nconst nameCache = new Map<string, Map<string, number>>();\n\nfunction normalizeName(name: string): string {\n  return name.toLowerCase().replace(/\\.$/, \"\");\n}\n\n/** Month names (long and short) in the locale and English, to month index. */\nfunction monthNames(locale: string | undefined): Map<string, number> {\n  const key = `month:${locale ?? \"\"}`;\n  const cached = nameCache.get(key);\n  if (cached) return cached;\n\n  const names = new Map<string, number>();\n  for (const loc of new Set([locale, \"en\"])) {\n    for (const width of [\"long\", \"short\"] as const) {\n      const format = new Intl.DateTimeFormat(loc, { month: width });\n      for (let month = 0; month < 12; month++) {\n        names.set(\n          normalizeName(format.format(new Date(2000, month, 1))),\n          month,\n        );\n      }\n    }\n  }\n  names.set(\"sept\", 8);\n  nameCache.set(key, names);\n  return names;\n}\n\n/** Weekday names (long and short) in the locale and English, to 0–6. */\nfunction weekdayNames(locale: string | undefined): Map<string, number> {\n  const key = `weekday:${locale ?? \"\"}`;\n  const cached = nameCache.get(key);\n  if (cached) return cached;\n\n  const names = new Map<string, number>();\n  for (const loc of new Set([locale, \"en\"])) {\n    for (const width of [\"long\", \"short\"] as const) {\n      const format = new Intl.DateTimeFormat(loc, { weekday: width });\n      // 2 January 2000 was a Sunday.\n      for (let weekday = 0; weekday < 7; weekday++) {\n        names.set(\n          normalizeName(format.format(new Date(2000, 0, 2 + weekday))),\n          weekday,\n        );\n      }\n    }\n  }\n  for (const [name, weekday] of Object.entries({\n    tues: 2,\n    weds: 3,\n    thur: 4,\n    thurs: 4,\n  })) {\n    names.set(name, weekday);\n  }\n  nameCache.set(key, names);\n  return names;\n}\n\n/** Whether the locale writes the day before the month in numeric dates. */\nfunction isDayFirst(locale: string | undefined): boolean {\n  const parts = new Intl.DateTimeFormat(locale, {\n    day: \"numeric\",\n    month: \"numeric\",\n  }).formatToParts(new Date(2000, 10, 22));\n  const day = parts.findIndex((part) => part.type === \"day\");\n  const month = parts.findIndex((part) => part.type === \"month\");\n  return day < month;\n}\n\n/** Expands a two-digit year to the century that lands within 20 years ahead. */\nfunction expandYear(year: number, reference: Date): number {\n  if (year >= 100) return year;\n  const current = reference.getFullYear();\n  let full = Math.floor(current / 100) * 100 + year;\n  if (full > current + 20) full -= 100;\n  return full;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Single dates\n * -------------------------------------------------------------------------------------------------*/\n\nfunction parseRelative(text: string, reference: Date): Date | null {\n  const keyword = keywordOf(text);\n  if (keyword !== undefined) return add(reference, keyword, \"day\");\n\n  // \"in 3 days\", \"+2w\", \"3 weeks\"\n  const ahead = text.match(/^(?:in\\s+|\\+)?(\\d+)\\s*([a-z]+)$/);\n  const aheadUnit = ahead && unitOf(ahead[2]);\n  if (ahead && aheadUnit) return add(reference, Number(ahead[1]), aheadUnit);\n\n  // \"-2w\", \"3 days ago\"\n  const behind =\n    text.match(/^-(\\d+)\\s*([a-z]+)$/) ?? text.match(/^(\\d+)\\s*([a-z]+)\\s+ago$/);\n  const behindUnit = behind && unitOf(behind[2]);\n  if (behind && behindUnit) {\n    return add(reference, -Number(behind[1]), behindUnit);\n  }\n\n  // \"next week\", \"last month\", \"this year\"\n  const step = text.match(/^(next|last|this)\\s+([a-z]+)$/);\n  const stepUnit = step && unitOf(step[2]);\n  if (step && stepUnit) {\n    const direction = { next: 1, last: -1, this: 0 }[step[1] as \"next\"];\n    return add(reference, direction, stepUnit);\n  }\n\n  return null;\n}\n\nfunction parseWeekday(\n  text: string,\n  reference: Date,\n  locale: string | undefined,\n): Date | null {\n  const match = text.match(/^(?:(next|last|this|on)\\s+)?([^\\s\\d]+)$/);\n  if (!match) return null;\n  const weekday = weekdayNames(locale).get(normalizeName(match[2]));\n  if (weekday === undefined) return null;\n\n  const today = reference.getDay();\n  if (match[1] === \"last\") {\n    // The most recent one before today.\n    return add(reference, -(((today - weekday + 6) % 7) + 1), \"day\");\n  }\n  if (match[1] === \"next\") {\n    // The first one after today.\n    return add(reference, ((weekday - today + 6) % 7) + 1, \"day\");\n  }\n  // Bare or \"this\": today if it matches, otherwise the next one.\n  return add(reference, (weekday - today + 7) % 7, \"day\");\n}\n\nfunction parseNumeric(\n  text: string,\n  reference: Date,\n  locale: string | undefined,\n): DateParts | null {\n  // Year first is unambiguous: 2026-03-14, 2026/3/14.\n  const yearFirst = text.match(/^(\\d{4})[-/.](\\d{1,2})[-/.](\\d{1,2})$/);\n  if (yearFirst) {\n    return {\n      year: Number(yearFirst[1]),\n      month: Number(yearFirst[2]) - 1,\n      day: Number(yearFirst[3]),\n    };\n  }\n\n  const short = text.match(/^(\\d{1,2})[-/.](\\d{1,2})(?:[-/.](\\d{2}|\\d{4}))?$/);\n  if (!short) return null;\n  const [first, second] = [Number(short[1]), Number(short[2])];\n  const [day, month] = isDayFirst(locale) ? [first, second] : [second, first];\n  return {\n    day,\n    month: month - 1,\n    year: short[3] ? expandYear(Number(short[3]), reference) : undefined,\n  };\n}\n\n/** Word dates in any order: \"mar 14\", \"14th of march 2027\", \"thu oct 1\". */\nfunction parseWords(\n  text: string,\n  reference: Date,\n  locale: string | undefined,\n): DateParts | null {\n  const months = monthNames(locale);\n  const weekdays = weekdayNames(locale);\n  const parts: DateParts = {};\n\n  for (const raw of text.split(\" \")) {\n    const token = normalizeName(raw);\n    if (!token || token === \"of\" || token === \"the\") continue;\n\n    // Months first: in some locales a weekday and a month share a short name\n    // (\"mar\" is Tuesday and March in Spanish and Italian).\n    const month = months.get(token);\n    if (month !== undefined) {\n      if (parts.month !== undefined) return null;\n      parts.month = month;\n      continue;\n    }\n\n    // A weekday alongside a full date (\"Thu, Oct 1\") is redundant.\n    if (weekdays.has(token)) continue;\n\n    const number = token.match(/^'?(\\d+)(?:st|nd|rd|th)?$/);\n    if (!number) return null;\n    const value = Number(number[1]);\n    const isYear =\n      number[1].length >= 3 || raw.startsWith(\"'\") || parts.day !== undefined;\n    if (isYear) {\n      if (parts.year !== undefined) return null;\n      parts.year = expandYear(value, reference);\n    } else {\n      parts.day = value;\n    }\n  }\n\n  return Object.keys(parts).length > 0 ? parts : null;\n}\n\nfunction parseOne(\n  input: string,\n  reference: Date,\n  locale: string | undefined,\n): Parsed | null {\n  const text = input\n    .trim()\n    .toLowerCase()\n    .replace(/,/g, \" \")\n    .replace(/\\s+/g, \" \");\n  if (!text) return null;\n\n  const relative =\n    parseRelative(text, reference) ?? parseWeekday(text, reference, locale);\n  if (relative) return { date: relative };\n\n  const parts =\n    parseNumeric(text, reference, locale) ??\n    parseWords(text, reference, locale);\n  return parts ? { parts } : null;\n}\n\n/** Fills missing parts from the reference date; rejects impossible days. */\nfunction resolve(parts: DateParts, reference: Date): Date | null {\n  const year = parts.year ?? reference.getFullYear();\n  const month = parts.month ?? reference.getMonth();\n  // A month on its own (\"march 2027\") means its first day.\n  const day =\n    parts.day ?? (parts.month !== undefined ? 1 : reference.getDate());\n  if (year < MIN_YEAR || year > MAX_YEAR) return null;\n  if (month < 0 || month > 11 || day < 1 || day > daysInMonth(year, month)) {\n    return null;\n  }\n  return makeDate(year, month, day);\n}\n\n/**\n * Reads a typed date. Returns `null` when the text isn't a date it\n * understands, or names a day that doesn't exist (\"feb 30\").\n */\nexport function parseDate(\n  input: string,\n  options: ParseDateOptions = {},\n): Date | null {\n  const reference = startOfDay(options.referenceDate ?? new Date());\n  const parsed = parseOne(input, reference, options.locale);\n  if (!parsed) return null;\n  return valid(\n    \"date\" in parsed ? parsed.date : resolve(parsed.parts, reference),\n  );\n}\n\nfunction dateOf(parsed: Parsed): Date | null {\n  return \"date\" in parsed ? parsed.date : null;\n}\n\nfunction checkedRange(range: ParsedDateRange): ParsedDateRange | null {\n  const from = valid(range.from);\n  const to = valid(range.to);\n  return from && to ? { from, to } : null;\n}\n\n/* -------------------------------------------------------------------------------------------------\n * Ranges\n * -------------------------------------------------------------------------------------------------*/\n\nfunction parseRelativeRange(\n  text: string,\n  reference: Date,\n): ParsedDateRange | null {\n  // \"last 7 days\", \"past 2 weeks\", \"next 30 days\"\n  const match = text.match(/^(last|past|next)\\s+(\\d+)\\s*([a-z]+)$/);\n  const unit = match && unitOf(match[3]);\n  if (!match || !unit) return null;\n  const amount = Number(match[2]);\n  if (amount < 1) return null;\n  if (match[1] === \"next\") {\n    return {\n      from: reference,\n      to: add(add(reference, amount, unit), -1, \"day\"),\n    };\n  }\n  return { from: add(add(reference, -amount, unit), 1, \"day\"), to: reference };\n}\n\n/**\n * Reads a typed range: two dates joined by a dash, \"to\", or \"until\", or a\n * relative span like \"last 7 days\". The second date borrows a missing month\n * or year from the first (\"Oct 1 – 8\"), the first borrows a missing year from\n * the second (\"Oct 1 – 8, 2026\"), and a range written backwards is flipped. A\n * single date reads as a one-day range.\n */\nexport function parseDateRange(\n  input: string,\n  options: ParseDateOptions = {},\n): ParsedDateRange | null {\n  const reference = startOfDay(options.referenceDate ?? new Date());\n  const { locale } = options;\n  const text = input.trim().toLowerCase().replace(/\\s+/g, \" \");\n  if (!text) return null;\n\n  const relative = parseRelativeRange(text, reference);\n  if (relative) return checkedRange(relative);\n\n  const sides = text.split(RANGE_SEPARATOR);\n  if (sides.length === 1) {\n    const date = parseDate(text, options);\n    return date ? { from: date, to: date } : null;\n  }\n  if (sides.length !== 2) return null;\n\n  const start = parseOne(sides[0], reference, locale);\n  const end = parseOne(sides[1], reference, locale);\n  if (!start || !end) return null;\n\n  const startParts = \"parts\" in start ? { ...start.parts } : null;\n  const endParts = \"parts\" in end ? { ...end.parts } : null;\n  // Whether a side's year came from the other side rather than the text.\n  let startYearBorrowed = false;\n  let endYearBorrowed = false;\n\n  if (startParts && endParts) {\n    endParts.month ??= startParts.month;\n    if (endParts.year === undefined && startParts.year !== undefined) {\n      endParts.year = startParts.year;\n      endYearBorrowed = true;\n    } else if (startParts.year === undefined && endParts.year !== undefined) {\n      startParts.year = endParts.year;\n      startYearBorrowed = true;\n    }\n  }\n\n  let from = startParts ? resolve(startParts, reference) : dateOf(start);\n  if (!from) return null;\n  // A bare end (\"today – 14\") fills in from the start, not from today.\n  let to = endParts ? resolve(endParts, from) : dateOf(end);\n  if (!to) return null;\n\n  if (to < from && to.getMonth() < from.getMonth()) {\n    // Running backwards across months with an inferred year means the range\n    // crosses New Year: \"Dec 28 – Jan 4\" ends in the January after.\n    if (startParts && startYearBorrowed) {\n      from = resolve({ ...startParts, year: to.getFullYear() - 1 }, reference);\n    } else if (endParts && (endYearBorrowed || endParts.year === undefined)) {\n      to = resolve({ ...endParts, year: from.getFullYear() + 1 }, from);\n    }\n    if (!from || !to) return null;\n  }\n  return checkedRange(to < from ? { from: to, to: from } : { from, to });\n}\n",
      "type": "registry:lib",
      "target": "lib/cubby-ui/parse-date.ts"
    }
  ],
  "type": "registry:lib"
}