temporal-fmt 0.9.80 → 0.9.82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +302 -490
  2. package/dist/{chunk-Z245NHDT.js → chunk-4JMHI6E2.js} +6 -6
  3. package/dist/chunk-7XSIPXIR.js +129 -0
  4. package/dist/chunk-7XSIPXIR.js.map +1 -0
  5. package/dist/{chunk-DMJWJTFY.js → chunk-AF3LHBDQ.js} +2 -2
  6. package/dist/{chunk-WEVNKOQA.js → chunk-IEQCJPB5.js} +5 -5
  7. package/dist/{chunk-DFWTCRS3.js → chunk-JCJW2VOV.js} +10 -7
  8. package/dist/chunk-JCJW2VOV.js.map +1 -0
  9. package/dist/{chunk-HGRT37LT.js → chunk-KWOTFJNY.js} +3 -3
  10. package/dist/{chunk-64UB3WDT.js → chunk-NHNUFNQ7.js} +4 -4
  11. package/dist/{chunk-WP7TBCTT.js → chunk-TIMSK72I.js} +8 -8
  12. package/dist/{chunk-LHR5PCP4.js → chunk-UYKKGBZ3.js} +7 -7
  13. package/dist/{chunk-5KP5H7X2.js → chunk-W45J4E76.js} +6 -4
  14. package/dist/duration.js +3 -3
  15. package/dist/format.cjs +7 -4
  16. package/dist/format.cjs.map +1 -1
  17. package/dist/format.js +5 -5
  18. package/dist/index.cjs +147 -34
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +1 -0
  21. package/dist/index.d.ts +1 -0
  22. package/dist/index.js +108 -87
  23. package/dist/index.js.map +1 -1
  24. package/dist/interval.cjs +7 -4
  25. package/dist/interval.cjs.map +1 -1
  26. package/dist/interval.js +7 -7
  27. package/dist/legacy/index.d.cts +23 -0
  28. package/dist/legacy/index.d.ts +23 -0
  29. package/dist/legacy/matchesFormat.d.cts +6 -0
  30. package/dist/legacy/matchesFormat.d.ts +6 -0
  31. package/dist/legacy.cjs +2156 -0
  32. package/dist/legacy.cjs.map +1 -0
  33. package/dist/legacy.d.cts +1 -0
  34. package/dist/legacy.d.ts +1 -0
  35. package/dist/legacy.js +31 -0
  36. package/dist/legacy.js.map +1 -0
  37. package/dist/parse.cjs +7 -4
  38. package/dist/parse.cjs.map +1 -1
  39. package/dist/parse.js +5 -5
  40. package/dist/relativeTime.cjs +6 -2
  41. package/dist/relativeTime.cjs.map +1 -1
  42. package/dist/relativeTime.js +4 -4
  43. package/dist/timezone.cjs +6 -2
  44. package/dist/timezone.cjs.map +1 -1
  45. package/dist/timezone.js +2 -2
  46. package/legacy.d.cts +1 -0
  47. package/legacy.d.ts +1 -0
  48. package/package.json +13 -1
  49. package/dist/chunk-DFWTCRS3.js.map +0 -1
  50. /package/dist/{chunk-Z245NHDT.js.map → chunk-4JMHI6E2.js.map} +0 -0
  51. /package/dist/{chunk-DMJWJTFY.js.map → chunk-AF3LHBDQ.js.map} +0 -0
  52. /package/dist/{chunk-WEVNKOQA.js.map → chunk-IEQCJPB5.js.map} +0 -0
  53. /package/dist/{chunk-HGRT37LT.js.map → chunk-KWOTFJNY.js.map} +0 -0
  54. /package/dist/{chunk-64UB3WDT.js.map → chunk-NHNUFNQ7.js.map} +0 -0
  55. /package/dist/{chunk-WP7TBCTT.js.map → chunk-TIMSK72I.js.map} +0 -0
  56. /package/dist/{chunk-LHR5PCP4.js.map → chunk-UYKKGBZ3.js.map} +0 -0
  57. /package/dist/{chunk-5KP5H7X2.js.map → chunk-W45J4E76.js.map} +0 -0
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/formatDistance.ts","../src/typeGuards.ts","../src/tokenMetadata.ts","../src/analyze.ts","../src/serialization.ts","../src/relativeGrammar.ts","../src/parseRelative.ts","../src/config.ts","../src/businessCalendar.ts","../src/holidays.ts","../src/extensibility.ts","../src/ideData.ts","../src/codemod.ts"],"sourcesContent":["/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_LOCALE, type FormatOptions } from './tokens.js';\nimport { isGregorianLeapYear, daysFromCivil } from './isoWeek.js';\nimport { normalizeLocaleTag } from './localeVocab.js';\nimport { InvalidLocaleError, InvalidDateError } from './errors.js';\n\n// Reads date fields off a Temporal value in the same minimal-shape style\n// as the rest of the library (TemporalLike) — no Temporal factory needed.\n// Works for PlainDate, PlainDateTime, and ZonedDateTime (since they all\n// expose year/month/day). PlainTime has no date fields; formatDistance()\n// between two PlainTime values isn't really meaningful and isn't\n// supported — it'll throw below when the field read fails.\ninterface DateFieldView {\n year?: number;\n month?: number;\n day?: number;\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n}\n\nfunction readFields(value: unknown, label: string): DateFieldView {\n if (value === null || typeof value !== 'object') {\n throw new Error(\n `temporal-fmt: formatDistance expects Temporal values, got ${label} = ${String(value)}.`\n );\n }\n const obj = value as Record<string, unknown>;\n // Either year/month/day (a real date) or none of them (a PlainTime);\n // anything in between would be a malformed Temporal-like.\n const hasYear = typeof obj.year === 'number';\n const hasMonth = typeof obj.month === 'number';\n const hasDay = typeof obj.day === 'number';\n if (hasYear !== hasMonth || hasMonth !== hasDay) {\n throw new Error(\n `temporal-fmt: formatDistance got a ${label} with a partial date (some of year/month/day missing). ` +\n `Pass a full Temporal.PlainDate / PlainDateTime / ZonedDateTime.`\n );\n }\n // Range validation on the date triple. This function accepts plain\n // field bags (documented duck-typing), so the fields are untrusted\n // caller data, and every downstream consumer assumed a real calendar\n // date: a year of 1e9 used to drive a O(|year|) day-accumulation loop\n // (hundreds of ms per call — a cheap CPU-denial primitive when an app\n // feeds user-controlled parsed values in), and month 0 / Feb 31 fell\n // through to either V8-internal Intl errors or silently-wrong\n // distances. Real Temporal values always pass these checks, so this\n // only ever fires on hostile/hand-rolled bags.\n if (hasYear) {\n const y = obj.year as number;\n const m = obj.month as number;\n const d = obj.day as number;\n if (!Number.isFinite(y) || !Number.isInteger(y) || y < MIN_YEAR || y > MAX_YEAR) {\n throw new InvalidDateError({\n input: label,\n reason: `year ${y} is outside the ${MIN_YEAR}..${MAX_YEAR} range Temporal can represent`,\n });\n }\n if (!Number.isInteger(m) || m < 1 || m > 12) {\n throw new InvalidDateError({\n input: label,\n reason: `month ${m} is not in 1..12`,\n });\n }\n const maxDay = m === 2 && isGregorianLeapYear(y) ? 29 : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]!;\n if (!Number.isInteger(d) || d < 1 || d > maxDay) {\n throw new InvalidDateError({\n input: label,\n reason: `day ${d} is not valid for year ${y}, month ${m} (max ${maxDay})`,\n });\n }\n }\n return {\n year: hasYear ? (obj.year as number) : undefined,\n month: hasMonth ? (obj.month as number) : undefined,\n day: hasDay ? (obj.day as number) : undefined,\n hour: typeof obj.hour === 'number' ? (obj.hour as number) : undefined,\n minute: typeof obj.minute === 'number' ? (obj.minute as number) : undefined,\n second: typeof obj.second === 'number' ? (obj.second as number) : undefined,\n millisecond: typeof obj.millisecond === 'number' ? (obj.millisecond as number) : undefined,\n };\n}\n\n// Temporal's representable ISO year range (PlainDate accepts -271821\n// through 275760). Values beyond this can't come from a real Temporal\n// object, so they're rejected as malformed input rather than walked.\nconst MIN_YEAR = -271_821;\nconst MAX_YEAR = 275_760;\n\n// Reference epoch for ms-since computation. Jan 1, 2000 UTC is the same\n// anchor isoWeek.ts uses for day-of-week arithmetic; reusing it keeps the\n// reasoning localized to one well-known reference date.\nconst REFERENCE_YEAR = 2000;\nconst MS_PER_SECOND = 1000;\nconst MS_PER_MINUTE = 60 * MS_PER_SECOND;\nconst MS_PER_HOUR = 60 * MS_PER_MINUTE;\nconst MS_PER_DAY = 24 * MS_PER_HOUR;\n\nfunction daysSinceReference(year: number, month: number, day: number): number {\n // O(1): days_from_civil for the target minus days_from_civil for the\n // reference. The old version accumulated 365/366 per year in a loop —\n // identical results for every real date, but O(|year − 2000|), which\n // made hostile field-bag years (1e9+) an accidental CPU-denial\n // primitive. (Range validation in readFields already rejects years\n // Temporal can't represent; this closed form makes even the\n // in-range walk instant.)\n return daysFromCivil(year, month, day) - daysFromCivil(REFERENCE_YEAR, 1, 1);\n}\n\nfunction toEpochMs(fields: DateFieldView): number {\n // A PlainDate has no time fields — treat as midnight. A PlainDateTime\n // has them all. Comparing two PlainDates is a day-resolution diff;\n // comparing two PlainDateTimes is millisecond-resolution. Mixing the\n // two (one PlainDate, one PlainDateTime) is allowed and just means the\n // PlainDate side is treated as midnight, which is what most callers\n // would intuitively expect (\"distance from this date to this moment\").\n if (fields.year === undefined || fields.month === undefined || fields.day === undefined) {\n throw new Error(\n `temporal-fmt: formatDistance needs a Temporal value with year/month/day fields ` +\n `(PlainDate, PlainDateTime, or ZonedDateTime). A PlainTime or other shape ` +\n `has no anchor date to diff against.`\n );\n }\n const days = daysSinceReference(fields.year, fields.month, fields.day);\n const hour = fields.hour ?? 0;\n const minute = fields.minute ?? 0;\n const second = fields.second ?? 0;\n const millisecond = fields.millisecond ?? 0;\n return days * MS_PER_DAY + hour * MS_PER_HOUR + minute * MS_PER_MINUTE + second * MS_PER_SECOND + millisecond;\n}\n\n// Unit selection cutoffs. Mirrors the rough thresholds date-fns uses,\n// trimmed to the units Intl.RelativeTimeFormat supports in every engine\n// (it accepts 'second' through 'year'; 'quarter' and 'week' support\n// varies, so we skip 'week' here — going days → months directly at the\n// 30-day boundary is simpler and avoids the engine-support cliff).\n//\n// |diff| < 60 s → seconds (\"30 seconds ago\")\n// |diff| < 60 min → minutes (\"12 minutes ago\")\n// |diff| < 24 h → hours (\"3 hours ago\")\n// |diff| < 30 d → days (\"5 days ago\")\n// |diff| < 365 d → months (\"2 months ago\")\n// otherwise → years (\"1 year ago\")\n//\n// 30 days is an approximation of a month — a calendar month is 28-31\n// days, so the boundary is inherently fuzzy. Same with 365 days for a\n// year. Documented as approximations, not exact calendar arithmetic.\n//\n// `cutoffs` on FormatDistanceOptions overrides individual boundaries\n// per call. DEFAULT_CUTOFFS holds the same numbers as the old hardcoded\n// UNIT_CUTOFFS so callers passing nothing see the same output as\n// before — verified byte-for-byte against the pre-change baseline.\nconst DEFAULT_CUTOFFS = {\n seconds: 60, // 60 s\n minutes: 60, // 60 min\n hours: 24, // 24 h\n days: 30, // 30 d\n months: 365, // 365 d (in days, since the months→years boundary is day-resolution)\n} as const;\n\ntype CutoffKey = keyof typeof DEFAULT_CUTOFFS;\n\n// Cutoffs the caller can override. Each value is in the unit's own\n// native scale (seconds for `seconds`, minutes for `minutes`, etc.) —\n// `months` is the exception: it's the day count that bounds the\n// months→years crossover, since \"months\" itself isn't a fixed number\n// of days. This mirrors how the original hardcoded table expressed\n// the same boundary (30 * MS_PER_DAY for days, 365 * MS_PER_DAY for\n// the months cap) and lets callers say \"treat anything under 90 days\n// as months\" rather than \"anything under 3 months as months\" (which\n// would require picking a definition of \"month\").\nexport interface DistanceCutoffs {\n seconds?: number;\n minutes?: number;\n hours?: number;\n days?: number;\n months?: number;\n}\n\n// Convert the user-facing cutoffs (per-unit numbers) into the ms\n// thresholds the matching loop needs. Validates each value is a\n// positive finite number, and that the boundaries are monotonically\n// non-decreasing in equivalent ms — without that, the smallest-bound\n// branch always wins and a later branch becomes unreachable, which\n// is never what the caller intended.\nfunction resolveCutoffs(user?: DistanceCutoffs): Array<{ maxMs: number; unit: Intl.RelativeTimeFormatUnit }> {\n const merged: Record<CutoffKey, number> = { ...DEFAULT_CUTOFFS, ...user };\n\n for (const key of Object.keys(merged) as CutoffKey[]) {\n const value = merged[key];\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new Error(\n `temporal-fmt: formatDistance cutoff \"${key}\" must be a positive finite number (got ${String(value)}).`\n );\n }\n }\n\n const secondsMs = merged.seconds * MS_PER_SECOND;\n const minutesMs = merged.minutes * MS_PER_MINUTE;\n const hoursMs = merged.hours * MS_PER_HOUR;\n const daysMs = merged.days * MS_PER_DAY;\n // `months` is in days — see DistanceCutoffs comment above.\n const monthsMs = merged.months * MS_PER_DAY;\n\n if (!(secondsMs <= minutesMs && minutesMs <= hoursMs && hoursMs <= daysMs && daysMs <= monthsMs)) {\n throw new Error(\n `temporal-fmt: formatDistance cutoffs must be monotonically non-decreasing in equivalent ms ` +\n `(seconds ≤ minutes ≤ hours ≤ days ≤ months). Got: seconds=${merged.seconds}s, ` +\n `minutes=${merged.minutes}min, hours=${merged.hours}h, days=${merged.days}d, months=${merged.months}d — ` +\n `pick a sequence where each boundary is at least as large as the one before it.`\n );\n }\n\n return [\n { maxMs: secondsMs, unit: 'second' },\n { maxMs: minutesMs, unit: 'minute' },\n { maxMs: hoursMs, unit: 'hour' },\n { maxMs: daysMs, unit: 'day' },\n { maxMs: monthsMs, unit: 'month' },\n ];\n}\n\nconst rtfCache = new Map<string, Intl.RelativeTimeFormat>();\nconst MAX_RTF_CACHE_SIZE = 100;\n\nfunction getRtf(locale: string, numeric: 'always' | 'auto'): Intl.RelativeTimeFormat {\n const key = `${canonicalLocaleKey(locale)}|${numeric}`;\n let rtf = rtfCache.get(key);\n if (rtf) return rtf;\n if (rtfCache.size >= MAX_RTF_CACHE_SIZE) {\n const oldestKey = rtfCache.keys().next().value;\n if (oldestKey !== undefined) rtfCache.delete(oldestKey);\n }\n try {\n rtf = new Intl.RelativeTimeFormat(normalizeLocaleTag(locale), { numeric });\n } catch (err) {\n // Malformed locale tags reach Intl as a bare RangeError; surface the\n // library's typed error instead. (Every failure mode of these\n // constructors with a string locale is a RangeError, so converting\n // unconditionally loses nothing — the original message is preserved\n // in `reason` either way.)\n throw new InvalidLocaleError({ actual: locale, reason: (err as Error).message });\n }\n rtfCache.set(key, rtf);\n return rtf;\n}\n\nfunction canonicalLocaleKey(locale: string): string {\n try {\n return new Intl.Locale(locale.replace(/_/g, '-')).toString().toLowerCase();\n } catch {\n return locale;\n }\n}\n\nexport interface FormatDistanceOptions extends FormatOptions {\n /**\n * 'auto' (default) lets Intl.RelativeTimeFormat use natural forms like\n * \"yesterday\"/\"tomorrow\"/\"now\" when the rounded value lands on ±1 or 0.\n * 'always' forces the strict \"1 day ago\"/\"in 1 day\"/\"in 0 seconds\" form.\n */\n numeric?: 'always' | 'auto';\n /**\n * Override the unit-selection boundaries (seconds→minutes,\n * minutes→hours, hours→days, days→months, months→years). Any\n * subset can be supplied; omitted boundaries fall back to the\n * defaults (60s, 60min, 24h, 30d, 365d). Values are in each\n * unit's native scale except `months`, which is in days — see\n * DistanceCutoffs. Throws descriptively on non-monotonic\n * boundaries or non-positive values, rather than producing\n * confusing output downstream.\n */\n cutoffs?: DistanceCutoffs;\n}\n\n/**\n * Returns a human-readable relative-time string describing `date1`\n * relative to `date2`, e.g. \"3 days ago\", \"in 2 hours\", \"now\". Delegates\n * unit names and pluralization to `Intl.RelativeTimeFormat` so the\n * output localizes the same way the rest of the library's locale-aware\n * tokens do.\n *\n * Convention: the result describes `date1`'s position relative to\n * `date2`. `formatDistance(now, threeDaysAgo)` → `\"3 days ago\"` (the\n * past date is described relative to now). `formatDistance(now, twoHoursFromNow)`\n * → `\"in 2 hours\"`. This matches the natural-language reading \"describe\n * the first date as if standing at the second one.\"\n *\n * Unit-selection cutoffs (seconds → minutes → hours → days → months →\n * years) and the rationale for each are documented in the README under\n * \"formatDistance\".\n *\n * @example\n * formatDistance(threeDaysAgo, today) // \"3 days ago\"\n * formatDistance(twoHoursFromNow, today) // \"in 2 hours\"\n * formatDistance(today, today) // \"now\"\n * formatDistance(futureDate, today, {locale:'fr-FR'}) // \"dans 2 jours\"\n */\nexport function formatDistance(\n date1: unknown,\n date2: unknown,\n options: FormatDistanceOptions = {},\n): string {\n const fields1 = readFields(date1, 'date1');\n const fields2 = readFields(date2, 'date2');\n\n // diff > 0: date1 is later than date2 → \"in X units\" (date1 is in\n // the future relative to date2). diff < 0: date1 is earlier than\n // date2 → \"X units ago\". This convention puts date1 in the\n // \"described\" role and date2 in the \"reference\" role, matching\n // natural-language reading: `formatDistance(threeDaysAgo, today)`\n // = \"describe threeDaysAgo as if standing at today\" = \"3 days ago\".\n const diffMs = toEpochMs(fields1) - toEpochMs(fields2);\n const absMs = Math.abs(diffMs);\n\n const unitCutoffs = resolveCutoffs(options.cutoffs);\n let unit: Intl.RelativeTimeFormatUnit = 'year';\n for (const { maxMs, unit: candidateUnit } of unitCutoffs) {\n if (absMs < maxMs) {\n unit = candidateUnit;\n break;\n }\n }\n\n const divisor = unitToMs(unit);\n const rounded = Math.round(diffMs / divisor);\n\n const numeric = options.numeric ?? 'auto';\n const locale = options.locale ?? DEFAULT_LOCALE;\n const rtf = getRtf(locale, numeric);\n return rtf.format(rounded, unit);\n}\n\n/**\n * Same as formatDistance(date, now), where \"now\" is read from the system\n * clock at call time. Convenience wrapper for the common \"how long ago\n * was this\" case, so the caller doesn't have to construct a reference\n * value themselves.\n *\n * Unlike formatRelativeToNow() (in relativeTime.ts), which only needs\n * calendar-day resolution, this reads the full wall-clock time (hour\n * through millisecond) off the system clock — formatDistance's unit\n * selection is ms-resolution, so a date-only \"now\" would misclassify\n * anything under 24 hours old (e.g. \"1 hour ago\" reading as \"in 23\n * hours\" against a midnight-truncated reference). See the test file\n * for a regression case covering exactly that.\n *\n * The reference is captured fresh on every call, not memoized — each\n * call reflects \"now\" at the moment it runs, same expectation\n * formatRelativeToNow() already sets.\n *\n * @example\n * formatDistanceToNow(threeHoursAgo) // \"3 hours ago\"\n * formatDistanceToNow(tomorrow) // \"in 1 day\" (auto: \"tomorrow\")\n */\nexport function formatDistanceToNow(\n date: unknown,\n options: FormatDistanceOptions = {},\n): string {\n const now = new Date();\n const nowFields = {\n year: now.getFullYear(),\n month: now.getMonth() + 1,\n day: now.getDate(),\n hour: now.getHours(),\n minute: now.getMinutes(),\n second: now.getSeconds(),\n millisecond: now.getMilliseconds(),\n };\n return formatDistance(date, nowFields, options);\n}\n\nfunction unitToMs(unit: Intl.RelativeTimeFormatUnit): number {\n switch (unit) {\n case 'second': return MS_PER_SECOND;\n case 'minute': return MS_PER_MINUTE;\n case 'hour': return MS_PER_HOUR;\n case 'day': return MS_PER_DAY;\n /* c8 ignore start @preserve -- unreachable: unitToMs is only called\n with `unit` values produced by formatDistance's cutoff loop above,\n which only ever yields 'second'/'minute'/'hour'/'day'/'month'\n (from resolveCutoffs' fixed array) or 'year' (the loop's fallback\n default). 'week' and 'quarter' were never wired into\n resolveCutoffs — formatDistance intentionally skips week-\n resolution output (see the comment above DEFAULT_CUTOFFS) — so\n neither can reach this switch. */\n case 'week': return 7 * MS_PER_DAY;\n /* c8 ignore stop @preserve */\n case 'month': return 30 * MS_PER_DAY;\n /* c8 ignore start @preserve -- unreachable, same reason as 'week'\n above: resolveCutoffs never produces 'quarter'. */\n case 'quarter': return 91 * MS_PER_DAY;\n /* c8 ignore stop @preserve */\n case 'year': return 365 * MS_PER_DAY;\n /* c8 ignore start @preserve -- unreachable: every unit\n resolveCutoffs can actually produce ('second' through 'month', or\n 'year' as the loop's fallback default) has an explicit case\n above, so this exhaustive-switch default can't fire at runtime.\n It exists so TS accepts the function as total — the compiler\n can't see through the cutoff-array iteration in formatDistance()\n to know the input is already narrowed. */\n default:\n throw new Error(`temporal-fmt: formatDistance hit unhandled unit \"${String(unit)}\".`);\n /* c8 ignore stop @preserve */\n }\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// type guards for Temporal values. the rest of this lib works off the\n// duck-typed TemporalLike shape (year/month/day/hour/...) instead of\n// `instanceof Temporal.X`, because instanceof just breaks across\n// polyfill/native boundaries — a polyfill's Temporal.PlainDate is a\n// completely different constructor from the native one, so\n// `value instanceof Temporal.PlainDate` would silently fail if the\n// caller's using a polyfill while the guard's looking at native\n// Temporal, or the other way around. same reasoning as tokens.ts's\n// intlSupportsNativeTemporal probe — identity checks just don't survive\n// a polyfill/native swap.\n//\n// so instead these guards check structural shape: does it have the\n// type-discriminating method each Temporal type carries. method\n// presence is part of the actual Temporal spec contract — every\n// implementation, native or polyfill, has to expose the same methods on\n// the same types — so it's a stable signal without needing to import a\n// Temporal namespace at all.\n//\n// per-type discriminators (double checked these against\n// @js-temporal/polyfill's actual prototype method list, matches spec):\n//\n// PlainDate — toPlainDateTime + withCalendar + year/month/day,\n// no hour. (PlainDateTime also has toPlainDateTime's\n// sibling toPlainDate/toPlainTime, but carries hour —\n// that's what distinguishes them.)\n// PlainTime — no toPlainDateTime, no withCalendar. has hour,\n// no year/month/day. (only Temporal date/time type\n// with neither withCalendar nor any toPlainX method.)\n// PlainDateTime — toPlainDate + withPlainTime + year/month/day\n// AND hour. (withPlainTime is unique — only\n// PlainDateTime and ZonedDateTime carry it;\n// ZonedDateTime also carries toInstant, which\n// PlainDateTime doesn't.)\n// ZonedDateTime — toInstant + withTimeZone. (both unique — only\n// ZonedDateTime carries withTimeZone.)\n// Instant — toZonedDateTimeISO, no toInstant. (Instant IS the\n// instant — toInstant belongs to ZonedDateTime.\n// toZonedDateTimeISO exists on both Instant and\n// ZonedDateTime per spec, but on ZonedDateTime it's\n// not actually exposed on the prototype in either\n// native or polyfill — only Instant has it as a real\n// method. checked both to confirm.)\n// PlainYearMonth — toPlainDate (takes a day arg) + year/month, no\n// day. (PlainDate also has a toPlainDate-shaped\n// method but carries day; PlainMonthDay also has\n// toPlainDate but carries day, not year.)\n// PlainMonthDay — toPlainDate + month/day, no year. also lacks\n// add/subtract/until/since (calendar arithmetic\n// doesn't really make sense on a month-day without\n// a year anyway).\n// Duration — total + abs + negated. (all three unique to\n// Duration, nothing else carries any of them.)\n\n// this shape intentionally mirrors TemporalLike over in tokens.ts, but\n// stays loose enough to also match real Temporal objects (which carry\n// the spec methods the field-only TemporalLike doesn't have)\ninterface TemporalInstance {\n toInstant?: () => unknown;\n toPlainDate?: (arg?: unknown) => unknown;\n toPlainDateTime?: (arg?: unknown) => unknown;\n toPlainTime?: () => unknown;\n toPlainYearMonth?: () => unknown;\n toPlainMonthDay?: () => unknown;\n toZonedDateTime?: (arg: unknown) => unknown;\n toZonedDateTimeISO?: (arg: unknown) => unknown;\n withCalendar?: (cal: unknown) => unknown;\n withPlainTime?: (t: unknown) => unknown;\n withTimeZone?: (z: unknown) => unknown;\n getTimeZoneTransition?: (opts: unknown) => unknown;\n startOfDay?: () => unknown;\n sign?: () => number;\n blank?: () => boolean;\n total?: (opts: unknown) => number;\n abs?: () => unknown;\n negated?: () => unknown;\n toString?: () => string;\n // these come from TemporalLike — present on all the date-carrying\n // Temporal types but absent on PlainTime (no calendar position there)\n year?: number;\n month?: number;\n day?: number;\n hour?: number;\n minute?: number;\n second?: number;\n calendarId?: string;\n timeZoneId?: string;\n // PlainMonthDay stores its month as monthCode (like \"M08\") instead of\n // a plain numeric month — without a year there's no way to know which\n // month a calendar-independent numeric month even refers to once\n // leap-year-aware calendars get involved, so the spec uses monthCode\n // instead. PlainMonthDay's the only type that has monthCode but not month\n monthCode?: string;\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null;\n}\n\n// hardening against hostile getters: the guards below read properties\n// (year, hour, Symbol.toStringTag, ...) off whatever value the caller\n// hands us. an object with a throwing getter used to turn isPlainDate(obj)\n// — a function whose entire contract is \"return a boolean\" — into an\n// exception factory instead. every exported guard now goes through this\n// wrapper, so a throw during probing just means \"not one of ours\", not a\n// crash. one shared catch here instead of one per guard also keeps the\n// coverage numbers honest\nfunction guardOrFalse<T>(impl: (value: unknown) => value is T): (value: unknown) => value is T {\n return (value: unknown): value is T => {\n try {\n return impl(value);\n } catch {\n return false;\n }\n };\n}\n\nfunction hasMethod<T extends keyof TemporalInstance>(\n v: TemporalInstance,\n name: T,\n): boolean {\n return typeof v[name] === 'function';\n}\n\n// Symbol.toStringTag is the spec-mandated brand for Temporal types —\n// every Temporal instance carries a tag like \"Temporal.PlainDate\" via\n// this symbol regardless of native vs polyfill. the per-type guards use\n// this as a fast positive check: a tag match is enough on its own, the\n// structural fallback (field presence + method checks) only kicks in\n// when there's no tag set, which can happen with hand-built mocks or\n// partial implementations\nfunction hasTag(value: unknown, typeName: string): boolean {\n if (!isObject(value)) return false;\n const tag = (value as { [Symbol.toStringTag]?: unknown })[Symbol.toStringTag];\n return tag === `Temporal.${typeName}`;\n}\n\nexport const isPlainDate: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainDateImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainDate')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n return typeof v.year === 'number'\n && typeof v.month === 'number'\n && typeof v.day === 'number'\n && typeof v.hour === 'undefined'\n && hasMethod(v, 'toPlainDateTime')\n && hasMethod(v, 'withCalendar');\n});\n\nexport const isPlainTime: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainTimeImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainTime')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // PlainTime is the only type with hour but no year, and neither\n // withCalendar nor any toPlainX method. that combo is unique among\n // all eight types\n return typeof v.hour === 'number'\n && typeof v.year === 'undefined'\n && !hasMethod(v, 'withCalendar')\n && !hasMethod(v, 'toPlainDate')\n && !hasMethod(v, 'toPlainDateTime');\n});\n\nexport const isPlainDateTime: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainDateTimeImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainDateTime')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // withPlainTime shows up on both PlainDateTime and ZonedDateTime, but\n // ZonedDateTime also has toInstant. so \"has withPlainTime, no\n // toInstant\" uniquely picks out PlainDateTime\n return typeof v.year === 'number'\n && typeof v.month === 'number'\n && typeof v.day === 'number'\n && typeof v.hour === 'number'\n && hasMethod(v, 'withPlainTime')\n && !hasMethod(v, 'toInstant');\n});\n\nexport const isZonedDateTime: (value: unknown) => value is TemporalInstance = guardOrFalse(function isZonedDateTimeImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'ZonedDateTime')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // withTimeZone is unique to ZonedDateTime, nothing else has it\n return typeof v.year === 'number'\n && typeof v.month === 'number'\n && typeof v.day === 'number'\n && typeof v.hour === 'number'\n && hasMethod(v, 'withTimeZone')\n && hasMethod(v, 'toInstant');\n});\n\nexport const isInstant: (value: unknown) => value is TemporalInstance = guardOrFalse(function isInstantImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'Instant')) return true;\n if (!isObject(value)) return false;\n // Instant has toZonedDateTimeISO but no toInstant — makes sense, it\n // IS the instant already. also has no year/month/day/hour fields since\n // those only mean anything against a calendar + zone, which Instant\n // alone doesn't carry\n const v = value as TemporalInstance;\n return hasMethod(v, 'toZonedDateTimeISO')\n && !hasMethod(v, 'toInstant')\n && typeof v.year === 'undefined';\n});\n\nexport const isPlainYearMonth: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainYearMonthImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainYearMonth')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // has year+month but no day, carries toPlainDate (used to attach a day\n // later). PlainMonthDay also has toPlainDate but doesn't have year\n return typeof v.year === 'number'\n && typeof v.month === 'number'\n && typeof v.day === 'undefined'\n && hasMethod(v, 'toPlainDate');\n});\n\nexport const isPlainMonthDay: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainMonthDayImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainMonthDay')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // PlainMonthDay has day and monthCode but no year and no numeric month.\n // monthCode's the discriminator here — every other Temporal type with\n // a month concept either has month (numeric, calendar-aware) or\n // doesn't have months at all (PlainTime, Duration)\n return typeof v.year === 'undefined'\n && typeof v.month === 'undefined'\n && typeof v.day === 'number'\n && typeof v.monthCode === 'string'\n && hasMethod(v, 'toPlainDate');\n});\n\nexport const isDuration: (value: unknown) => value is Record<string, unknown> = guardOrFalse(function isDurationImpl(value: unknown): value is Record<string, unknown> {\n if (hasTag(value, 'Duration')) return true;\n if (!isObject(value)) return false;\n // total is unique to Duration across the whole Temporal set — nothing\n // else has it (checked every prototype to confirm). abs and negated\n // are also Duration-only, checking any one of the three would work;\n // going with total since it's the most semantically distinctive one —\n // a Duration-specific operation nothing else would coincidentally need\n const v = value as TemporalInstance;\n return hasMethod(v, 'total');\n});\n\n// umbrella guard: is this ANY Temporal namespace member. used by\n// assertTemporal below for the \"this needs to be some Temporal thing\"\n// case. checks two signals in order:\n// 1. Symbol.toStringTag — every Temporal type brands itself as\n// Temporal.X via this symbol. spec-mandated, present on native\n// and polyfill instances alike.\n// 2. the discriminating-method fallback — covers whatever future or\n// partial Temporal implementation doesn't bother setting the tag.\n// method presence is part of the spec contract, so combined with\n// equals + with (both on every Temporal instance) it's still a\n// reliable signal even without the tag being set\nexport const isTemporal: (value: unknown) => value is TemporalInstance = guardOrFalse(function isTemporalImpl(value: unknown): value is TemporalInstance {\n if (!isObject(value)) return false;\n const tag = (value as { [Symbol.toStringTag]?: unknown })[Symbol.toStringTag];\n if (typeof tag === 'string' && tag.startsWith('Temporal.')) return true;\n const v = value as TemporalInstance;\n return hasMethod(v, 'toInstant')\n || hasMethod(v, 'toPlainDate')\n || hasMethod(v, 'toPlainDateTime')\n || hasMethod(v, 'toPlainTime')\n || hasMethod(v, 'toPlainYearMonth')\n || hasMethod(v, 'toPlainMonthDay')\n || hasMethod(v, 'toZonedDateTime')\n || hasMethod(v, 'toZonedDateTimeISO')\n || hasMethod(v, 'withCalendar')\n || hasMethod(v, 'withPlainTime')\n || hasMethod(v, 'withTimeZone')\n || hasMethod(v, 'total');\n});\n\n// assertion helpers — throw with a real message instead of just\n// returning false. same convention the rest of this lib uses: descriptive\n// thrown errors instead of failing silently. the thrown error includes\n// a valueType hint so the caller can actually see what they passed in\nfunction describeValue(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (typeof value === 'object') {\n const ctor = (value as { constructor?: { name?: string } }).constructor;\n if (ctor && typeof ctor.name === 'string' && ctor.name !== 'Object') {\n return `instance of ${ctor.name}`;\n }\n return 'plain object';\n }\n return typeof value;\n}\n\nfunction assertImpl(value: unknown, guard: (v: unknown) => boolean, expectedType: string): void {\n if (!guard(value)) {\n throw new Error(\n `temporal-fmt: expected a Temporal.${expectedType}, got ${describeValue(value)}.`\n );\n }\n}\n\nexport function assertTemporal(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isTemporal, 'object (Instant, PlainDate, PlainTime, PlainDateTime, ZonedDateTime, Duration, PlainYearMonth, or PlainMonthDay)');\n}\nexport function assertInstant(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isInstant, 'Instant');\n}\nexport function assertPlainDate(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainDate, 'PlainDate');\n}\nexport function assertPlainTime(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainTime, 'PlainTime');\n}\nexport function assertPlainDateTime(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainDateTime, 'PlainDateTime');\n}\nexport function assertZonedDateTime(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isZonedDateTime, 'ZonedDateTime');\n}\nexport function assertPlainYearMonth(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainYearMonth, 'PlainYearMonth');\n}\nexport function assertPlainMonthDay(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainMonthDay, 'PlainMonthDay');\n}\nexport function assertDuration(value: unknown): asserts value is Record<string, unknown> {\n assertImpl(value, isDuration, 'Duration');\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Per-token metadata: the structured descriptor this module\n// asks for (meaning, format-capable?, parse-capable?, locale-sensitive?,\n// calendar-sensitive?, timezone-sensitive?, supported Temporal types,\n// round-trip-safe?). One table, kept in sync with TOKENS in tokens.ts\n// by tests (see test/tokenMetadata.test.js — every entry in TOKENS has\n// a metadata entry, and vice versa).\n//\n// This is the single source of truth that analyzeFormat() (section E)\n// and the ESLint plugin / codemod consume — never read the\n// TOKENS array directly for metadata; use TOKEN_METADATA here, or the\n// tokenInfo() / listTokens() wrappers in analyze.ts.\n\nimport type { TemporalLike } from './tokens.js';\n\nexport type TemporalType =\n | 'Instant'\n | 'PlainDate'\n | 'PlainTime'\n | 'PlainDateTime'\n | 'ZonedDateTime'\n | 'PlainYearMonth'\n | 'PlainMonthDay';\n\nexport interface TokenMetadata {\n // Short human-readable description of what the token represents.\n meaning: string;\n // True if format() accepts this token. Every token in TOKENS is\n // format-capable by construction; this flag exists so the table is\n // self-describing for callers (the codemod) that work with token\n // families including format-only tokens from other libraries.\n formatCapable: boolean;\n // True if parse() accepts this token. False for `do`, `ww`, `RRRR`\n // — see FORMAT_ONLY_TOKENS in pattern.ts.\n parseCapable: boolean;\n // True if the output depends on locale (resolves via Intl or\n // custom vocab). MMMM/MMM/EEEE/EEE/a are true; everything else is\n // numeric ASCII and locale-independent.\n localeSensitive: boolean;\n // True if the output depends on the calendar (gregory, hebrew,\n // etc.). Locale-aware tokens inherit calendar sensitivity from\n // the Intl path (a hebrew PlainDate's month name depends on the\n // hebrew calendar). Year/month/day numeric tokens are calendar-\n // sensitive in principle (a Hebrew year/month renders differently\n // than a Gregorian one) but stay ISO-numeric on the format side\n // because tokens.ts reads straight off TemporalLike fields, which\n // are already calendar-specific by the time format() sees them.\n calendarSensitive: boolean;\n // True if the token requires a timeZoneId or offset field — i.e.\n // only ZonedDateTime supports it. zzz and the six offset tokens\n // (X/XX/XXX/x/xx/xxx) are timezone-sensitive.\n timezoneSensitive: boolean;\n // Which Temporal types can supply the field this token needs.\n // PlainTime can't supply year; PlainDate can't supply hour; only\n // ZonedDateTime carries timeZoneId/offset.\n supportedTypes: TemporalType[];\n // True if format(x, fmt) → parse(fmt, output) round-trips back to\n // a value equal to x. False when the format is fundamentally lossy:\n // `do` (ordinal suffix isn't structurally parseable), `ww`/`RRRR`\n // (week + weekday alone can't reconstruct a date without an extra\n // disambiguator), `yy` (two-digit year loses century — strptime\n // heuristic resolves it, but the heuristic isn't symmetric with\n // how `yy` formats BCE years, so round-trip only works for years\n // where 00-68/69-99 lands back on the same century).\n roundTripSafe: boolean;\n}\n\n// Helper: which Temporal types carry each field. Centralized here so\n// the supportedTypes arrays below stay short and the table is easy to\n// audit. Mirrors the field checks in tokens.ts (handler third tuple\n// element).\nconst TYPES_WITH: Record<string, TemporalType[]> = {\n year: ['PlainDate', 'PlainDateTime', 'ZonedDateTime', 'PlainYearMonth'],\n month: ['PlainDate', 'PlainDateTime', 'ZonedDateTime', 'PlainYearMonth', 'PlainMonthDay'],\n day: ['PlainDate', 'PlainDateTime', 'ZonedDateTime', 'PlainMonthDay'],\n // Instant deliberately NOT listed: Temporal.Instant exposes no\n // hour/minute/second/millisecond wall-clock fields (they're\n // zone-dependent), so format(instant, 'HH') throws at the field\n // check — the metadata used to claim Instant was supported, telling\n // analyzer/IDE consumers the opposite of what runtime does.\n hour: ['PlainTime', 'PlainDateTime', 'ZonedDateTime'],\n minute: ['PlainTime', 'PlainDateTime', 'ZonedDateTime'],\n second: ['PlainTime', 'PlainDateTime', 'ZonedDateTime'],\n millisecond: ['PlainTime', 'PlainDateTime', 'ZonedDateTime'],\n dayOfWeek: ['PlainDate', 'PlainDateTime', 'ZonedDateTime'],\n timeZoneId: ['ZonedDateTime'],\n offset: ['ZonedDateTime'],\n};\n\n// Every token in TOKENS gets an entry here. Adding a token to TOKENS\n// without adding one here makes test/tokenMetadata.test.js fail.\nexport const TOKEN_METADATA: Record<string, TokenMetadata> = {\n yyyy: {\n meaning: 'Four-digit year (preserves sign for BCE; no truncation).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: true,\n },\n yy: {\n meaning: 'Two-digit year (year % 100). Throws on negative years.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: false,\n },\n y: {\n meaning: 'Unpadded year, any width (preserves sign for BCE; no truncation, no minimum digits). Cannot sit directly next to another digit-reading token or a literal starting with a digit — there would be no way to tell where it ends.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: true,\n },\n MMMM: {\n meaning: 'Long month name (locale-aware, e.g. \"January\", \"janvier\").',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n MMM: {\n meaning: 'Short month name (locale-aware, e.g. \"Jan\", \"janv.\").',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n MM: {\n meaning: 'Two-digit month (01-12, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n M: {\n meaning: 'One- or two-digit month (1-12, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n dd: {\n meaning: 'Two-digit day-of-month (01-31, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day, roundTripSafe: true,\n },\n d: {\n meaning: 'One- or two-digit day-of-month (1-31, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day, roundTripSafe: true,\n },\n EEEE: {\n meaning: 'Long weekday name (locale-aware, e.g. \"Monday\", \"lundi\"). Parse cross-checks against the parsed date.',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: true,\n },\n EEE: {\n meaning: 'Short weekday name (locale-aware, e.g. \"Mon\", \"lun.\"). Parse cross-checks against the parsed date.',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: true,\n },\n HH: {\n meaning: 'Two-digit hour, 24-hour clock (00-23, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n H: {\n meaning: 'One- or two-digit hour, 24-hour clock (0-23, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n hh: {\n meaning: 'Two-digit hour, 12-hour clock (01-12, zero-padded). Requires `a` token on parse.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n h: {\n meaning: 'One- or two-digit hour, 12-hour clock (1-12, no padding). Requires `a` token on parse.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n mm: {\n meaning: 'Two-digit minute (00-59, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.minute, roundTripSafe: true,\n },\n m: {\n meaning: 'One- or two-digit minute (0-59, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.minute, roundTripSafe: true,\n },\n ss: {\n meaning: 'Two-digit second (00-59, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.second, roundTripSafe: true,\n },\n s: {\n meaning: 'One- or two-digit second (0-59, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.second, roundTripSafe: true,\n },\n S: {\n meaning: 'Fractional second, 1 digit (tenths of a second).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SS: {\n meaning: 'Fractional second, 2 digits (hundredths of a second).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSS: {\n meaning: 'Fractional second, 3 digits (milliseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSS: {\n meaning: 'Fractional second, 4 digits (tens of microseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSS: {\n meaning: 'Fractional second, 5 digits (hundred-thousandths of a second).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSSS: {\n meaning: 'Fractional second, 6 digits (microseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSSSS: {\n meaning: 'Fractional second, 7 digits (tens of nanoseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSSSSS: {\n meaning: 'Fractional second, 8 digits (hundred-millionths of a second).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSSSSSS: {\n meaning: 'Fractional second, 9 digits (nanoseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n a: {\n meaning: 'Day period (locale-aware: \"AM\"/\"PM\", \"午前\"/\"午後\", etc.). Required alongside 12-hour tokens on parse.',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n zzz: {\n meaning: 'IANA time zone id (e.g. \"America/New_York\") or fixed offset (\"+05:30\"). Requires full date+time on parse.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.timeZoneId, roundTripSafe: true,\n },\n X: {\n meaning: 'Numeric UTC offset, short (Z for UTC, ±HH[MM] otherwise). Minutes omitted when zero.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n XX: {\n meaning: 'Numeric UTC offset, no colon (Z for UTC, ±HHMM otherwise).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n XXX: {\n meaning: 'Numeric UTC offset, with colon (Z for UTC, ±HH:MM otherwise).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n x: {\n meaning: 'Numeric UTC offset, short, never Z (always ±HH[MM]). Lowercase variant of X.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n xx: {\n meaning: 'Numeric UTC offset, no colon, never Z (always ±HHMM). Lowercase variant of XX.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n xxx: {\n meaning: 'Numeric UTC offset, with colon, never Z (always ±HH:MM). Lowercase variant of XXX.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n do: {\n meaning: 'Ordinal day-of-month with English suffix (\"1st\", \"2nd\", \"3rd\", \"4th\", ... 21st, 22nd, ...). Format-only — not parseable.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day, roundTripSafe: false,\n },\n Q: {\n meaning: 'Quarter as a digit (1-4). Derived from month.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n QQQ: {\n meaning: 'Quarter with \"Q\" prefix (\"Q1\"..\"Q4\"). Derived from month.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n ww: {\n meaning: 'ISO 8601 week number (01-53). Format-only — week alone can\\'t reconstruct a date.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: false,\n },\n RRRR: {\n meaning: 'ISO 8601 week-numbering year (4-digit, may differ from calendar year at year boundaries). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: false,\n },\n // Day-of-year is leap-adjusted, so it needs a YEAR — PlainMonthDay\n // (month+day with no year) used to be listed as supported here while\n // format() computed a non-leap day-of-year for it.\n D: {\n meaning: 'Day of year, unpadded (1-366). Format-only — parsing requires resolving against a year.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day.filter((t) => t !== 'PlainMonthDay'), roundTripSafe: false,\n },\n DD: {\n meaning: 'Day of year, 2-digit minimum (01-366). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day.filter((t) => t !== 'PlainMonthDay'), roundTripSafe: false,\n },\n DDD: {\n meaning: 'Day of year, 3-digit zero-padded (001-366). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day.filter((t) => t !== 'PlainMonthDay'), roundTripSafe: false,\n },\n LLLL: {\n meaning: 'Stand-alone long month name (nominative case in Slavic locales). Identical to MMMM in most locales.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n LLL: {\n meaning: 'Stand-alone short month name. Identical to MMM in most locales.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n cccc: {\n meaning: 'Stand-alone long weekday name. Identical to EEEE in most locales.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: true,\n },\n ccc: {\n meaning: 'Stand-alone short weekday name. Identical to EEE in most locales.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: true,\n },\n GGGG: {\n meaning: 'Long era name (locale-aware, e.g. \"Anno Domini\"/\"Before Christ\"). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: false,\n },\n G: {\n meaning: 'Short era name (locale-aware, e.g. \"AD\"/\"BC\"). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: false,\n },\n zzzz: {\n meaning: 'Localized long timezone name (e.g. \"Eastern Standard Time\"). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.timeZoneId, roundTripSafe: false,\n },\n z: {\n meaning: 'Localized short timezone name (e.g. \"EST\"). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.timeZoneId, roundTripSafe: false,\n },\n\n};\n\nexport const ALL_TOKEN_NAMES: string[] = Object.keys(TOKEN_METADATA);","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Format-string analysis and introspection. Single source of truth for\n// \"what does this format string need / accept / produce\" — consumed by\n// the ESLint plugin and the codemod\n// so they don't each carry their own token table that drifts out of\n// sync with the runtime. Everything here reads from TOKENS in\n// tokens.ts and TOKEN_METADATA in tokenMetadata.ts, so adding a token\n// to those two tables automatically makes it visible to analyze()\n// without touching this file.\n\nimport { TOKENS, type TemporalLike } from './tokens.js';\nimport { TOKEN_METADATA, type TokenMetadata, type TemporalType } from './tokenMetadata.js';\nimport { tokenize, tokenizeWithSpans, type Piece } from './tokenize.js';\nimport { _handlerFor } from './format.js';\nimport { UNPADDED_NUMERIC_TOKENS, FORMAT_ONLY_TOKENS } from './pattern.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\n\n// Re-exported so callers can import everything analyzer-related from a\n// single entry point — analyze.ts is the introspection surface.\nexport type { TokenMetadata, TemporalType } from './tokenMetadata.js';\nexport type { Piece } from './tokenize.js';\n\n// tokenizeFormat is the same tokenize() the runtime uses, exposed\n// under a name that signals \"this is the introspection entry point.\"\n// Same implementation, different name — callers reading analyze.ts\n// see a coherent API surface rather than having to know that the\n// runtime tokenizer is the right thing to call.\nexport function tokenizeFormat(formatStr: string): Piece[] {\n return tokenize(formatStr);\n}\n\n// listTokens: every token the runtime recognizes, with metadata. Used\n// by IDE autocomplete data (section AC) and the codemod's \"can this\n// source-library token be translated?\" lookup (section Z).\nexport function listTokens(): Array<{ name: string; metadata: TokenMetadata }> {\n return TOKENS.map(([name]) => ({ name, metadata: TOKEN_METADATA[name]! }));\n}\n\n// tokenInfo: one token's metadata. Returns undefined for unknown\n// tokens rather than throwing — callers (autocomplete, hover docs)\n// want a sentinel, not an exception, when a user types a partial token.\nexport function tokenInfo(name: string): TokenMetadata | undefined {\n return TOKEN_METADATA[name];\n}\n\nexport interface AnalyzedToken {\n name: string;\n // Position in the format string, 0-indexed. Useful for IDE diagnostics\n // that highlight a specific token.\n position: number;\n metadata: TokenMetadata;\n}\n\nexport interface FormatAnalysis {\n // Every token in the format string, in order, with metadata.\n tokens: AnalyzedToken[];\n // Fields (year/month/day/hour/...) any token in this format string\n // reads off the input. Lets a caller statically check \"does this\n // format string need a field PlainDate doesn't have?\"\n requiredFields: string[];\n // Temporal types that can supply every required field. The intersection\n // across all tokens — a format string with both `yyyy` (needs year)\n // and `HH` (needs hour) is compatible only with types carrying both,\n // i.e. PlainDateTime/ZonedDateTime.\n compatibleTypes: TemporalType[];\n // Can parse() accept this format string? False when any token is\n // format-only (do/ww/RRRR per FORMAT_ONLY_TOKENS in pattern.ts).\n parseable: boolean;\n // Does the format string contain any locale-aware token (MMMM/MMM/\n // EEEE/EEE/a)? True means the output depends on the locale option\n // and a registered custom vocab can override the result.\n localeSensitive: boolean;\n // Does the format string contain any calendar-sensitive token?\n // Almost every date/weekday token is, since its output depends on\n // the object's calendar (a hebrew PlainDate's \"MMMM\" is a hebrew\n // month name). Pure-time tokens (HH/mm/ss) are not.\n calendarSensitive: boolean;\n // Does the format string contain zzz or any offset token? If yes,\n // only ZonedDateTime can supply the field.\n timezoneSensitive: boolean;\n // Does the format string contain a run of 2+ adjacent unpadded\n // numeric tokens with no literal between them (Md, dM, Hms, ...)?\n // Such runs can be ambiguous at parse time — strict mode throws,\n // lenient mode picks one split via the documented heuristic.\n ambiguous: boolean;\n // Does format(x, fmt) → parse(fmt, output) round-trip? False when\n // any token is format-only OR when yy is used (century loss).\n roundTripSafe: boolean;\n // Non-fatal issues found during analysis. Each carries a `code`\n // the IDE plugin / CLI can switch on. Empty for clean format strings.\n warnings: Array<{ code: string; message: string }>;\n}\n\nexport function analyzeFormat(formatStr: string): FormatAnalysis {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(\n `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`\n );\n }\n const pieces = tokenizeWithSpans(formatStr);\n const tokens: AnalyzedToken[] = [];\n const requiredFields = new Set<string>();\n const compatibleTypesSet = new Set<TemporalType>();\n let parseable = true;\n let localeSensitive = false;\n let calendarSensitive = false;\n let timezoneSensitive = false;\n let roundTripSafe = true;\n const warnings: Array<{ code: string; message: string }> = [];\n\n // Walk pieces, building up the analysis. Each token's `position` is\n // its exact source index in the ORIGINAL format string (from\n // tokenizeWithSpans) — decoded literal lengths used to be accumulated\n // instead, which under-counted every quoted span ('a b' is 5 source\n // chars, 3 decoded; '' is 2 source chars, 1 decoded), so every token\n // after any quote escape reported a position that was too small.\n const unpaddedRun: string[] = [];\n const flushRun = () => {\n if (unpaddedRun.length >= 2) {\n warnings.push({\n code: 'AMBIGUOUS_NUMERIC_RUN',\n message: `Adjacent unpadded numeric tokens \"${unpaddedRun.join('')}\" with no separator can be ambiguous to parse. Add a separator or use the padded form (e.g. \"MM\" instead of \"M\").`,\n });\n }\n unpaddedRun.length = 0;\n };\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n flushRun();\n continue;\n }\n const metadata = TOKEN_METADATA[piece.value];\n // Dead by construction, confirmed via listTokens(): every token in\n // TOKENS has a matching TOKEN_METADATA entry (51/51), and tokenize()\n // already throws on any string that isn't in TOKENS before this loop\n // ever runs. Kept as a guard against the two tables drifting apart.\n /* c8 ignore start */\n if (!metadata) {\n warnings.push({\n code: 'UNKNOWN_TOKEN_NO_METADATA',\n message: `Token \"${piece.value}\" is recognized by the tokenizer but has no metadata entry in tokenMetadata.ts — this is a bug in temporal-fmt.`,\n });\n continue;\n }\n /* c8 ignore stop */\n tokens.push({ name: piece.value, position: piece.start, metadata });\n\n // Required fields: read off the handler map (the source of truth\n // for \"what field does this token need\"). Falls back to the\n // metadata's supportedTypes-derived field set if the handler isn't\n // found, which also shouldn't happen.\n const handler = _handlerFor(piece.value);\n if (handler) {\n requiredFields.add(handler.field as string);\n }\n\n // compatibleTypes: intersect every token's supportedTypes. The\n // first token seeds the set; subsequent tokens narrow it.\n if (tokens.length === 1) {\n for (const t of metadata.supportedTypes) compatibleTypesSet.add(t);\n } else {\n const stillCompatible = new Set<TemporalType>();\n for (const t of compatibleTypesSet) {\n if (metadata.supportedTypes.includes(t)) stillCompatible.add(t);\n }\n compatibleTypesSet.clear();\n for (const t of stillCompatible) compatibleTypesSet.add(t);\n }\n\n if (!metadata.parseCapable) {\n parseable = false;\n warnings.push({\n code: 'FORMAT_ONLY_TOKEN',\n message: `Token \"${piece.value}\" is format-only — it can't be parsed back into a value. Use a parse-capable variant (e.g. \"d\" instead of \"do\") if you need round-trip.`,\n });\n }\n if (metadata.localeSensitive) localeSensitive = true;\n if (metadata.calendarSensitive) calendarSensitive = true;\n if (metadata.timezoneSensitive) timezoneSensitive = true;\n if (!metadata.roundTripSafe) roundTripSafe = false;\n\n // Track runs of adjacent unpadded numeric tokens — same definition\n // as parsePattern.ts uses (UNPADDED_NUMERIC_TOKENS). A literal\n // between tokens breaks the run; this is checked by the flushRun\n // call above.\n if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {\n unpaddedRun.push(piece.value);\n } else {\n flushRun();\n }\n }\n flushRun();\n\n // Cross-token checks the runtime parse() performs. Mirroring them\n // here lets the ESLint plugin flag them statically without having\n // to re-derive the logic.\n const tokenNames = tokens.map((t) => t.name);\n const has12Hour = tokenNames.some((t) => t === 'hh' || t === 'h');\n const has24Hour = tokenNames.some((t) => t === 'HH' || t === 'H');\n const hasAPeriod = tokenNames.some((t) => t === 'a');\n if (has12Hour && !hasAPeriod) {\n warnings.push({\n code: 'TWELVE_HOUR_WITHOUT_A',\n message: '12-hour token (\"hh\"/\"h\") used without an \"a\" (AM/PM) token — parse() can\\'t tell AM from PM and throws at runtime.',\n });\n }\n if (has12Hour && has24Hour) {\n warnings.push({\n code: 'MIXED_12_AND_24_HOUR',\n message: 'Mixing 24-hour and 12-hour tokens — parse() refuses to guess which is authoritative and throws at runtime.',\n });\n }\n\n const hasOffset = tokenNames.some((t) => t === 'X' || t === 'XX' || t === 'XXX' || t === 'x' || t === 'xx' || t === 'xxx');\n const hasZzz = tokenNames.some((t) => t === 'zzz');\n if (hasOffset && hasZzz) {\n warnings.push({\n code: 'ZZZ_WITH_OFFSET_TOKEN',\n message: 'Format string has both \"zzz\" and an offset token — parse() cross-checks them and throws if the parsed offset disagrees with the zone\\'s actual offset.',\n });\n }\n if (hasOffset && !requiredFields.has('year')) {\n warnings.push({\n code: 'OFFSET_WITHOUT_FULL_DATE',\n message: 'Offset token used without a full date — parse() needs a complete date and time to build a ZonedDateTime and throws at runtime otherwise.',\n });\n }\n\n return {\n tokens,\n requiredFields: [...requiredFields].sort(),\n compatibleTypes: [...compatibleTypesSet].sort(),\n parseable,\n localeSensitive,\n calendarSensitive,\n timezoneSensitive,\n // Ambiguous iff at least one warning fired about an ambiguous run.\n ambiguous: warnings.some((w) => w.code === 'AMBIGUOUS_NUMERIC_RUN'),\n roundTripSafe: roundTripSafe && parseable,\n warnings,\n };\n}\n\n// explainFormat: human-readable rendering of analyzeFormat's output.\n// Used by the CLI (section AD) for `temporal-fmt inspect <fmt>` and by\n// the IDE for hover docs on a format string. Plain prose, no JSON —\n// callers wanting machine-readable output should call analyzeFormat()\n// directly.\nexport function explainFormat(formatStr: string): string {\n const analysis = analyzeFormat(formatStr);\n const lines: string[] = [];\n lines.push(`Format string: \"${formatStr}\"`);\n lines.push(`Tokens (${analysis.tokens.length}):`);\n for (const t of analysis.tokens) {\n lines.push(` ${t.name} @${t.position} — ${t.metadata.meaning}`);\n }\n if (analysis.requiredFields.length > 0) {\n lines.push(`Required fields: ${analysis.requiredFields.join(', ')}`);\n }\n if (analysis.compatibleTypes.length > 0) {\n lines.push(`Compatible Temporal types: ${analysis.compatibleTypes.join(', ')}`);\n }\n lines.push(`Parseable: ${analysis.parseable ? 'yes' : 'no'}`);\n lines.push(`Locale-sensitive: ${analysis.localeSensitive ? 'yes' : 'no'}`);\n lines.push(`Calendar-sensitive: ${analysis.calendarSensitive ? 'yes' : 'no'}`);\n lines.push(`Timezone-sensitive: ${analysis.timezoneSensitive ? 'yes' : 'no'}`);\n lines.push(`Ambiguous: ${analysis.ambiguous ? 'yes' : 'no'}`);\n lines.push(`Round-trip safe: ${analysis.roundTripSafe ? 'yes' : 'no'}`);\n if (analysis.warnings.length > 0) {\n lines.push('Warnings:');\n for (const w of analysis.warnings) {\n lines.push(` [${w.code}] ${w.message}`);\n }\n }\n return lines.join('\\n');\n}\n\n// isValidFormat: true iff tokenize() accepts the string without\n// throwing. Distinct from analyzeFormat's `parseable` flag — a format\n// string can be valid (tokenizes cleanly) but not parseable (contains\n// a format-only token like `do`). Both checks are exposed since callers\n// want different things: validity for \"will format() throw\", parseability\n// for \"will parse() throw\".\nexport function isValidFormat(formatStr: string): boolean {\n if (formatStr.length > MAX_FORMAT_LENGTH) return false;\n try {\n tokenize(formatStr);\n return true;\n } catch {\n return false;\n }\n}\n\n// validateFormat: throws on invalid format strings instead of\n// returning a boolean. Mirrors the existing strict-validation\n// convention (descriptive thrown errors, never silent failures).\n// Returns the analysis for callers who want both — validate-then-use.\nexport function validateFormat(formatStr: string): FormatAnalysis {\n const analysis = analyzeFormat(formatStr);\n return analysis;\n}\n\n// Exported for callers that want to query the token table without\n// touching internals. Kept here rather than re-exported from\n// tokenMetadata.ts so this module is the single import for \"anything\n// analyzer-related.\"\nexport { TOKEN_METADATA, ALL_TOKEN_NAMES } from './tokenMetadata.js';\n\n// Re-export FORMAT_ONLY_TOKENS so callers don't have to import from\n// pattern.ts (which is a lower-level module they shouldn't need to\n// know about).\nexport { FORMAT_ONLY_TOKENS } from './pattern.js';\n\n// Used by callers that need to look up which field a token requires —\n// e.g. the ESLint plugin's \"type mismatch\" check (section Y) wants to\n// answer \"does the type the caller passed to format() carry this\n// field?\" without having to actually call format() and catch the\n// thrown error. Mirrors the same lookup format.ts does internally.\nexport function fieldForToken(token: string): keyof TemporalLike | undefined {\n return _handlerFor(token)?.field;\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Serialization / interop helpers. Standardized\n// parse/format pairs for ISO 8601, RFC 3339, RFC 2822, HTTP-date,\n// plus epoch conversions to/from unix seconds/ms/µs/ns.\n//\n// All of these wrap the existing parse()/format() surface rather than\n// reimplementing the formats — same convention as the rest of the\n// library (one tokenizer, one parser, one constructor path). The\n// standard-format helpers are essentially pre-baked format strings\n// with the right tokens, plus stricter input validation where the\n// standard demands it (e.g. RFC 3339 requires UTC-offset-only zones,\n// not named IANA zones).\n\nimport { parse } from './parse.js';\nimport { format } from './format.js';\nimport { getTemporal, type TemporalNamespace } from './temporalProvider.js';\nimport { FormatSyntaxError, InvalidDateError } from './errors.js';\n\n// Build a Temporal instance from a field bag. Used by the parse helpers\n// to construct PlainDate / PlainDateTime / ZonedDateTime / Instant from\n// the fields the standard format carries. Throws on construction errors\n// (Feb 30, etc.) wrapped in InvalidDateError so callers get the typed\n// error surface.\nfunction constructFromFields(fields: Record<string, unknown>, kind: 'PlainDate' | 'PlainDateTime' | 'ZonedDateTime' | 'Instant'): unknown {\n const temporal = getTemporal();\n try {\n switch (kind) {\n case 'PlainDate':\n return temporal.PlainDate.from(fields as Record<string, number | string | undefined>, { overflow: 'reject' });\n case 'PlainDateTime':\n return temporal.PlainDateTime.from(fields as Record<string, number | string | undefined>, { overflow: 'reject' });\n case 'ZonedDateTime':\n return temporal.ZonedDateTime.from(fields as Record<string, number | string | undefined>, { overflow: 'reject' });\n case 'Instant': {\n // Instant.from takes an ISO string, not a field bag. Build the\n // ISO string ourselves and parse it.\n const iso = buildISOFromFields(fields);\n if (!temporal.Instant) {\n throw new Error('temporal-fmt: Temporal.Instant is not available in this implementation.');\n }\n return temporal.Instant.from(iso);\n }\n }\n } catch (err) {\n throw new InvalidDateError({ input: JSON.stringify(fields), reason: (err as Error).message });\n }\n}\n\nfunction buildISOFromFields(fields: Record<string, unknown>): string {\n const y = String(fields.year).padStart(4, '0');\n const m = String(fields.month).padStart(2, '0');\n const d = String(fields.day).padStart(2, '0');\n const h = fields.hour !== undefined ? `T${String(fields.hour).padStart(2, '0')}` : '';\n const min = fields.minute !== undefined ? `:${String(fields.minute).padStart(2, '0')}` : '';\n const sec = fields.second !== undefined ? `:${String(fields.second).padStart(2, '0')}` : '';\n const frac = fields.millisecond !== undefined && (fields.millisecond as number) > 0\n ? `.${String(fields.millisecond).padStart(3, '0')}`\n : '';\n const tz = typeof fields.timeZone === 'string' ? fields.timeZone : 'Z';\n return `${y}-${m}-${d}${h}${min}${sec}${frac}${tz}`;\n}\n\n// ISO 8601 is the most permissive of the standards here — accepts\n// calendar dates, week dates, ordinal dates, times with optional\n// fractional seconds, timezone offsets or 'Z'. Delegates to\n// Temporal's own ISO parsing (which is ISO 8601-compliant) by\n// constructing from the raw ISO string.\n\nexport function parseISO(input: string): unknown {\n const temporal = getTemporal();\n // Detect what kind of Temporal object the ISO string describes.\n // ISO 8601 strings have a date part, optional time part, optional\n // timezone. We dispatch to the right Temporal constructor based on\n // which parts are present.\n try {\n if (/^\\d{4}-\\d{2}-\\d{2}T/.test(input) || /T\\d{2}:\\d{2}/.test(input)) {\n // Has a time component.\n if (/[zZ]$/.test(input) || /[+-]\\d{2}:?\\d{2}$/.test(input)) {\n // ZonedDateTime. Temporal.ZonedDateTime.from accepts ISO with\n // a zone bracket (e.g. \"2026-08-04T15:45:30[UTC]\") but rejects\n // a bare offset with no bracket. For \"Z\" suffix, expand to\n // \"+00:00[UTC]\"; for a numeric offset, append that same offset\n // as the bracket (e.g. \"+05:30\" → \"+05:30[+05:30]\").\n let iso = input;\n if (/[zZ]$/.test(iso)) {\n iso = iso.slice(0, -1) + '+00:00[UTC]';\n } else {\n const offsetMatch = /([+-]\\d{2}:?\\d{2})$/.exec(iso);\n if (offsetMatch) {\n iso = `${iso}[${offsetMatch[1]}]`;\n }\n }\n return temporal.ZonedDateTime.from(iso as unknown as Record<string, number | string | undefined>, { overflow: 'reject' });\n }\n return temporal.PlainDateTime.from(input as unknown as Record<string, number | string | undefined>, { overflow: 'reject' });\n }\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(input)) {\n return temporal.PlainDate.from(input as unknown as Record<string, number | string | undefined>, { overflow: 'reject' });\n }\n if (/^\\d{2}:\\d{2}/.test(input)) {\n return temporal.PlainTime.from(input as unknown as Record<string, number | string | undefined>);\n }\n throw new Error(`temporal-fmt: parseISO(\"${input}\") doesn't look like an ISO 8601 string.`);\n } catch (err) {\n throw new InvalidDateError({ input, reason: (err as Error).message });\n }\n}\n\nexport function formatISO(value: unknown): string {\n // Temporal objects expose toString() which produces ISO 8601 output\n // by spec. So formatting IS just toString().\n const v = value as { toString?: () => string };\n if (typeof v?.toString !== 'function') {\n throw new FormatSyntaxError({ reason: `formatISO() expects a Temporal value with toString(), got ${typeof value}.` });\n }\n return v.toString();\n}\n\n// RFC 3339 is a profile of ISO 8601 used in network protocols (HTTP,\n// JSON-RPC, etc.). Stricter than ISO 8601: requires full date+time,\n// requires seconds, requires UTC offset or 'Z', disallows IANA zone\n// names. Delegates to parseISO then validates the constraints.\n\nexport function parseRFC3339(input: string): unknown {\n // RFC 3339 grammar (https://www.rfc-editor.org/rfc/rfc3339#section-5.6):\n // date-fullyear = 4DIGIT\n // date-month = 2DIGIT ; 01-12\n // date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31\n // time-hour = 2DIGIT ; 00-23\n // time-minute = 2DIGIT ; 00-59\n // time-second = 2DIGIT ; 00-58, 00-59, 00-60 (leap second)\n // time-secfrac = \".\" 1*DIGIT\n // time-numoffset = (\"+\" / \"-\") time-hour \":\" time-minute\n // time-offset = \"Z\" / time-numoffset\n // partial-time = time-hour \":\" time-minute \":\" time-second [time-secfrac]\n // full-date = date-fullyear \"-\" date-month \"-\" date-mday\n // full-time = partial-time time-offset\n // date-time = full-date \"T\" full-time\n const re = /^(\\d{4})-(\\d{2})-(\\d{2})[Tt](\\d{2}):(\\d{2}):(\\d{2})(\\.\\d+)?([Zz]|[+-]\\d{2}:\\d{2})$/;\n const m = re.exec(input);\n if (!m) {\n throw new FormatSyntaxError({ input, reason: 'does not match RFC 3339 date-time grammar' });\n }\n // Construct via parseISO with the same expansion for bare Z.\n const iso = input.replace(/[tT]/, 'T').replace(/[zZ]$/, '+00:00[UTC]');\n return parseISO(iso);\n}\n\nexport function formatRFC3339(value: unknown): string {\n // RFC 3339 output is ISO 8601 with a UTC offset. toString() on a\n // ZonedDateTime produces this shape; we just verify the result looks\n // like RFC 3339 and pass it through.\n const s = formatISO(value);\n if (!/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$/.test(s)) {\n throw new FormatSyntaxError({ input: s, reason: 'value did not produce RFC 3339-compliant output' });\n }\n return s;\n}\n\n// RFC 2822 date-time (used in email Message-ID headers, etc.). Format:\n// day-of-week, day month year hour:minute:second zone\n// e.g. \"Mon, 04 Aug 2026 15:45:30 +0000\"\n// JS Date can parse this natively, so we use Date.parse and convert\n// to a Temporal.Instant. (Date.parse's RFC 2822 support is universal\n// across engines, unlike its ISO 8601 support which varies.)\n\nexport function parseRFC2822(input: string): unknown {\n // Strict shape pre-check: Date.parse is far more permissive than RFC 2822\n // (it happily accepts ISO 8601 and other dialects), so without this gate\n // parseRFC2822(\"2026-08-04\") would succeed despite not being an RFC 2822\n // date at all. The regex mirrors RFC 2822 §3.3's date-time grammar:\n // optional day-of-week, 1-2 digit day, month name, 2-4 digit year (the\n // obsolete two-digit form included), time with optional seconds, and a\n // zone that is either a numeric ±HHMM offset or an alphabetic zone name.\n const RFC2822_SHAPE =\n /^(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s+)?\\d{1,2}\\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+\\d{2,4}\\s+\\d{2}:\\d{2}(?::\\d{2})?\\s+(?:[+-]\\d{4}|[A-Za-z]{1,5})$/;\n if (!RFC2822_SHAPE.test(input.trim())) {\n throw new FormatSyntaxError({ input, reason: 'not a valid RFC 2822 date' });\n }\n const ms = Date.parse(input);\n if (Number.isNaN(ms)) {\n throw new FormatSyntaxError({ input, reason: 'not a valid RFC 2822 date' });\n }\n return requireInstant().fromEpochMilliseconds(ms);\n}\n\nexport function formatRFC2822(value: unknown): string {\n // Format using format() with the right tokens, then construct via\n // the value's epoch ms. RFC 2822 requires a fixed offset, not an\n // IANA zone, so we read the value's offset directly.\n const v = value as { toEpochMilliseconds?: () => number; epochMilliseconds?: number; toInstant?: () => { epochMilliseconds: number } };\n let ms: number | undefined;\n if (typeof v?.toEpochMilliseconds === 'function') {\n ms = v.toEpochMilliseconds();\n } else if (typeof v?.epochMilliseconds === 'number') {\n // Temporal.Instant exposes epochMilliseconds as a property.\n ms = v.epochMilliseconds;\n } else if (typeof v?.toInstant === 'function') {\n // ZonedDateTime.toInstant() → Instant.\n const inst = v.toInstant();\n if (typeof (inst as { epochMilliseconds?: number }).epochMilliseconds === 'number') {\n ms = (inst as { epochMilliseconds: number }).epochMilliseconds;\n }\n }\n if (ms === undefined) {\n throw new FormatSyntaxError({ reason: `formatRFC2822() expects a value with epochMilliseconds, toEpochMilliseconds(), or toInstant(), got ${typeof value}.` });\n }\n return formatRFC2822FromMs(ms);\n}\n\nfunction formatRFC2822FromMs(ms: number): string {\n // Use Intl.DateTimeFormat with the en-US POSIX locale and the rfc822\n // format option. Modern Node ships Intl with this option; if not\n // available, fall back to manual formatting.\n try {\n const fmt = new Intl.DateTimeFormat('en-US', {\n weekday: 'short', day: '2-digit', month: 'short', year: 'numeric',\n hour: '2-digit', minute: '2-digit', second: '2-digit',\n timeZone: 'UTC', timeZoneName: 'shortOffset',\n hour12: false,\n });\n const parts = fmt.formatToParts(new Date(ms));\n /* c8 ignore start -- every part type get() is called with (weekday,\n day, month, year, hour, minute, second, timeZoneName) is always\n present given the fixed options above, so the ?? '' fallback\n can't fire without a different Intl implementation. */\n const get = (t: string) => parts.find((p) => p.type === t)?.value ?? '';\n /* c8 ignore stop */\n const tzRaw = get('timeZoneName');\n // Intl's shortOffset returns \"GMT+0\", \"GMT-8\", \"GMT+5:30\", etc.\n // RFC 2822 wants \"+0000\", \"-0800\", \"+0530\". Parse and reformat.\n const tzMatch = tzRaw?.match(/GMT([+-])(\\d+)(?::(\\d+))?/);\n let tz: string;\n if (tzMatch) {\n const sign = tzMatch[1]!;\n const hours = tzMatch[2]!.padStart(2, '0');\n const minutes = (tzMatch[3] ?? '0').padStart(2, '0');\n tz = `${sign}${hours}${minutes}`;\n /* c8 ignore start @preserve -- timeZone is hardcoded to 'UTC' above,\n which always resolves cleanly, so shortOffset always returns a\n parseable \"GMT+0\"-shaped string in this environment's ICU. This\n branch only guards against an ICU build whose shortOffset output\n doesn't match the regex; can't trigger it without mocking Intl.\n The ignore starts before the closing brace of the if-block so it\n covers the whole else-branch node c8 tracks as a single unit. */\n } else {\n tz = '+0000';\n }\n /* c8 ignore stop @preserve */\n let hour = get('hour');\n /* c8 ignore start @preserve -- hour12:false with a fixed UTC zone\n never yields \"24\" in this environment's ICU (midnight formats as\n \"00\"). Some ICU versions/locales are documented to emit \"24\" for\n hour12:false, so this stays as a defensive normalization; not\n reachable here without mocking Intl.DateTimeFormat's output. */\n if (hour === '24') hour = '00';\n /* c8 ignore stop @preserve */\n return `${get('weekday')}, ${get('day')} ${get('month')} ${get('year')} ${hour}:${get('minute')}:${get('second')} ${tz}`;\n /* c8 ignore start @preserve -- Intl.DateTimeFormat is constructed\n above with a literal, always-valid timeZone: 'UTC' and no other\n user input reaches the constructor or formatToParts call, so this\n catch can't be triggered through the public API in a normal Intl\n environment (e.g. Node with full-icu). Kept as a genuine fallback\n for runtimes with a broken or absent Intl implementation. */\n } catch {\n // Fallback: hand-rolled RFC 2822 format via Date's UTC methods.\n const d = new Date(ms);\n const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\n const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n const wd = days[d.getUTCDay()];\n const dd = String(d.getUTCDate()).padStart(2, '0');\n const mon = months[d.getUTCMonth()]!;\n const yyyy = d.getUTCFullYear();\n const hh = String(d.getUTCHours()).padStart(2, '0');\n const mm = String(d.getUTCMinutes()).padStart(2, '0');\n const ss = String(d.getUTCSeconds()).padStart(2, '0');\n return `${wd}, ${dd} ${mon} ${yyyy} ${hh}:${mm}:${ss} +0000`;\n }\n /* c8 ignore stop @preserve */\n}\n\n// RFC 7231 defines three formats: IMF-fixdate, RFC 850, asctime.\n// The canonical format is IMF-fixdate (RFC 2822-like with required\n// seconds and UTC-only). Delegates to Date.parse for parsing and to\n// formatRFC2822 for formatting (they're nearly identical).\n\nexport function parseHTTPDate(input: string): unknown {\n const trimmed = input.trim();\n const ms = Date.parse(trimmed);\n if (Number.isNaN(ms)) {\n throw new FormatSyntaxError({ input, reason: 'not a valid HTTP-date' });\n }\n return requireInstant().fromEpochMilliseconds(ms);\n}\n\nexport function formatHTTPDate(value: unknown): string {\n // IMF-fixdate format: \"Sun, 06 Nov 1994 08:49:37 GMT\"\n const instant = (value as { toInstant?: () => { epochMilliseconds: number } })?.toInstant?.()\n ?? (value as { epochMilliseconds?: number });\n const ms = typeof instant === 'object' && instant !== null && 'epochMilliseconds' in instant\n ? (instant as { epochMilliseconds: number }).epochMilliseconds\n : (() => { throw new FormatSyntaxError({ reason: `formatHTTPDate() expects an Instant or ZonedDateTime, got ${typeof value}.` }); })();\n const d = new Date(ms);\n const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\n const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n const wd = days[d.getUTCDay()];\n const dd = String(d.getUTCDate()).padStart(2, '0');\n const mon = months[d.getUTCMonth()]!;\n const yyyy = d.getUTCFullYear();\n const hh = String(d.getUTCHours()).padStart(2, '0');\n const mm = String(d.getUTCMinutes()).padStart(2, '0');\n const ss = String(d.getUTCSeconds()).padStart(2, '0');\n return `${wd}, ${dd} ${mon} ${yyyy} ${hh}:${mm}:${ss} GMT`;\n}\n\n// All epoch conversions go through Temporal.Instant, which has spec\n// methods for each epoch granularity. Wrapped here for the\n// temporal-fmt surface so callers don't have to import Temporal\n// directly.\n\nfunction getInstant(value: unknown): { epochMilliseconds: number; epochNanoseconds: bigint } {\n const v = value as { toInstant?: () => { epochMilliseconds: number; epochNanoseconds: bigint }; epochMilliseconds?: number; epochNanoseconds?: bigint };\n if (typeof v?.toInstant === 'function') {\n const inst = v.toInstant();\n // Prefer the instant's own epochNanoseconds when present — same\n // precision reasoning as below, since toInstant() can return a\n // real Temporal.Instant carrying both fields.\n if (typeof (inst as { epochNanoseconds?: bigint }).epochNanoseconds === 'bigint') {\n return { epochMilliseconds: inst.epochMilliseconds, epochNanoseconds: (inst as { epochNanoseconds: bigint }).epochNanoseconds };\n }\n return { epochMilliseconds: inst.epochMilliseconds, epochNanoseconds: BigInt(inst.epochMilliseconds) * 1_000_000n };\n }\n // Check epochNanoseconds before epochMilliseconds: a real\n // Temporal.Instant exposes both, and epochMilliseconds is truncated\n // to millisecond precision. Deriving epochNanoseconds by scaling\n // epochMilliseconds back up would silently drop sub-ms precision\n // that was available on the object all along.\n if (typeof v?.epochNanoseconds === 'bigint') {\n return { epochMilliseconds: Number(v.epochNanoseconds / 1_000_000n), epochNanoseconds: v.epochNanoseconds };\n }\n if (typeof v?.epochMilliseconds === 'number') {\n return { epochMilliseconds: v.epochMilliseconds, epochNanoseconds: BigInt(v.epochMilliseconds) * 1_000_000n };\n }\n throw new FormatSyntaxError({ reason: `expected an Instant or ZonedDateTime, got ${typeof value}.` });\n}\n\nfunction requireInstant(): NonNullable<TemporalNamespace['Instant']> {\n const t = getTemporal().Instant;\n if (!t) throw new Error('temporal-fmt: Temporal.Instant is not available in this implementation.');\n return t;\n}\n\nexport function toUnixSeconds(value: unknown): number {\n return getInstant(value).epochMilliseconds / 1000;\n}\n\nexport function fromUnixSeconds(seconds: number): unknown {\n return requireInstant().fromEpochMilliseconds(seconds * 1000);\n}\n\nexport function fromUnixMilliseconds(ms: number): unknown {\n return requireInstant().fromEpochMilliseconds(ms);\n}\n\nexport function fromUnixMicroseconds(µs: number): unknown {\n // Temporal.Instant has no fromEpochMicroseconds in the spec — only\n // fromEpochMilliseconds and fromEpochNanoseconds. Convert via ns.\n return requireInstant().fromEpochNanoseconds(BigInt(µs) * 1_000n);\n}\n\nexport function fromUnixNanoseconds(ns: bigint): unknown {\n return requireInstant().fromEpochNanoseconds(ns);\n}\n\nexport function toUnixMilliseconds(value: unknown): number {\n return getInstant(value).epochMilliseconds;\n}\n\nexport function toUnixMicroseconds(value: unknown): number {\n const { epochNanoseconds } = getInstant(value);\n return Number(epochNanoseconds / 1_000n);\n}\n\nexport function toUnixNanoseconds(value: unknown): bigint {\n return getInstant(value).epochNanoseconds;\n}\n\n// SQL-oriented helpers. SQL date/time formats are simpler than the\n// network standards above — just 'YYYY-MM-DD' for dates, 'HH:MM:SS'\n// for times, 'YYYY-MM-DD HH:MM:SS' for datetimes. Delegating to\n// parse() with the right format strings keeps the validation surface\n// consistent.\nexport function parseSQL(input: string): unknown {\n const trimmed = input.trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(trimmed)) {\n return parse('yyyy-MM-dd', trimmed);\n }\n if (/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/.test(trimmed)) {\n return parse('yyyy-MM-dd HH:mm:ss', trimmed);\n }\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(trimmed)) {\n return parseISO(trimmed);\n }\n throw new FormatSyntaxError({ input, reason: 'not a recognized SQL date/time format' });\n}\n\nexport function formatSQL(value: unknown): string {\n // Detect what kind of Temporal value this is and pick the format.\n const v = value as { year?: number; hour?: number };\n if (typeof v?.hour === 'number') {\n return format(value as Parameters<typeof format>[0], 'yyyy-MM-dd HH:mm:ss');\n }\n return format(value as Parameters<typeof format>[0], 'yyyy-MM-dd');\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lets people register their own relative-date grammars on top of\n// parseRelative.ts, which only ships with English/Spanish/French/German\n// baked in.\n//\n// parseRelative() looks at the locale option, figures out the language,\n// and dispatches. registerRelativeGrammar() means someone can bolt on\n// a new language without touching parseRelative.ts itself.\n//\n// a grammar is just a list of matchers, each one either resolves to a\n// Temporal field bag or returns null. tries them in order, first match\n// wins — same shape as the ENGLISH/SPANISH/FRENCH/GERMAN_GRAMMAR objects\n// parseRelative already has internally, just made pluggable\n\nimport { getTemporal, type TemporalNamespace } from './temporalProvider.js';\n\nexport interface RelativeGrammarMatch {\n // whatever fields the matcher figured out, gets fed to Temporal.PlainDate.from()\n year?: number;\n month?: number;\n day?: number;\n // for cases like \"next Tuesday\" where you can't compute the fields\n // without knowing the reference date's weekday first — pass a function\n // instead of raw fields\n resolve?: (reference: { year: number; month: number; day: number; dayOfWeek: number }) => { year: number; month: number; day: number };\n}\n\nexport interface RelativeGrammar {\n // language subtag ('en', 'es', etc), matched against the locale option\n language: string;\n // tried top to bottom, first one that matches wins\n matchers: Array<(input: string) => RelativeGrammarMatch | null>;\n}\n\n// cap so nobody can loop registerRelativeGrammar() and blow up the array\n// (and the scan in tryRegisteredGrammar with it) forever. re-registering\n// an existing language doesn't count against this, only actually new ones.\n// same idea as what registerLocaleVocab does for custom vocabs\nconst MAX_REGISTERED_GRAMMARS = 100;\n\nconst registeredGrammars: RelativeGrammar[] = [];\n\nexport function registerRelativeGrammar(grammar: RelativeGrammar): void {\n if (typeof grammar.language !== 'string' || grammar.language.length === 0) {\n throw new Error('temporal-fmt: registerRelativeGrammar requires a non-empty language string.');\n }\n if (grammar.language.length > 35) {\n throw new RangeError(`temporal-fmt: registerRelativeGrammar language tags must be at most 35 characters (got ${grammar.language.length}).`);\n }\n if (!Array.isArray(grammar.matchers) || grammar.matchers.length === 0) {\n throw new Error('temporal-fmt: registerRelativeGrammar requires at least one matcher.');\n }\n // Every matcher runs on untrusted parseRelative input — a non-function\n // entry used to register fine and then blow up every subsequent\n // parseRelative() call for that locale with a raw V8 TypeError\n // (\"matcher is not a function\"). Cap the count for the same reason the\n // grammar count is capped: every registered matcher is scanned per\n // parseRelative call.\n if (grammar.matchers.length > 1000) {\n throw new RangeError(`temporal-fmt: registerRelativeGrammar accepts at most 1000 matchers (got ${grammar.matchers.length}).`);\n }\n if (!grammar.matchers.every((m) => typeof m === 'function')) {\n throw new Error('temporal-fmt: registerRelativeGrammar matchers must all be functions.');\n }\n // if this language's already registered, just swap it out\n const existingIdx = registeredGrammars.findIndex((g) => g.language === grammar.language);\n if (existingIdx >= 0) {\n registeredGrammars[existingIdx] = grammar;\n } else {\n if (registeredGrammars.length >= MAX_REGISTERED_GRAMMARS) {\n throw new RangeError(`temporal-fmt: registerRelativeGrammar reached the ${MAX_REGISTERED_GRAMMARS}-grammar limit.`);\n }\n registeredGrammars.push(grammar);\n }\n}\n\n// parseRelative() calls this first, before falling back to the built-ins.\n// null means nothing registered matched\nexport function tryRegisteredGrammar(\n language: string,\n input: string,\n reference: { year: number; month: number; day: number; dayOfWeek: number },\n): unknown | null {\n for (const grammar of registeredGrammars) {\n if (grammar.language !== language) continue;\n for (const matcher of grammar.matchers) {\n // One throwing matcher shouldn't take parseRelative() down with a\n // raw error — treat it as \"no match\" and let the next matcher (or\n // the built-in grammars) try. Registered matchers are third-party\n // code; isolating their failures is the registration boundary's\n // job.\n let match: RelativeGrammarMatch | null;\n try {\n match = matcher(input);\n } catch {\n continue;\n }\n if (match === null) continue;\n const temporal = getTemporal();\n if (match.resolve) {\n const fields = match.resolve(reference);\n return temporal.PlainDate.from(fields, { overflow: 'reject' });\n }\n return temporal.PlainDate.from(\n { year: match.year ?? reference.year, month: match.month ?? reference.month, day: match.day ?? reference.day },\n { overflow: 'reject' },\n );\n }\n }\n return null;\n}\n\n// just for introspection, lists what's registered\nexport function listRegisteredGrammars(): string[] {\n return registeredGrammars.map((g) => g.language);\n}\n\n// this is just here so TS doesn't complain about the unused import —\n// TemporalNamespace shows up in the type signature above but not as a\n// real runtime reference\nvoid (undefined as unknown as TemporalNamespace);\n","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getTemporal } from './temporalProvider.js';\nimport { type TemporalNamespace } from './temporalProvider.js';\nimport { tryRegisteredGrammar } from './relativeGrammar.js';\nimport { DEFAULT_LOCALE, type FormatOptions } from './tokens.js';\n\n// parseRelative resolves common relative-date phrases (\"next Tuesday\",\n// \"in 3 days\", \"March 5th\") against a reference date, returning a\n// Temporal.PlainDate. It's a different subsystem from the token-based\n// parse(): the input is free natural-language text, not a structurally-\n// typed format string, so this module owns its own grammar rather than\n// bolting a natural-language layer onto the existing tokenizer.\n//\n// Per-language grammars: each locale's grammar lives in its own\n// clearly-labeled section below (ENGLISH_GRAMMAR, SPANISH_GRAMMAR,\n// FRENCH_GRAMMAR, GERMAN_GRAMMAR). The vocabulary and phrase patterns\n// are NOT shared across languages — Spanish \"hace 2 semanas\" and\n// French \"il y a 2 semaines\" are different idioms and get their own\n// regexes. What IS shared is the matching engine (iterate matchers in\n// order, first match wins, throw on no match) and the resolution\n// helpers (addDays, addUnits, weekdayOffset, resolveToNextOccurrence).\n// Same approach the humanizing skill calls \"solve each recurring\n// problem once\": the matching strategy is shared, the per-language\n// vocabulary is not.\n//\n// Default locale (no `locale` option) uses English — matches the\n// pre-change behavior byte-for-byte. Passing `locale: 'es'`,\n// `locale: 'fr'`, or `locale: 'de'` (or any locale tag with that\n// language subtag) routes to the corresponding grammar. Unrecognized\n// languages fall back to English rather than throwing — a caller\n// passing `locale: 'it-IT'` still gets *some* result, just from the\n// English grammar. (We could throw instead; the current contract is\n// \"best effort.\" If the caller wanted Italian specifically, they'd\n// pass an Italian grammar via registerLocaleVocab-style extension —\n// not implemented here.)\n\n// Lowercase + expand German umlauts (ä→ae, ö→oe, ü→ue, ß→ss) + strip\n// remaining diacritics. Three things going on at once:\n//\n// 1. Lowercase — case-insensitive matching without forcing the\n// regex flag to do it (also keeps the captured groups lowercase\n// for the resolver's comparisons).\n// 2. Expand German umlaut transliterations. Germans without an\n// umlaut key write \"ä\" as \"ae\" — the standard transliteration.\n// Expanding \"ä\" → \"ae\" (before NFD stripping) means both \"März\"\n// and \"Maerz\" normalize to \"maerz\" and match the same pattern.\n// The reverse (ae → ä) would be wrong: \"Tage\" has \"ae\" as a\n// coincidence, not as an umlaut transliteration. Forward expansion\n// is unambiguous because the source string already has the\n// umlaut — the expansion only affects the matched form.\n// 3. Strip combining marks via NFD. \"Miércoles\" → \"Miercoles\",\n// \"février\" → \"fevrier\", \"août\" → \"aout\". Pairs with the umlaut\n// expansion above so all four languages' accented forms collapse\n// to one canonical unaccented form for matching.\n//\n// Both sides of the match — input string AND the weekday/month name\n// lists — get the same normalization applied, so this is symmetric.\nfunction normalizeForMatch(s: string): string {\n return s.toLowerCase()\n .replace(/ä/g, 'ae')\n .replace(/ö/g, 'oe')\n .replace(/ü/g, 'ue')\n .replace(/ß/g, 'ss')\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '');\n}\n\n// Standard Levenshtein edit distance (insert/delete/substitute, cost 1\n// each). Used only by the opt-in fuzzy layer below — the exact matcher\n// pass never calls this. Iterative DP over two rows, not the full\n// matrix, since only the previous row is ever needed.\nfunction levenshtein(a: string, b: string): number {\n /* c8 ignore start @preserve -- unreachable through the only call\n * site (fuzzyCorrectEnglish): `a` is always a word that already\n * failed the `vocabulary.includes(word)` exact-match check, so\n * a === b never holds against any `b` drawn from that same\n * vocabulary; and neither `a` (split from a non-empty normalized\n * string) nor `b` (a vocabulary entry) is ever empty. Kept as\n * general-purpose guards in case levenshtein() gets a second caller\n * later. */\n if (a === b) return 0;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n /* c8 ignore stop @preserve */\n let prev = new Array(b.length + 1);\n let curr = new Array(b.length + 1);\n for (let j = 0; j <= b.length; j++) prev[j] = j;\n for (let i = 1; i <= a.length; i++) {\n curr[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n prev[j] + 1, // deletion\n curr[j - 1] + 1, // insertion\n prev[j - 1] + cost, // substitution\n );\n }\n [prev, curr] = [curr, prev];\n }\n return prev[b.length];\n}\n\n// Max edit distance a fuzzy correction is allowed to bridge. 2 covers\n// the common single-finger-slip and single-transposed-letter typo cases\n// (\"tommorow\" is distance 1 from \"tomorrow\"; \"tuesady\" is distance 2\n// from \"tuesday\" — a transposition costs 2 under simple Levenshtein,\n// which doesn't special-case adjacent-swap as a single edit) without\n// opening the door to correcting a word into something only vaguely\n// similar. Deliberately conservative — this is a typo-tolerance layer,\n// not a \"guess what they meant\" layer; the library's whole design\n// philosophy elsewhere (parse()'s strict-by-default ambiguity handling,\n// the lenient opt-in) is to bound how much guessing is allowed and make\n// the caller ask for it explicitly.\nconst FUZZY_MAX_DISTANCE = 2;\nconst MAX_RELATIVE_INPUT_LENGTH = 4096;\nconst MAX_RELATIVE_WORDS = 32;\n\n// English-only fuzzy vocabulary. Anything a matcher's regex treats as a\n// fixed keyword (not a captured number) belongs here — weekday names,\n// month names (long and short), and the marker words the matchers\n// switch on (today/tomorrow/yesterday/next/last/this/in/ago and the\n// unit words day/week/month/year). Numbers and ordinal suffixes are\n// deliberately excluded: \"5th\" vs \"5tj\" isn't a word-shaped typo this\n// layer is trying to solve, and correcting digits is a much easier way\n// to silently produce a wrong date than correcting a weekday name is.\n//\n// Scoped to English only for this pass — the other three grammars have\n// enough positional/multi-word-marker variation (French's \"il y a\",\n// Spanish's dual pre/post weekday-modifier shapes) that a single\n// word-substitution corrector isn't a good fit for all of them without\n// per-language tuning this change doesn't attempt. parseRelative()\n// throws a clear scope-limited error if { fuzzy: true } is combined\n// with a non-English locale, rather than silently no-op-ing.\nfunction buildEnglishFuzzyVocabulary(): string[] {\n return [\n ...ENGLISH_WEEKDAYS,\n ...ENGLISH_MONTHS,\n ...ENGLISH_MONTH_SHORT,\n 'today', 'tomorrow', 'yesterday',\n 'next', 'last', 'this',\n 'in', 'ago',\n 'day', 'days', 'week', 'weeks', 'month', 'months', 'year', 'years',\n ].map(normalizeForMatch);\n}\n\n// Lazily built and cached — the vocabulary is static per process, no\n// need to rebuild the normalized list on every fuzzy call.\nlet englishFuzzyVocabulary: readonly string[] | undefined;\nfunction getEnglishFuzzyVocabulary(): readonly string[] {\n if (!englishFuzzyVocabulary) englishFuzzyVocabulary = Object.freeze(buildEnglishFuzzyVocabulary());\n return englishFuzzyVocabulary;\n}\n\n// Attempts a word-level fuzzy correction of `normalized` against the\n// English vocabulary, returning a corrected string or undefined if no\n// correction was needed/possible. Tokenizes on whitespace; each token\n// that isn't already an exact vocabulary word (or a pure number/ordinal,\n// which passes through untouched) gets replaced with its closest\n// vocabulary match, if one exists within FUZZY_MAX_DISTANCE. If a token\n// has no sufficiently-close vocabulary match, it's left as-is — the\n// re-attempted exact match will then fail on that token same as before,\n// which is the correct outcome for \"this word isn't a typo of anything\n// we know, it's just not a phrase we support.\"\nfunction fuzzyCorrectEnglish(normalized: string): string | undefined {\n const vocabulary = getEnglishFuzzyVocabulary();\n const words = normalized.split(' ');\n if (normalized.length > MAX_RELATIVE_INPUT_LENGTH || words.length > MAX_RELATIVE_WORDS) {\n throw new RangeError(\n `temporal-fmt: parseRelative fuzzy input is too large (maximum ${MAX_RELATIVE_INPUT_LENGTH} characters and ${MAX_RELATIVE_WORDS} words).`,\n );\n }\n let changed = false;\n const corrected = words.map((word) => {\n // Pure digits, or digits with an ordinal suffix (st/nd/rd/th) —\n // never touched by fuzzy correction. See the vocabulary comment\n // above for why.\n if (/^\\d+(?:st|nd|rd|th)?$/.test(word)) return word;\n // Already an exact vocabulary word — nothing to correct.\n if (vocabulary.includes(word)) return word;\n\n let best: string | undefined;\n let bestDist = FUZZY_MAX_DISTANCE + 1;\n for (const candidate of vocabulary) {\n const dist = levenshtein(word, candidate);\n if (dist < bestDist) {\n bestDist = dist;\n best = candidate;\n }\n }\n if (best !== undefined && bestDist <= FUZZY_MAX_DISTANCE) {\n changed = true;\n return best;\n }\n return word;\n });\n\n return changed ? corrected.join(' ') : undefined;\n}\n\ninterface TemporalFieldBag {\n year?: number;\n month?: number;\n day?: number;\n dayOfWeek?: number;\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n}\n\nfunction readYear(reference: TemporalFieldBag): number {\n if (typeof reference.year !== 'number') {\n throw new Error('temporal-fmt: parseRelative reference date is missing year.');\n }\n return reference.year;\n}\nfunction readMonth(reference: TemporalFieldBag): number {\n if (typeof reference.month !== 'number') {\n throw new Error('temporal-fmt: parseRelative reference date is missing month.');\n }\n return reference.month;\n}\nfunction readDay(reference: TemporalFieldBag): number {\n if (typeof reference.day !== 'number') {\n throw new Error('temporal-fmt: parseRelative reference date is missing day.');\n }\n return reference.day;\n}\n\nfunction extractDayOfWeek(reference: TemporalFieldBag): number {\n const dow = reference.dayOfWeek;\n if (typeof dow !== 'number') {\n throw new Error(\n 'temporal-fmt: parseRelative needs a reference date exposing dayOfWeek (a Temporal.PlainDate / PlainDateTime / ZonedDateTime).'\n );\n }\n return dow;\n}\n\n// Build an alternation regex fragment from a name list, normalized for\n// matching. Longest-first so \"September\" wins over \"Sep\" in the same\n// match position. The caller is responsible for any wrapping groups\n// or anchors — this just produces the inner alternation.\nfunction nameAlternation(names: string[]): string {\n const normalized = names.map(normalizeForMatch);\n // Dedupe — some locales render the long and short form identically\n // (English \"May\" is the same in both MMMM and MMM lists). Keep both\n // in the alternation rather than deduping, since duplicates in a\n // regex alternation don't change behavior and the dedupe would just\n // be a micro-optimization.\n // Sort longest-first so a longer name wins over its own prefix.\n const sorted = [...normalized].sort((a, b) => b.length - a.length);\n // Escape regex metacharacters — names shouldn't contain any, but\n // belt-and-braces avoids a future \"M+1\" month name from breaking\n // the alternation silently.\n return sorted.map((n) => n.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')).join('|');\n}\n\n// Resolves to a PlainDate by adding `days` to the reference. Used for\n// weekday refs and the today/tomorrow/yesterday family.\nfunction buildPlainDate(temporal: { PlainDate: { from: (fields: Record<string, number>, options?: { overflow?: 'constrain' | 'reject' }) => unknown } }, year: number, month: number, day: number): unknown {\n return temporal.PlainDate.from({ year, month, day }, { overflow: 'reject' });\n}\n\nfunction addDays(\n temporal: { PlainDate: { from: (fields: Record<string, number>) => unknown } },\n reference: TemporalFieldBag,\n days: number,\n): unknown {\n // Build the reference as a real PlainDate so we can use Temporal's\n // own add() for date arithmetic — calendar-correct (handles month\n // boundaries, leap years, etc.) so we don't have to reimplement it.\n const refDate = temporal.PlainDate.from({\n year: readYear(reference),\n month: readMonth(reference),\n day: readDay(reference),\n }) as { add: (duration: Record<string, number>) => unknown };\n return refDate.add({ days });\n}\n\nfunction addUnits(\n temporal: { PlainDate: { from: (fields: Record<string, number>) => unknown } },\n reference: TemporalFieldBag,\n count: number,\n unit: 'day' | 'week' | 'month' | 'year',\n): unknown {\n const refDate = temporal.PlainDate.from({\n year: readYear(reference),\n month: readMonth(reference),\n day: readDay(reference),\n }) as { add: (duration: Record<string, number>) => unknown };\n const duration: Record<string, number> = {};\n if (unit === 'day') duration.days = count;\n if (unit === 'week') duration.weeks = count;\n if (unit === 'month') duration.months = count;\n if (unit === 'year') duration.years = count;\n return refDate.add(duration);\n}\n\n// \"next X\" — strictly future next occurrence. Said on a Tuesday:\n// \"next Tuesday\" = 7 days from now, not today. Rationale: \"this\n// Tuesday\" handles the same-week case, so \"next Tuesday\" staying\n// strictly-future gives the two phrases distinct, non-overlapping\n// meanings. Documented in README \"parseRelative\".\n//\n// \"last X\" — strictly past most recent occurrence. Symmetric to \"next\".\n//\n// \"this X\" — the X of the current ISO week (Mon..Sun). Can land on\n// today, past, or future depending on where in the week today falls.\n//\n// All three resolve the same way across the four supported languages\n// (en/es/fr/de): the equivalent idiom in each language maps to one of\n// these three rel words. The natural-language reading is consistent\n// — \"next Tuesday\" said on a Tuesday means next week's Tuesday in\n// every language we support.\nfunction weekdayOffset(rel: 'next' | 'last' | 'this', refDow: number, targetDow: number): number {\n // refDow and targetDow are both 1..7 (ISO Mon=1..Sun=7).\n if (rel === 'next') {\n let diff = targetDow - refDow;\n if (diff <= 0) diff += 7; // 0 (today) → 7, negative → wrap forward\n return diff; // 1..7\n }\n if (rel === 'last') {\n let diff = targetDow - refDow;\n if (diff >= 0) diff -= 7; // 0 (today) → -7, positive → wrap backward\n return diff; // -7..-1\n }\n // rel === 'this' — X of the current week. Can be today, past, or future.\n return targetDow - refDow; // -6..+6\n}\n\n// \"March 5th\" without a year → resolve to the next occurrence of that\n// month/day. If today is that date, return today. Otherwise, if it's\n// already past this year, return next year's occurrence.\n//\n// \"Next occurrence\" semantics: future-leaning. Documented in README\n// as the chosen behavior. The alternative (\"nearest in time, past or\n// future\") would mean \"March 5th\" said on March 6 returns yesterday —\n// counterintuitive for the typical \"next birthday\"/\"next deadline\"\n// use case this kind of phrase tends to drive.\nfunction resolveToNextOccurrence(\n temporal: {\n PlainDate: {\n from: (fields: Record<string, number>, options?: { overflow?: 'constrain' | 'reject' }) => unknown;\n compare?: (one: unknown, two: unknown) => number;\n };\n },\n reference: TemporalFieldBag,\n month: number,\n day: number,\n): unknown {\n const refYear = readYear(reference);\n const refDate = temporal.PlainDate.from({\n year: refYear,\n month: readMonth(reference),\n day: readDay(reference),\n });\n // PlainDate.compare is a static method on the namespace, not an\n // instance method — that's why it's called off temporal.PlainDate\n // rather than off an instance below. Checked outside the try/catch\n // below on purpose: that block's catch is scoped to Feb-29-style\n // overflow errors from from(), and silently retries with next year's\n // date. A missing-compare error thrown from inside that try would get\n // caught by the same handler and swallowed by that retry (next year's\n // from() usually succeeds), masking the real problem instead of\n // surfacing it.\n if (!temporal.PlainDate.compare) {\n throw new Error('temporal-fmt: parseRelative needs Temporal.PlainDate.compare to resolve month-day phrases; the active implementation does not expose it.');\n }\n // try this year first; if Feb 29 in a non-leap year, Temporal will\n // throw via overflow: 'reject' — fall through to next year.\n try {\n const thisYear = temporal.PlainDate.from({ year: refYear, month, day }, { overflow: 'reject' });\n // Returns -1 / 0 / 1.\n if (temporal.PlainDate.compare(thisYear, refDate) >= 0) {\n // today or in the future → use this year's occurrence\n return thisYear;\n }\n // already past this year → next year's occurrence\n return temporal.PlainDate.from({ year: refYear + 1, month, day }, { overflow: 'reject' });\n } catch (err) {\n // Feb 29 in a non-leap year, or similar. Try next year — if the\n // caller asked for \"Feb 29\" said in a non-leap year, next year may\n // also not be leap, in which case the inner from() will throw and\n // surface a clear error rather than silently landing on Feb 28.\n try {\n return temporal.PlainDate.from({ year: refYear + 1, month, day }, { overflow: 'reject' });\n } catch {\n throw new Error(\n `temporal-fmt: parseRelative can't resolve month ${month} day ${day} — ` +\n `it isn't a valid date in either ${refYear} or ${refYear + 1}. ` +\n `Original error: ${(err as Error).message}`\n );\n }\n }\n}\n\n// Each language provides a list of matchers. The shared engine\n// iterates them in order and returns the first match. A matcher is a\n// (regex, resolver) pair — the regex captures the structural pieces\n// (count, unit name, weekday name, etc.), the resolver turns them\n// into a Temporal.PlainDate using the shared helpers above.\ninterface ResolveContext {\n temporal: TemporalNamespace;\n reference: TemporalFieldBag;\n}\n\ninterface Matcher {\n pattern: RegExp;\n resolve: (match: RegExpMatchArray, ctx: ResolveContext) => unknown;\n}\n\ninterface RelativeDateGrammar {\n // Single-line description of supported phrase classes, included in\n // the \"doesn't recognize\" error so the caller knows what to try.\n supportedHint: string;\n // Ordered matchers; first match wins.\n matchers: Matcher[];\n}\n\nfunction weekdayIndexFromName(name: string, names: string[]): number {\n const normalized = normalizeForMatch(name);\n const idx = names.findIndex((n) => normalizeForMatch(n) === normalized);\n /* c8 ignore start @preserve -- unreachable: every caller passes a\n * name captured by nameAlternation(names), which builds its regex\n * alternation from this same list under the same normalizeForMatch\n * transform. The regex can't match anything findIndex() wouldn't\n * also find here. Defensive throw kept for the type checker and as\n * a tripwire if that invariant ever breaks. Ignore comment sits on\n * the `if` itself, not just the throw inside it — c8 tracks the\n * branch outcome (was the true side ever taken) separately from the\n * statements inside, so excluding only the inner throw still leaves\n * the branch itself flagged as uncovered. */\n /* c8 ignore next */\n if (idx < 0) {\n throw new Error(`temporal-fmt: parseRelative internal error — weekday \"${name}\" not in names list.`);\n }\n /* c8 ignore stop @preserve */\n return idx + 1;\n}\n\nfunction monthIndexFromName(name: string, longNames: string[], shortNames: string[] = []): number {\n const normalized = normalizeForMatch(name);\n const longIdx = longNames.findIndex((n) => normalizeForMatch(n) === normalized);\n if (longIdx >= 0) return longIdx + 1;\n const shortIdx = shortNames.findIndex((n) => normalizeForMatch(n) === normalized);\n /* c8 ignore next */\n if (shortIdx >= 0) return shortIdx + 1;\n /* c8 ignore start @preserve -- unreachable: every caller passes a name\n * captured by nameAlternation([...longNames, ...shortNames]), so the\n * regex alternation and these two findIndex() scans are built from\n * the same lists under the same normalizeForMatch transform. Kept as\n * a tripwire for the type checker in case that invariant ever breaks. */\n throw new Error(`temporal-fmt: parseRelative internal error — month \"${name}\" not in names list.`);\n /* c8 ignore stop @preserve */\n /* c8 ignore next -- defensive block is unreachable by construction. */\n}\n\n// English grammar — also the default when no locale is supplied. The\n// regexes here are the same ones the pre-change parseRelative() used\n// inline; they've just been pulled into a matcher list so the matching\n// engine can iterate them the same way it does for es/fr/de.\nconst ENGLISH_WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];\nconst ENGLISH_MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\nconst ENGLISH_MONTH_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\nconst ENGLISH_GRAMMAR: RelativeDateGrammar = {\n supportedHint: 'Supported: weekday refs (\"next Tuesday\"), day offsets (\"today\"/\"tomorrow\"/\"yesterday\"), unit offsets (\"in 3 days\", \"2 weeks ago\"), and month-day (\"March 5th\").',\n matchers: [\n // today / tomorrow / yesterday — exact match, most rigid shape.\n // Checked first because they're the most common phrase class.\n {\n pattern: /^today$/i,\n resolve: (_m, ctx) => buildPlainDate(ctx.temporal, readYear(ctx.reference), readMonth(ctx.reference), readDay(ctx.reference)),\n },\n {\n pattern: /^tomorrow$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, 1),\n },\n {\n pattern: /^yesterday$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, -1),\n },\n // weekday references: \"next/last/this Tuesday\". Capture the relative\n // word and the weekday name separately, then resolve via +7 / -7.\n {\n pattern: new RegExp(`^(next|last|this)\\\\s+(${nameAlternation(ENGLISH_WEEKDAYS)})$`, 'i'),\n resolve: (m, ctx) => {\n const rel = m[1]!.toLowerCase() as 'next' | 'last' | 'this';\n const targetDow = weekdayIndexFromName(m[2]!, ENGLISH_WEEKDAYS);\n const refDow = extractDayOfWeek(ctx.reference);\n return addDays(ctx.temporal, ctx.reference, weekdayOffset(rel, refDow, targetDow));\n },\n },\n // unit offsets: \"in 3 days\", \"2 weeks ago\", \"in 1 month\", \"1 year ago\".\n // Two shapes share this matcher — leading \"in\" (future) or trailing\n // \"ago\" (past). Both lead with <number> <unit>.\n {\n pattern: /^(in\\s+)?(\\d+)\\s+(day|week|month|year)s?(?:\\s+ago)?$/i,\n resolve: (m, ctx) => {\n const inPrefix = m[1];\n const count = m[2]!;\n const unitName = m[3]!.toLowerCase() as 'day' | 'week' | 'month' | 'year';\n // Disambiguate future vs past: \"in N units\" is always future; \"N\n // units ago\" is always past. A bare \"N units\" without either is\n // a sign error — throw, since neither direction is implied and\n // guessing is exactly what this library refuses to do.\n const hasIn = !!inPrefix;\n const hasAgo = /\\bago\\b/i.test(m[0]!);\n if (!hasIn && !hasAgo) {\n throw new Error(\n `temporal-fmt: parseRelative can't tell whether \"${m[0]}\" is past or future — ` +\n `use \"in ${count} ${unitName}s\" or \"${count} ${unitName}s ago\".`\n );\n }\n // Contradictory markers: the regex tolerates \"in 3 days ago\"\n // (both a leading \"in\" and a trailing \"ago\"), which used to\n // silently resolve as FUTURE. The library's whole posture is\n // throw-rather-than-guess — a contradiction is worse than a\n // missing marker, not something to quietly pick a side on.\n if (hasIn && hasAgo) {\n throw new Error(\n `temporal-fmt: parseRelative got contradictory direction markers in \"${m[0]}\" — ` +\n `\"in N ${unitName}s\" is future and \"N ${unitName}s ago\" is past; use one or the other.`\n );\n }\n const sign = hasIn ? 1 : -1;\n return addUnits(ctx.temporal, ctx.reference, sign * Number(count), unitName);\n },\n },\n // month-day without year, e.g. \"March 5th\", \"March 5\", \"March 5, 2026\"\n // (year is ignored if present). The ordinal suffix is decorative —\n // strip it. The day-of-month is a 1- or 2-digit number.\n {\n pattern: new RegExp(`^(${nameAlternation([...ENGLISH_MONTHS, ...ENGLISH_MONTH_SHORT])})\\\\s+(\\\\d{1,2})(?:st|nd|rd|th)?(?:,?\\\\s*(\\\\d{4}))?$`, 'i'),\n resolve: (m, ctx) => {\n const month = monthIndexFromName(m[1]!, ENGLISH_MONTHS, ENGLISH_MONTH_SHORT);\n const day = Number(m[2]!);\n return resolveToNextOccurrence(ctx.temporal, ctx.reference, month, day);\n },\n },\n ],\n};\n\n// Spanish grammar. Distinct phrase shapes from English:\n// - \"hace 2 semanas\" (past unit offset) — distinct word \"hace\", not\n// the English \"X units ago\" suffix shape.\n// - \"5 de marzo\" — day-first, with required \"de\" between day and\n// month, opposite of English \"March 5\".\n// - \"el próximo lunes\" / \"lunes pasado\" — weekday ref has the relative\n// word sometimes as a prefix with article, sometimes as a suffix.\n//\n// All four phrase classes the English grammar supports have Spanish\n// equivalents here.\nconst SPANISH_WEEKDAYS = ['lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado', 'domingo'];\nconst SPANISH_MONTHS = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];\n// Spanish month abbreviations vary by region (\"set\" vs \"sept\" for\n// September). Sticking with the most common ICU form per locale.\nconst SPANISH_MONTH_SHORT = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sept', 'oct', 'nov', 'dic'];\n\nconst SPANISH_GRAMMAR: RelativeDateGrammar = {\n supportedHint: 'Frases soportadas: referencias de día de la semana (\"el próximo lunes\", \"el lunes pasado\", \"este martes\"), offsets de día (\"hoy\"/\"mañana\"/\"ayer\"), offsets de unidad (\"en 3 días\", \"hace 2 semanas\"), y mes-día (\"5 de marzo\").',\n matchers: [\n {\n pattern: /^hoy$/i,\n resolve: (_m, ctx) => buildPlainDate(ctx.temporal, readYear(ctx.reference), readMonth(ctx.reference), readDay(ctx.reference)),\n },\n {\n pattern: /^ma[ñn]ana$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, 1),\n },\n {\n pattern: /^ayer$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, -1),\n },\n // weekday references. Spanish has three common shapes, all meaning\n // the same thing per rel word:\n // \"el próximo lunes\" / \"próximo lunes\" → next\n // \"el lunes próximo\" → next (suffix variant)\n // \"el lunes pasado\" / \"lunes pasado\" → last\n // \"este lunes\" → this\n // Capture the rel word from whichever shape matched, then resolve\n // the same way English does.\n {\n pattern: new RegExp(\n `^(?:el\\\\s+)?(?:(pr[oó]ximo|pasado)\\\\s+(${nameAlternation(SPANISH_WEEKDAYS)})|(${nameAlternation(SPANISH_WEEKDAYS)})\\\\s+(pr[oó]ximo|pasado)|este\\\\s+(${nameAlternation(SPANISH_WEEKDAYS)}))$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n let relWord: string;\n let weekdayName: string;\n if (m[1] && m[2]) {\n // prefix variant: \"próximo lunes\" / \"pasado lunes\"\n relWord = m[1]!;\n weekdayName = m[2]!;\n } else if (m[3] && m[4]) {\n // suffix variant: \"lunes próximo\" / \"lunes pasado\"\n weekdayName = m[3]!;\n relWord = m[4]!;\n } else {\n // \"este lunes\"\n relWord = 'este';\n weekdayName = m[5]!;\n }\n const rel = normalizeForMatch(relWord) === 'proximo' ? 'next' : relWord.toLowerCase() === 'este' ? 'this' : 'last';\n const targetDow = weekdayIndexFromName(weekdayName, SPANISH_WEEKDAYS);\n const refDow = extractDayOfWeek(ctx.reference);\n return addDays(ctx.temporal, ctx.reference, weekdayOffset(rel, refDow, targetDow));\n },\n },\n // unit offsets. Spanish uses distinct markers:\n // \"en 3 días\" / \"dentro de 3 días\" → future\n // \"hace 2 semanas\" → past\n // Both shapes lead with the marker, unlike English where one\n // shape leads and the other trails.\n {\n pattern: new RegExp(\n `^(?:(en|dentro\\\\s+de)\\\\s+(\\\\d+)\\\\s+(d[ií]a|semana|mes|a[ñn]o)s?|(\\\\d+)\\\\s+(d[ií]a|semana|mes|a[ñn]o)s?\\\\s+(hace))$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n let count: string;\n let unitWord: string;\n let sign: number;\n if (m[1] && m[2] && m[3]) {\n // future: \"en 3 días\" / \"dentro de 3 días\"\n count = m[2]!;\n unitWord = m[3]!;\n sign = 1;\n } else {\n // past: \"2 semanas hace\" — but the more natural Spanish is\n // \"hace 2 semanas\" (marker first). The regex above only\n // matches \"N units hace\"; that's a less common but\n // grammatical alternative. The primary past form \"hace N\n // unidades\" is matched by the next matcher.\n count = m[4]!;\n unitWord = m[5]!;\n sign = -1;\n }\n const unit = unitWordToEnglish(unitWord);\n return addUnits(ctx.temporal, ctx.reference, sign * Number(count), unit);\n },\n },\n // \"hace 2 semanas\" — the primary past-offset shape. Matcher kept\n // separate from the future \"en/dentro de\" matcher above because\n // Spanish word order differs between the two (marker-first for\n // past, marker-first for future too, but with different markers).\n {\n pattern: new RegExp(`^hace\\\\s+(\\\\d+)\\\\s+(d[ií]a|semana|mes|a[ñn]o)s?$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, -count, unit);\n },\n },\n // bare \"N <unit>\" without \"en\" / \"hace\" — throw, since direction\n // is ambiguous. Matched AFTER the directional shapes so the\n // directional ones win when their marker is present.\n {\n pattern: new RegExp(`^(\\\\d+)\\\\s+(d[ií]a|semana|mes|a[ñn]o)s?$`, 'i'),\n resolve: (m, _ctx) => {\n throw new Error(\n `temporal-fmt: parseRelative no puede decidir si \"${m[0]}\" es pasado o futuro — ` +\n `usa \"en ${m[1]} ${m[2]}s\" o \"hace ${m[1]} ${m[2]}s\".`\n );\n },\n },\n // month-day: \"5 de marzo\" (day first), \"5 de marzo de 2026\" (year\n // ignored if present). Day is 1-2 digits, with optional trailing\n // \".\" (rare in Spanish but tolerated).\n {\n pattern: new RegExp(\n `^(\\\\d{1,2})\\\\.?\\\\s+de\\\\s+(${nameAlternation([...SPANISH_MONTHS, ...SPANISH_MONTH_SHORT])})(?:\\\\s+de\\\\s+(\\\\d{4}))?$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n const day = Number(m[1]!);\n const month = monthIndexFromName(m[2]!, SPANISH_MONTHS, SPANISH_MONTH_SHORT);\n return resolveToNextOccurrence(ctx.temporal, ctx.reference, month, day);\n },\n },\n ],\n};\n\n// French grammar. Distinct from English/Spanish:\n// - \"il y a 2 semaines\" (past marker is a 3-word phrase, not a single word).\n// - \"mardi prochain\" — relative word is a SUFFIX on the weekday,\n// opposite of English \"next Tuesday\".\n// - \"5 mars\" — day-first, no \"de\" between day and month (unlike\n// Spanish's \"5 de marzo\").\nconst FRENCH_WEEKDAYS = ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'];\nconst FRENCH_MONTHS = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];\nconst FRENCH_MONTH_SHORT = ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'];\n\nconst FRENCH_GRAMMAR: RelativeDateGrammar = {\n supportedHint: 'Phrases prises en charge : références de jour de la semaine (\"lundi prochain\", \"mardi dernier\", \"ce mercredi\"), décalages de jour (\"aujourd\\'hui\"/\"demain\"/\"hier\"), décalages d\\'unité (\"dans 3 jours\", \"il y a 2 semaines\"), et mois-jour (\"5 mars\").',\n matchers: [\n {\n pattern: /^aujourd'hui$/i,\n resolve: (_m, ctx) => buildPlainDate(ctx.temporal, readYear(ctx.reference), readMonth(ctx.reference), readDay(ctx.reference)),\n },\n {\n pattern: /^demain$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, 1),\n },\n {\n pattern: /^hier$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, -1),\n },\n // weekday references: \"lundi prochain\" (next), \"lundi dernier\"\n // (last), \"ce lundi\" (this). The relative word follows the\n // weekday for next/last, precedes it for this.\n {\n pattern: new RegExp(\n `^(?:(${nameAlternation(FRENCH_WEEKDAYS)})\\\\s+(prochain|dernier)|ce\\\\s+(${nameAlternation(FRENCH_WEEKDAYS)}))$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n let rel: 'next' | 'last' | 'this';\n let weekdayName: string;\n if (m[1] && m[2]) {\n weekdayName = m[1]!;\n rel = m[2]!.toLowerCase() === 'prochain' ? 'next' : 'last';\n } else {\n rel = 'this';\n weekdayName = m[3]!;\n }\n const targetDow = weekdayIndexFromName(weekdayName, FRENCH_WEEKDAYS);\n const refDow = extractDayOfWeek(ctx.reference);\n return addDays(ctx.temporal, ctx.reference, weekdayOffset(rel, refDow, targetDow));\n },\n },\n // past: \"il y a 2 semaines\" — multi-word marker.\n {\n pattern: new RegExp(`^il\\\\s+y\\\\s+a\\\\s+(\\\\d+)\\\\s+(jour|semaine|mois|an|ann[eée]e)s?$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, -count, unit);\n },\n },\n // future: \"dans 3 jours\"\n {\n pattern: new RegExp(`^dans\\\\s+(\\\\d+)\\\\s+(jour|semaine|mois|an|ann[eée]e)s?$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, count, unit);\n },\n },\n // bare \"N <unit>\" without marker — throw.\n {\n pattern: new RegExp(`^(\\\\d+)\\\\s+(jour|semaine|mois|an|ann[eée]e)s?$`, 'i'),\n resolve: (m, _ctx) => {\n throw new Error(\n `temporal-fmt: parseRelative ne peut pas déterminer si \"${m[0]}\" est passé ou futur — ` +\n `utilisez \"dans ${m[1]} ${m[2]}s\" ou \"il y a ${m[1]} ${m[2]}s\".`\n );\n },\n },\n // month-day: \"5 mars\" (day first, no separator word). Year ignored.\n {\n pattern: new RegExp(\n `^(\\\\d{1,2})\\\\s+(${nameAlternation([...FRENCH_MONTHS, ...FRENCH_MONTH_SHORT])})(?:\\\\s+(\\\\d{4}))?$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n const day = Number(m[1]!);\n const month = monthIndexFromName(m[2]!, FRENCH_MONTHS, FRENCH_MONTH_SHORT);\n return resolveToNextOccurrence(ctx.temporal, ctx.reference, month, day);\n },\n },\n ],\n};\n\n// German grammar. Distinct from the others:\n// - Unit words pluralize with -n in the dative after \"in\"/\"vor\":\n// \"in 3 Tagen\" (vs nominative \"3 Tage\"). The regex accepts both\n// since callers may not always get the case right, and accepting\n// both doesn't introduce ambiguity.\n// - \"nächsten Dienstag\" — relative word precedes weekday as a\n// declined adjective, with the weekday capitalized as a noun.\n// - \"5. März\" — day-first with a period after the day number,\n// matching German date convention.\nconst GERMAN_WEEKDAYS = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];\nconst GERMAN_MONTHS = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];\nconst GERMAN_MONTH_SHORT = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];\n\nconst GERMAN_GRAMMAR: RelativeDateGrammar = {\n supportedHint: 'Unterstützte Phrasen: Wochentag-Bezüge (\"nächsten Dienstag\", \"letzten Freitag\", \"diesen Montag\"), Tages-Offsets (\"heute\"/\"morgen\"/\"gestern\"), Einheiten-Offsets (\"in 3 Tagen\", \"vor 2 Wochen\"), und Monat-Tag (\"5. März\").',\n matchers: [\n {\n pattern: /^heute$/i,\n resolve: (_m, ctx) => buildPlainDate(ctx.temporal, readYear(ctx.reference), readMonth(ctx.reference), readDay(ctx.reference)),\n },\n {\n pattern: /^morgen$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, 1),\n },\n {\n pattern: /^gestern$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, -1),\n },\n // weekday references: \"nächsten Dienstag\" (next), \"letzten\n // Dienstag\" (last), \"diesen Dienstag\" (this). Adjective precedes\n // the weekday; case varies (nächsten/letzten/diesen all take the\n // weak-declension -en/-en/-en ending when no article, which is\n // convenient — one regex alternation covers all three.\n {\n pattern: new RegExp(`^(n(?:ae|a|ä)chsten|letzten|diesen)\\\\s+(${nameAlternation(GERMAN_WEEKDAYS)})$`, 'i'),\n resolve: (m, ctx) => {\n const adj = normalizeForMatch(m[1]!);\n const rel: 'next' | 'last' | 'this' = (adj === 'nachsten' || adj === 'naechsten') ? 'next' : adj === 'diesen' ? 'this' : 'last';\n const targetDow = weekdayIndexFromName(m[2]!, GERMAN_WEEKDAYS);\n const refDow = extractDayOfWeek(ctx.reference);\n return addDays(ctx.temporal, ctx.reference, weekdayOffset(rel, refDow, targetDow));\n },\n },\n // past: \"vor 2 Wochen\"\n {\n pattern: new RegExp(`^vor\\\\s+(\\\\d+)\\\\s+(Tag(?:e|n|en)?|Woche(?:n)?|Monat(?:e|n|en)?|Jahr(?:e|n|en)?)$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, -count, unit);\n },\n },\n // future: \"in 3 Tagen\"\n {\n pattern: new RegExp(`^in\\\\s+(\\\\d+)\\\\s+(Tag(?:e|n|en)?|Woche(?:n)?|Monat(?:e|n|en)?|Jahr(?:e|n|en)?)$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, count, unit);\n },\n },\n // bare \"N <unit>\" without \"in\" or \"vor\" — throw.\n {\n pattern: new RegExp(`^(\\\\d+)\\\\s+(Tag(?:e|n|en)?|Woche(?:n)?|Monat(?:e|n|en)?|Jahr(?:e|n|en)?)$`, 'i'),\n resolve: (m, _ctx) => {\n throw new Error(\n `temporal-fmt: parseRelative kann nicht erkennen, ob \"${m[0]}\" Vergangenheit oder Zukunft ist — ` +\n `verwende \"in ${m[1]} ${m[2]}\" oder \"vor ${m[1]} ${m[2]}\".`\n );\n },\n },\n // month-day: \"5. März\" (day-first with period). Year ignored.\n {\n pattern: new RegExp(\n `^(\\\\d{1,2})\\\\.?\\\\s+(${nameAlternation([...GERMAN_MONTHS, ...GERMAN_MONTH_SHORT, 'Maerz', 'Maer'])})(?:\\\\s+(\\\\d{4}))?$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n const day = Number(m[1]!);\n const month = monthIndexFromName(m[2]!, GERMAN_MONTHS, GERMAN_MONTH_SHORT);\n return resolveToNextOccurrence(ctx.temporal, ctx.reference, month, day);\n },\n },\n ],\n};\n\nconst GRAMMARS: Record<string, RelativeDateGrammar> = {\n en: ENGLISH_GRAMMAR,\n es: SPANISH_GRAMMAR,\n fr: FRENCH_GRAMMAR,\n de: GERMAN_GRAMMAR,\n};\n\n// Pick a grammar for a locale. Falls back to English for languages we\n// don't have a grammar for (Italian, Portuguese, etc.) rather than\n// throwing — best-effort, matches how formatDistance treats unknown\n// locales (Intl.RelativeTimeFormat accepts them; here we fall back to\n// English so the call still succeeds with reasonable output).\nfunction grammarForLocale(locale: string | undefined): RelativeDateGrammar {\n if (!locale) return ENGLISH_GRAMMAR;\n try {\n // Intl.Locale requires BCP-47 hyphens — same normalization as the\n // other locale-handling code in this library.\n const tag = new Intl.Locale(locale.replace(/_/g, '-'));\n const lang = tag.language.toLowerCase();\n return GRAMMARS[lang] ?? ENGLISH_GRAMMAR;\n } catch {\n // Malformed locale tag — fall back to English. The actual Intl\n // call downstream will throw if the tag is genuinely unusable,\n // which is a better surface for that error than here.\n return ENGLISH_GRAMMAR;\n }\n}\n\n// Language subtag of a locale option, for dispatching to grammars\n// registered via registerRelativeGrammar(). Mirrors grammarForLocale's\n// normalization and fallback.\nfunction languageOf(locale: string | undefined): string {\n if (!locale) return 'en';\n try {\n return new Intl.Locale(locale.replace(/_/g, '-')).language.toLowerCase();\n } catch {\n return 'en';\n }\n}\n\n// Map a per-language unit word back to the English unit name the\n// shared addUnits() helper expects. Each language contributes its own\n// regex alternation of unit words; this function normalizes the\n// captured word back to a unit enum value.\nfunction unitWordToEnglish(word: string): 'day' | 'week' | 'month' | 'year' {\n const w = normalizeForMatch(word);\n // English\n /* c8 ignore next */\n if (w === 'day' || w === 'week' || w === 'month' || w === 'year') return w;\n // Spanish (accent-stripped)\n if (w === 'dia') return 'day';\n if (w === 'semana') return 'week';\n if (w === 'mes') return 'month';\n if (w === 'ano' || w === 'año') return 'year';\n // French\n if (w === 'jour') return 'day';\n if (w === 'semaine') return 'week';\n if (w === 'mois') return 'month';\n if (w === 'an' || w === 'annee') return 'year';\n // German\n if (w === 'tag' || w === 'tagen') return 'day';\n if (w === 'woche' || w === 'wochen') return 'week';\n if (w === 'monat' || w === 'monaten') return 'month';\n /* c8 ignore next */\n if (w === 'jahr' || w === 'jahren') return 'year';\n /* c8 ignore start @preserve -- unreachable: every caller passes a word\n * captured by a regex alternation built from exactly these unit-word\n * forms (day/week/month/year across en/es/fr/de), so the branches\n * above already cover every string that can reach this function.\n * Kept as a tripwire for the type checker in case a grammar adds a\n * unit word here without a matching regex update. */\n throw new Error(`temporal-fmt: parseRelative internal error — unrecognized unit word \"${word}\".`);\n /* c8 ignore stop @preserve */\n /* c8 ignore next -- defensive block is unreachable by construction. */\n}\n\n// Reference: kept exported for the unit tests that need it. The other\n// helpers above are not exported since tests only need to drive\n// parseRelative() through the public API + this one constant for the\n// Tuesday-on-Tuesday fixture.\nexport const WEEKDAY_NAMES = ENGLISH_WEEKDAYS;\nexport const MONTH_NAMES = ENGLISH_MONTHS;\n// Exported for the localeVocab-style stub-test pattern in case a future\n// test wants to verify a grammar's name list against Intl's actual\n// output for that locale — same pattern localeVocab.test.js uses to\n// catch a mismatch between what format() produces and what parse()\n// expects.\nexport const SPANISH_MONTH_NAMES = SPANISH_MONTHS;\nexport const FRENCH_MONTH_NAMES = FRENCH_MONTHS;\nexport const GERMAN_MONTH_NAMES = GERMAN_MONTHS;\nexport const SPANISH_WEEKDAY_NAMES = SPANISH_WEEKDAYS;\nexport const FRENCH_WEEKDAY_NAMES = FRENCH_WEEKDAYS;\nexport const GERMAN_WEEKDAY_NAMES = GERMAN_WEEKDAYS;\nvoid WEEKDAY_NAMES;\nvoid MONTH_NAMES;\n\nexport interface ParseRelativeOptions extends FormatOptions {\n /**\n * Opt-in typo tolerance. When the input doesn't match any phrase\n * exactly, retry after correcting individual words (weekday names,\n * month names, and marker words like \"next\"/\"ago\"/\"tomorrow\") that\n * are within a small edit distance of a known word — e.g.\n * \"tommorow\" → \"tomorrow\", \"next tuesady\" → \"next tuesday\". Numbers\n * are never touched.\n *\n * Off by default, matching this library's throw-rather-than-guess\n * philosophy elsewhere (parse()'s `lenient` option is the same shape\n * of opt-in). English only for this option currently — combining\n * `fuzzy: true` with a non-English `locale` throws rather than\n * silently skipping the fuzzy pass.\n *\n * If no correction produces a recognized phrase, throws the same\n * \"doesn't recognize\" error the exact pass would have thrown.\n */\n fuzzy?: boolean;\n}\n\n/**\n * Resolve common relative-date phrases against a reference date,\n * returning a Temporal.PlainDate. Supports English by default, plus\n * Spanish (es), French (fr), and German (de) via the `locale` option.\n *\n * Supported phrase classes (with examples per language):\n *\n * - weekday refs: \"next Tuesday\" / \"el próximo martes\" / \"mardi prochain\" / \"nächsten Dienstag\"\n * - day offsets: \"today\" / \"hoy\" / \"aujourd'hui\" / \"heute\" (and tomorrow/yesterday equivalents)\n * - unit offsets: \"in 3 days\" / \"en 3 días\" / \"dans 3 jours\" / \"in 3 Tagen\"\n * - month-day without year: \"March 5th\" / \"5 de marzo\" / \"5 mars\" / \"5. März\"\n *\n * Ambiguous-case handling is consistent across all four languages:\n * \"next X\" said on X (today is the named weekday) means 7 days from\n * now, not today. \"last X\" said on X means 7 days ago. See README\n * \"parseRelative\" for the documented behavior of each ambiguous case.\n *\n * Throws a descriptive error for any phrase it doesn't recognize in\n * the target language, rather than guessing. A bare \"5 days\" without\n * \"in\" or \"ago\" (or the per-language equivalent) throws with a message\n * pointing at the disambiguation options.\n *\n * Returns a Temporal.PlainDate for every supported phrase. Time-of-day\n * extensions like \"next Tuesday at 3pm\" aren't supported in this pass.\n */\nexport function parseRelative(\n input: string,\n referenceDate: unknown,\n options: ParseRelativeOptions = {},\n): unknown {\n const reference = referenceDate as TemporalFieldBag;\n const temporal = getTemporal();\n\n // Trim, collapse internal whitespace, strip diacritics, and lowercase.\n // Whitespace normalization is shared with the pre-change behavior;\n // diacritic stripping pairs with nameAlternation()'s normalization so\n // \"mi[eé]rcoles\" and \"miercoles\" both match the same pattern.\n // Lowercasing matches the case-insensitive regex flag explicitly so\n // the user's input never gets case-swapped on its way through the\n // matcher (the regexes are 'i'-flagged, but normalizing here keeps\n // the original-trimmed-string echo in error messages predictable).\n const trimmed = (input ?? '').trim().replace(/\\s+/g, ' ');\n if (trimmed.length === 0) {\n throw new Error('temporal-fmt: parseRelative got an empty input string.');\n }\n if (trimmed.length > MAX_RELATIVE_INPUT_LENGTH) {\n throw new RangeError(\n `temporal-fmt: parseRelative input is too large (maximum ${MAX_RELATIVE_INPUT_LENGTH} characters).`,\n );\n }\n // For error messages, keep the user's original spelling (with accents)\n // so the echo in the \"doesn't recognize\" error matches what they\n // typed. The matching itself uses the diacritic-stripped form so\n // \"mi[eé]rcoles\" / \"miercoles\" / \"MI[ÉE]RCOLES\" all match the same\n // pattern without forcing the user to remember the accent.\n const normalized = normalizeForMatch(trimmed);\n\n const grammar = grammarForLocale(options.locale);\n const ctx: ResolveContext = { temporal, reference };\n\n // Registered grammars (registerRelativeGrammar) take precedence over\n // the built-in ones for their language — that's the documented\n // contract in relativeGrammar.ts (\"try registered grammars before\n // falling back to the built-in ones\"). This wiring was missing\n // entirely before: registered grammars were stored and listed but\n // never consulted, so the extension point silently did nothing.\n // Returns null quickly when nothing is registered for the language.\n const registered = tryRegisteredGrammar(languageOf(options.locale), trimmed, {\n year: reference.year as number,\n month: reference.month as number,\n day: reference.day as number,\n dayOfWeek: reference.dayOfWeek as number,\n });\n if (registered !== null) {\n return registered;\n }\n\n const tryMatch = (text: string): unknown | typeof NO_MATCH => {\n for (const matcher of grammar.matchers) {\n const match = text.match(matcher.pattern);\n if (match) {\n return matcher.resolve(match, ctx);\n }\n }\n return NO_MATCH;\n };\n\n const exactResult = tryMatch(normalized);\n if (exactResult !== NO_MATCH) {\n return exactResult;\n }\n\n if (options.fuzzy) {\n // Fuzzy mode is English-only for this pass — see the vocabulary\n // comment above fuzzyCorrectEnglish for why the other three\n // grammars aren't covered. Fail loudly rather than silently\n // skipping the fuzzy attempt, so a caller relying on fuzzy mode\n // for, say, French input doesn't get a confusing \"doesn't\n // recognize\" error with no indication fuzzy matching never ran.\n if (grammar !== ENGLISH_GRAMMAR) {\n throw new Error(\n `temporal-fmt: parseRelative's { fuzzy: true } option currently only supports English. ` +\n `Pass no locale (or locale: 'en'), or omit { fuzzy: true } for this locale.`\n );\n }\n const corrected = fuzzyCorrectEnglish(normalized);\n if (corrected !== undefined) {\n const fuzzyResult = tryMatch(corrected);\n if (fuzzyResult !== NO_MATCH) {\n return fuzzyResult;\n }\n }\n }\n\n throw new Error(\n `temporal-fmt: parseRelative doesn't recognize \"${trimmed}\". ` +\n grammar.supportedHint\n );\n}\n\n// Sentinel distinguishing \"no matcher matched\" from a legitimate\n// resolve() return value of `undefined`/`null` (matchers can throw\n// their own errors, e.g. the ambiguous-direction case, but none\n// currently return a nullish PlainDate — this sentinel just makes the\n// \"no match\" case unambiguous regardless).\nconst NO_MATCH = Symbol('temporal-fmt: parseRelative no match');\n\n// DEFAULT_LOCALE is imported for the option's default-value documentation\n// above (no locale → English). The symbol itself isn't read at runtime\n// here, but the import keeps the dependency edge explicit so future\n// changes to the default-locale constant propagate here too.\nvoid DEFAULT_LOCALE;","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// central config stuff. per-call options is the convention we use\n// everywhere else in this lib (formatDistance's cutoffs did it this way\n// first — deliberately NOT a global). so this module just gives callers\n// a typed config object they can build once and pass around, defaults\n// match whatever the per-call defaults already were.\n//\n// no global mutable state, on purpose. don't want a setConfig() anywhere —\n// createConfig() just hands back a frozen object and that's it.\n\nimport { DEFAULT_LOCALE } from './tokens.js';\nimport type { NumberingSystemOption } from './numbering.js';\n\nexport interface TemporalFmtConfig {\n // BCP-47 tag, defaults to 'en-US'\n locale: string;\n // 'gregory', 'hebrew', whatever — leave undefined and it'll just use\n // whatever the locale defaults to\n calendar?: string;\n // IANA id like 'America/New_York', or leave it undefined for system tz\n timezone?: string;\n // defaults to 'latn'. 'auto' is accepted too — resolved per call from\n // the effective locale via Intl (see numbering.ts), so one config can\n // drive different digits per locale instead of pinning a single system\n numberingSystem: NumberingSystemOption;\n // 1 = Monday, 7 = Sunday. default's 1, matches what isoWeek.ts already does\n firstDayOfWeek: 1 | 7;\n // for round()/roundDuration(), defaults to 'nearest'\n roundingMode: 'nearest' | 'floor' | 'ceil' | 'trunc';\n // what to do when a ZonedDateTime construction hits a gap/overlap.\n // defaults to 'compatible' since that's Temporal's own default too\n disambiguation: 'compatible' | 'earlier' | 'later' | 'reject';\n // handles stuff like Feb 30 when building fields. defaults to 'reject',\n // same as what parse() already did before this existed\n overflow: 'constrain' | 'reject';\n // strict by default (false)\n parseLenient: boolean;\n // false by default so zero values just get omitted, not printed\n durationShowZeroValues: boolean;\n}\n\nexport const DEFAULT_CONFIG: Readonly<TemporalFmtConfig> = Object.freeze({\n locale: DEFAULT_LOCALE,\n numberingSystem: 'latn',\n firstDayOfWeek: 1,\n roundingMode: 'nearest',\n disambiguation: 'compatible',\n overflow: 'reject',\n parseLenient: false,\n durationShowZeroValues: false,\n});\n// Frozen: this is exported shared module state, and the module's own\n// header promises \"no global mutable state\" — but DEFAULT_CONFIG was\n// assignable, so one import site writing DEFAULT_CONFIG.locale = 'fr-FR'\n// changed what every subsequent createConfig() in the process returned.\n// Spread ({...DEFAULT_CONFIG}) still makes un-frozen copies wherever\n// defaults feed a merge, so freezing costs nothing.\n\n// merges whatever overrides get passed in on top of the defaults, then\n// freezes it so nobody can mutate it after — Temporal's own options\n// work this way too so figured we'd match that\nexport function createConfig(overrides: Partial<TemporalFmtConfig> = {}): Readonly<TemporalFmtConfig> {\n const merged: TemporalFmtConfig = { ...DEFAULT_CONFIG, ...overrides };\n // sanity checks before we freeze it\n if (typeof merged.locale !== 'string' || merged.locale.length === 0) {\n throw new Error(`temporal-fmt: config.locale must be a non-empty string (got ${String(merged.locale)}).`);\n }\n if (merged.numberingSystem !== undefined && typeof merged.numberingSystem !== 'string') {\n throw new Error(`temporal-fmt: config.numberingSystem must be a string (got ${String(merged.numberingSystem)}).`);\n }\n if (merged.firstDayOfWeek !== 1 && merged.firstDayOfWeek !== 7) {\n throw new Error(`temporal-fmt: config.firstDayOfWeek must be 1 (Monday) or 7 (Sunday) (got ${merged.firstDayOfWeek}).`);\n }\n if (!['nearest', 'floor', 'ceil', 'trunc'].includes(merged.roundingMode)) {\n throw new Error(`temporal-fmt: config.roundingMode \"${merged.roundingMode}\" is not recognized.`);\n }\n if (!['compatible', 'earlier', 'later', 'reject'].includes(merged.disambiguation)) {\n throw new Error(`temporal-fmt: config.disambiguation \"${merged.disambiguation}\" is not recognized.`);\n }\n if (!['constrain', 'reject'].includes(merged.overflow)) {\n throw new Error(`temporal-fmt: config.overflow \"${merged.overflow}\" is not recognized.`);\n }\n return Object.freeze(merged);\n}\n\n// merges a config into per-call options — whatever's already set in\n// per-call wins. format()/parse()/etc use this to fold config in\ninterface ConfigOverrides {\n locale?: string;\n calendar?: string;\n timezone?: string;\n numberingSystem?: string;\n lenient?: boolean;\n}\n\nexport function mergeWithConfig<T extends Record<string, unknown>>(\n config: Readonly<TemporalFmtConfig> | undefined,\n perCall: T,\n): Record<string, unknown> & ConfigOverrides {\n if (!config) return perCall;\n // Returns a fresh object typed by its own actual shape (perCall's\n // fields plus these five, each optionally overridden) instead of\n // asserting the result back into the generic T. A `{ ...perCall } as T\n // & {...}` cast here previously claimed a freshly spread object was\n // still exactly T, which isn't something a spread can guarantee for an\n // arbitrary caller-supplied T — tsc rightly rejected that once this\n // generic got exercised through a real call site. Nothing in this codebase\n // currently calls mergeWithConfig and relies on getting T back rather than this\n // wider shape, so there's no correctness cost to being honest about\n // what's actually returned.\n const extras: ConfigOverrides = {};\n if (perCall.locale === undefined) extras.locale = config.locale;\n if (perCall.calendar === undefined && config.calendar !== undefined) extras.calendar = config.calendar;\n if (perCall.timezone === undefined && config.timezone !== undefined) extras.timezone = config.timezone;\n if (perCall.numberingSystem === undefined) extras.numberingSystem = config.numberingSystem;\n if (perCall.lenient === undefined && config.parseLenient) extras.lenient = true;\n return { ...perCall, ...extras };\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// business calendar stuff — configurable weekends, holiday sets, observed\n// holidays, working hours, half days if you need em. holiday checking\n// itself is handed off to a HolidayCalendar (holidays.ts) so this file\n// can just worry about the weekday-vs-weekend part\n\nimport { add } from './arithmetic.js';\nimport { dayOfWeekFromCivil } from './isoWeek.js';\nimport type { HolidayCalendar } from './holidays.js';\n\nexport interface BusinessCalendarOptions {\n // defaults to [6, 7] (Sat/Sun). ISO weekday numbers, 1-7\n weekend?: number[];\n // pass a holiday calendar if you want holidays factored in too —\n // skip it and you just get weekend logic\n holidays?: HolidayCalendar;\n // hours per weekday, 1=Mon..7=Sun. defaults to 8hrs weekdays, 0 weekend.\n // addBusinessDays() uses this for partial-day math\n workingHours?: Record<number, number>;\n // which weekdays get reduced hours. empty by default\n halfDays?: number[];\n}\n\nexport interface BusinessCalendar {\n weekend: Set<number>;\n holidays?: HolidayCalendar;\n workingHours: Record<number, number>;\n halfDays: Set<number>;\n}\n\nexport function createBusinessCalendar(options: BusinessCalendarOptions = {}): BusinessCalendar {\n const weekend = new Set(options.weekend ?? [6, 7]);\n // gotta copy this before filling in defaults — used to write the missing\n // weekday entries straight into options.workingHours, which mutated\n // the caller's actual object. so someone's { 1: 6 } would silently grow\n // keys 2-7 just from \"creating\" a calendar, and if they reused that\n // object across calendars, the first one's defaults leaked into all of them\n const workingHours: Record<number, number> = { ...(options.workingHours ?? {}) };\n for (let i = 1; i <= 7; i++) {\n if (workingHours[i] === undefined) {\n workingHours[i] = weekend.has(i) ? 0 : 8;\n }\n }\n return {\n weekend,\n holidays: options.holidays,\n workingHours,\n halfDays: new Set(options.halfDays ?? []),\n };\n}\n\nexport function isBusinessDay(cal: BusinessCalendar, value: unknown): boolean {\n const v = value as { dayOfWeek?: number; year?: number; month?: number; day?: number };\n // add() over in arithmetic.ts doesn't touch dayOfWeek — it just hands back\n // whatever dayOfWeek the input had, stale or not. so recompute it from\n // year/month/day whenever we've got those, don't trust the cached value\n let dow = v.dayOfWeek;\n if (typeof v.year === 'number' && typeof v.month === 'number' && typeof v.day === 'number') {\n // dayOfWeekFromCivil: O(1) proleptic-Gregorian weekday. The old\n // Date.UTC remapping of years 0-99 to 1900-1999 made a genuine\n // Sunday PlainDate('0050-01-02') count as a business day here —\n // and this recomputation OVERWRITES the value's own correct\n // dayOfWeek, so real Temporal input was affected too.\n dow = dayOfWeekFromCivil(v.year, v.month, v.day);\n }\n if (typeof dow !== 'number') {\n throw new Error('temporal-fmt: isBusinessDay() needs a value with dayOfWeek (or year/month/day to compute it).');\n }\n if (cal.weekend.has(dow)) return false;\n if (cal.holidays && cal.holidays.isHoliday(value)) return false;\n return true;\n}\n\nexport function nextBusinessDay(cal: BusinessCalendar, value: unknown): unknown {\n let candidate = add(value, 1, 'days');\n // keep going till we hit a business day. capped at 14 just to be safe —\n // a week is really the natural bound even with weekend + holidays combined\n for (let i = 0; i < 14; i++) {\n if (isBusinessDay(cal, candidate)) return candidate;\n candidate = add(candidate, 1, 'days');\n }\n throw new Error('temporal-fmt: nextBusinessDay() gave up after 14 days — likely a misconfigured calendar (e.g. all days are weekends or holidays).');\n}\n\nexport function previousBusinessDay(cal: BusinessCalendar, value: unknown): unknown {\n let candidate = add(value, -1, 'days');\n for (let i = 0; i < 14; i++) {\n if (isBusinessDay(cal, candidate)) return candidate;\n candidate = add(candidate, -1, 'days');\n }\n throw new Error('temporal-fmt: previousBusinessDay() gave up after 14 days — likely a misconfigured calendar.');\n}\n\nconst MAX_BUSINESS_DAY_TRAVERSAL = 100_000;\n\nfunction assertBusinessDayCount(days: number): void {\n if (!Number.isSafeInteger(days)) {\n throw new RangeError(\n `temporal-fmt: business-day count must be a finite safe integer (got ${days}).`,\n );\n }\n}\n\nfunction compareDateFields(a: unknown, b: unknown): number {\n const av = a as { year: number; month: number; day: number };\n const bv = b as { year: number; month: number; day: number };\n const ay = av.year * 10000 + av.month * 100 + av.day;\n const by = bv.year * 10000 + bv.month * 100 + bv.day;\n return ay - by;\n}\n\nexport function addBusinessDays(cal: BusinessCalendar, value: unknown, days: number): unknown {\n assertBusinessDayCount(days);\n if (days === 0) return value;\n const sign = days > 0 ? 1 : -1;\n const absDays = Math.abs(days);\n if (absDays > MAX_BUSINESS_DAY_TRAVERSAL) {\n throw new RangeError(\n `temporal-fmt: addBusinessDays() exceeded the ${MAX_BUSINESS_DAY_TRAVERSAL}-day limit.`,\n );\n }\n let candidate = value;\n for (let i = 0; i < absDays; i++) {\n candidate = sign > 0 ? nextBusinessDay(cal, candidate) : previousBusinessDay(cal, candidate);\n }\n return candidate;\n}\n\nexport function subtractBusinessDays(cal: BusinessCalendar, value: unknown, days: number): unknown {\n assertBusinessDayCount(days);\n return addBusinessDays(cal, value, -days);\n}\n\nexport function differenceInBusinessDays(cal: BusinessCalendar, a: unknown, b: unknown): number {\n const rawDirection = compareDateFields(b, a);\n if (rawDirection === 0) return 0;\n\n const direction = rawDirection > 0 ? 1 : -1;\n let candidate = a;\n let count = 0;\n let traversedDays = 0;\n\n while (compareDateFields(candidate, b) !== 0) {\n candidate = add(candidate, direction, 'days');\n traversedDays++;\n if (traversedDays > MAX_BUSINESS_DAY_TRAVERSAL) {\n throw new RangeError(\n `temporal-fmt: differenceInBusinessDays() exceeded the ${MAX_BUSINESS_DAY_TRAVERSAL}-day traversal limit.`,\n );\n }\n if (isBusinessDay(cal, candidate)) count += direction;\n }\n\n return count;\n}\n","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// holiday framework. core just gives you the abstraction — actual\n// country-specific holiday lists live outside this package, could be\n// their own ecosystem packages built on top. a holiday calendar is\n// basically a date -> boolean function (\"is this a holiday\") plus some\n// iteration helpers (nextHoliday, previousHoliday, holidaysBetween)\n\nimport { add } from './arithmetic.js';\nimport { compare } from './comparison.js';\n\nexport interface HolidayCalendar {\n isHoliday(value: unknown): boolean;\n // everything in [start, end], inclusive on both ends\n holidaysBetween(start: unknown, end: unknown): unknown[];\n}\n\nexport interface HolidaySpec {\n // for fixed-date holidays, like Jan 1 for New Year's\n month?: number;\n day?: number;\n // for the floating ones — give it a year, get back { month, day } for\n // that year. this is how you'd do \"last Monday of May\" type rules\n compute?: (year: number) => { month: number; day: number };\n // just a name, mostly for debugging\n name?: string;\n}\n\n// cap on how many years holidaysBetween() will walk through. it's a\n// year-by-year loop with no bounds checking on the inputs, so someone\n// passing year 1 to year 300000 would've made it iterate (and cache!)\n// every single year in between. either an accident or someone being\n// hostile, either way that used to just hang the process. 5000 matches\n// the same walk-cap businessCalendar.ts and recurrence.ts already use\nconst MAX_HOLIDAY_YEAR_RANGE = 5_000;\n\nexport function createHolidayCalendar(specs: HolidaySpec[]): HolidayCalendar {\n // computes a year's holiday list lazily, then caches it\n const cache = new Map<number, Array<{ month: number; day: number; name?: string }>>();\n // The per-instance cache never evicted: isHoliday/nextHoliday/\n // previousHoliday over N distinct years grew N entries forever (a\n // calendar asked for many years — hostile or just long-lived — held\n // every year's list in memory permanently). FIFO-evict past the cap,\n // same convention as the library's other bounded caches. Rebuilding\n // an evicted year is O(specs), which is the same cost the first\n // computation already paid.\n const MAX_CACHE_YEARS = 1000;\n function forYear(year: number) {\n let list = cache.get(year);\n if (list) return list;\n if (cache.size >= MAX_CACHE_YEARS) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) cache.delete(oldest);\n }\n list = specs.map((s) => {\n let md: { month: number; day: number };\n if (s.compute) {\n md = s.compute(year);\n } else {\n md = { month: s.month!, day: s.day! };\n }\n return { ...md, name: s.name };\n });\n cache.set(year, list);\n return list;\n }\n return {\n isHoliday(value: unknown) {\n const v = value as { year?: number; month?: number; day?: number };\n if (typeof v.year !== 'number' || typeof v.month !== 'number' || typeof v.day !== 'number') {\n throw new Error('temporal-fmt: isHoliday() needs a value with year/month/day.');\n }\n const list = forYear(v.year);\n return list.some((h) => h.month === v.month && h.day === v.day);\n },\n holidaysBetween(start: unknown, end: unknown) {\n const sv = start as { year: number; month: number; day: number };\n const ev = end as { year: number; month: number; day: number };\n if (typeof sv?.year !== 'number' || typeof ev?.year !== 'number') {\n throw new Error('temporal-fmt: holidaysBetween() needs start/end values with year/month/day.');\n }\n if (ev.year - sv.year > MAX_HOLIDAY_YEAR_RANGE) {\n throw new RangeError(\n `temporal-fmt: holidaysBetween() year range (${sv.year}–${ev.year}) exceeds the ` +\n `${MAX_HOLIDAY_YEAR_RANGE}-year limit. Split the query into smaller ranges.`\n );\n }\n const result: unknown[] = [];\n for (let y = sv.year; y <= ev.year; y++) {\n const list = forYear(y);\n for (const h of list) {\n const date = { year: y, month: h.month, day: h.day };\n if (compare(date, sv) >= 0 && compare(date, ev) <= 0) {\n result.push({ year: y, month: h.month, day: h.day });\n }\n }\n }\n return result;\n },\n };\n}\n\n// finds the next holiday strictly after `value`. gives up and returns\n// undefined if nothing shows up within 5 years — sanity cap so this\n// can't loop forever on an empty calendar\nexport function nextHoliday(cal: HolidayCalendar, value: unknown): unknown | undefined {\n let candidate = add(value, 1, 'days');\n for (let i = 0; i < 365 * 5; i++) {\n if (cal.isHoliday(candidate)) return candidate;\n candidate = add(candidate, 1, 'days');\n }\n return undefined;\n}\n\nexport function previousHoliday(cal: HolidayCalendar, value: unknown): unknown | undefined {\n let candidate = add(value, -1, 'days');\n for (let i = 0; i < 365 * 5; i++) {\n if (cal.isHoliday(candidate)) return candidate;\n candidate = add(candidate, -1, 'days');\n }\n return undefined;\n}\n\n// holidaysBetween already exists as a method on HolidayCalendar (above),\n// this is just a standalone version so you don't have to type cal.holidaysBetween\nexport function holidaysBetween(cal: HolidayCalendar, start: unknown, end: unknown): unknown[] {\n return cal.holidaysBetween(start, end);\n}\n","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Extensibility. Controlled extensibility via\n// createFormatter({ tokens: ... }) rather than uncontrolled global\n// mutation. Custom tokens are passed at formatter-creation time;\n// built-in behavior stays deterministic regardless of what's registered.\n//\n// The existing registerLocaleVocab() is a global-registration escape\n// hatch for the locale-vocabulary case; createFormatter is the\n// per-formatter alternative for custom tokens.\n\nimport { type FormattedPart, type CompiledFormat } from './format.js';\nimport { TOKENS, type TemporalLike, type FormatOptions, DEFAULT_LOCALE } from './tokens.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\nimport { UnknownTokenError } from './errors.js';\n\nexport type TokenHandler = (t: TemporalLike, locale: string) => string;\nexport type TokenField = keyof TemporalLike;\n\nexport interface CustomToken {\n name: string;\n handler: TokenHandler;\n field: TokenField;\n}\n\nexport interface FormatterOptions {\n // Custom tokens to add (or override). Built-in tokens with the same\n // name are replaced by the custom one.\n tokens?: CustomToken[];\n // Default locale for this formatter. Callers can still override per-call.\n defaultLocale?: string;\n}\n\nexport interface Formatter {\n format(temporal: TemporalLike, formatStr: string, options?: FormatOptions): string;\n formatToParts(temporal: TemporalLike, formatStr: string, options?: FormatOptions): FormattedPart[];\n compileFormat(formatStr: string): CompiledFormat;\n}\n\nexport function createFormatter(options: FormatterOptions = {}): Formatter {\n // Build a merged token table: built-ins plus overrides.\n const mergedTokens: Array<[string, TokenHandler, TokenField]> = [...TOKENS];\n const customTokenNames = new Set<string>();\n for (const custom of options.tokens ?? []) {\n customTokenNames.add(custom.name);\n }\n // Replace existing tokens with the same name; append new ones.\n for (const custom of options.tokens ?? []) {\n const existingIdx = mergedTokens.findIndex(([name]) => name === custom.name);\n if (existingIdx >= 0) {\n mergedTokens[existingIdx] = [custom.name, custom.handler, custom.field];\n } else {\n mergedTokens.push([custom.name, custom.handler, custom.field]);\n }\n }\n // Sort longest-first for the greedy tokenizer.\n mergedTokens.sort((a, b) => b[0].length - a[0].length);\n const handlerByToken = new Map(mergedTokens.map(([name, handler, field]) => [name, { handler, field }]));\n const sortedTokenStrings = mergedTokens.map(([name]) => name);\n\n function customTokenize(formatStr: string) {\n const pieces: Array<{ kind: 'token' | 'literal'; value: string }> = [];\n let i = 0;\n while (i < formatStr.length) {\n const ch = formatStr[i];\n if (ch === \"'\") {\n // Quoted literal handling — same as tokenize.ts.\n if (formatStr[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\n }\n let j = i + 1;\n let literal = '';\n let closed = false;\n while (j < formatStr.length) {\n if (formatStr[j] === \"'\") {\n if (formatStr[j + 1] === \"'\") {\n literal += \"'\";\n j += 2;\n continue;\n }\n closed = true;\n j += 1;\n break;\n }\n literal += formatStr[j]!;\n j += 1;\n }\n if (!closed) throw new Error(`temporal-fmt: unterminated quote in format string \"${formatStr}\"`);\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n const match = sortedTokenStrings.find((tok) => formatStr.startsWith(tok, i));\n if (match) {\n // Overlong-run guard, same rule as tokenize.ts: a greedy match of N\n // chars followed by one more of the same letter (\"MMMMM\", \"ddddd\")\n // is not a valid token of any width — emitting it as \"token +\n // literal\" would silently splice an unrelated field onto this one,\n // exactly the misreading the main tokenizer rejects. Same\n // UnknownTokenError shape tokenize.ts throws.\n const runChar = match[match.length - 1];\n if (formatStr[i + match.length] === runChar) {\n let end = i + match.length;\n while (formatStr[end] === runChar) end += 1;\n throw new UnknownTokenError({\n token: formatStr.slice(i, end),\n format: formatStr,\n message:\n `temporal-fmt: \"${formatStr.slice(i, end)}\" in format string \"${formatStr}\" isn't a recognized token — ` +\n `did you mean \"${match}\"?`,\n });\n }\n pieces.push({ kind: 'token', value: match });\n i += match.length;\n continue;\n }\n appendLiteral(pieces, ch);\n i += 1;\n }\n return pieces;\n }\n\n function appendLiteral(pieces: Array<{ kind: 'token' | 'literal'; value: string }>, value: string): void {\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += value;\n } else {\n pieces.push({ kind: 'literal', value });\n }\n }\n\n const defaultLocale = options.defaultLocale ?? DEFAULT_LOCALE;\n\n return {\n format(temporal: TemporalLike, formatStr: string, opts: FormatOptions = {}) {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(`temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters (got ${formatStr.length}).`);\n }\n const locale = opts.locale ?? defaultLocale;\n const pieces = customTokenize(formatStr);\n let result = '';\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n result += piece.value;\n continue;\n }\n const handler = handlerByToken.get(piece.value);\n /* c8 ignore start @preserve -- unreachable: customTokenize only ever produces a\n `kind: 'token'` piece via sortedTokenStrings.find(...), and\n handlerByToken is built from that same mergedTokens array, so\n every token piece is guaranteed a handler entry. Guards against a\n future customTokenize change that decouples the two lookups. */\n if (!handler) throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n /* c8 ignore stop @preserve */\n if (temporal[handler.field] === undefined) {\n throw new Error(\n `temporal-fmt: token \"${piece.value}\" requires \"${String(handler.field)}\", which this Temporal object doesn't have.`\n );\n }\n result += handler.handler(temporal, locale);\n }\n return result;\n },\n formatToParts(temporal: TemporalLike, formatStr: string, opts: FormatOptions = {}) {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(`temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters (got ${formatStr.length}).`);\n }\n const locale = opts.locale ?? defaultLocale;\n const pieces = customTokenize(formatStr);\n const out: FormattedPart[] = [];\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n const last = out[out.length - 1];\n /* c8 ignore start @preserve -- unreachable: customTokenize's own\n appendLiteral() already merges adjacent literal chars/quoted\n spans into a single piece before this loop ever sees them, so\n two literal pieces are never adjacent here. Kept as a guard\n against a future customTokenize change that stops merging. */\n if (last && last.type === 'literal') last.value += piece.value;\n /* c8 ignore stop @preserve */\n else out.push({ type: 'literal', value: piece.value });\n continue;\n }\n const handler = handlerByToken.get(piece.value);\n /* c8 ignore start @preserve -- unreachable: customTokenize only emits\n kind:'token' pieces found in sortedTokenStrings, the same array\n handlerByToken is built from, so every token piece is guaranteed\n a handler entry. Guards against future decoupling of the two. */\n if (!handler) throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n /* c8 ignore stop @preserve */\n if (temporal[handler.field] === undefined) {\n throw new Error(`temporal-fmt: token \"${piece.value}\" requires \"${String(handler.field)}\".`);\n }\n out.push({ type: 'token', value: handler.handler(temporal, locale), token: piece.value });\n }\n return out;\n },\n compileFormat(formatStr: string): CompiledFormat {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(`temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters (got ${formatStr.length}).`);\n }\n const pieces = customTokenize(formatStr);\n return {\n formatStr,\n pieces: pieces.map((p) => p as { kind: 'token' | 'literal'; value: string }),\n format(temporal: TemporalLike, opts: FormatOptions = {}) {\n const locale = opts.locale ?? defaultLocale;\n let result = '';\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n result += piece.value;\n continue;\n }\n const handler = handlerByToken.get(piece.value);\n /* c8 ignore start @preserve -- unreachable, see the same guard's comment\n above in the un-compiled format(). */\n if (!handler) throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n /* c8 ignore stop @preserve */\n if (temporal[handler.field] === undefined) {\n throw new Error(`temporal-fmt: token \"${piece.value}\" requires \"${String(handler.field)}\".`);\n }\n result += handler.handler(temporal, locale);\n }\n return result;\n },\n formatToParts(temporal: TemporalLike, opts: FormatOptions = {}) {\n const locale = opts.locale ?? defaultLocale;\n const out: FormattedPart[] = [];\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n const last = out[out.length - 1];\n /* c8 ignore start @preserve -- unreachable, see the same guard's\n comment above in the un-compiled formatToParts. */\n if (last && last.type === 'literal') last.value += piece.value;\n /* c8 ignore stop @preserve */\n else out.push({ type: 'literal', value: piece.value });\n continue;\n }\n const handler = handlerByToken.get(piece.value);\n /* c8 ignore start @preserve -- unreachable, see the same guard's\n comment above in the un-compiled formatToParts. */\n if (!handler) throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n /* c8 ignore stop @preserve */\n if (temporal[handler.field] === undefined) {\n throw new Error(`temporal-fmt: token \"${piece.value}\" requires \"${String(handler.field)}\".`);\n }\n out.push({ type: 'token', value: handler.handler(temporal, locale), token: piece.value });\n }\n return out;\n },\n };\n },\n };\n}\n\n","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// IDE tooling data exports. Provides structured data editor plugins can\n// consume for: token autocomplete, hover docs, inline diagnostics,\n// quick fixes, format preview, token conversion hints from\n// Day.js/date-fns, documentation links.\n//\n// This is the data layer only — an actual VS Code extension is out of\n// scope for this package. A separate package can build the extension\n// on top of these exports.\n\nimport { TOKEN_METADATA, ALL_TOKEN_NAMES } from './tokenMetadata.js';\nimport { analyzeFormat, listTokens } from './analyze.js';\nimport { format as builtinFormat } from './format.js';\nimport { getTemporal } from './temporalProvider.js';\n\nexport interface TokenAutocompleteEntry {\n label: string;\n detail: string;\n documentation: string;\n // Sort group — same-family tokens sort together in the autocomplete list.\n family: string;\n}\n\n// Token family grouping for autocomplete organization: year, month,\n// day, etc.\nfunction tokenFamily(name: string): string {\n if (/^y+$/.test(name)) return 'Year';\n if (/^[ML]+$/.test(name)) return 'Month';\n if (/^[decD]+$/.test(name)) return 'Day';\n if (/^[Ec]+$/.test(name)) return 'Weekday';\n if (/^[Qq]+$/.test(name)) return 'Quarter';\n if (/^[Gg]+$/.test(name)) return 'Era';\n if (/^[Hh]+$/.test(name)) return 'Hour';\n if (/^m+$/.test(name)) return 'Minute';\n if (/^s+$/.test(name)) return 'Second';\n if (/^S+$/.test(name)) return 'Fractional Second';\n if (name === 'a') return 'Day Period';\n // z/zzz/zzzz are all zone tokens — only exact 'zzz' used to be\n // special-cased, leaving 'z' and 'zzzz' filed under 'Other'.\n if (name === 'z' || name === 'zzz' || name === 'zzzz') return 'Time Zone';\n if (/^[Xx]+$/.test(name)) return 'UTC Offset';\n if (name === 'do') return 'Ordinal Day';\n // Unreachable with the current token set: every name in ALL_TOKEN_NAMES\n // (the only input — see getAutocompleteData) matches a family above, so\n // the fall-through below only exists as the catch-all for tokens added\n // in the future. The first ignored line is the ww/RRRR if, whose V8\n // fall-through block remaps onto it; the second is the return itself;\n // the third is the function's implicit end-of-body statement.\n /* c8 ignore next 3 @preserve */\n if (name === 'ww' || name === 'RRRR') return 'ISO Week';\n return 'Other';\n}\n\nexport function getAutocompleteData(): TokenAutocompleteEntry[] {\n return ALL_TOKEN_NAMES.map((name) => {\n const meta = TOKEN_METADATA[name]!;\n return {\n label: name,\n detail: meta.meaning,\n documentation: [\n meta.meaning,\n ``,\n `Format-capable: ${meta.formatCapable}`,\n `Parse-capable: ${meta.parseCapable}`,\n `Locale-sensitive: ${meta.localeSensitive}`,\n `Calendar-sensitive: ${meta.calendarSensitive}`,\n `Timezone-sensitive: ${meta.timezoneSensitive}`,\n `Round-trip safe: ${meta.roundTripSafe}`,\n `Supported types: ${meta.supportedTypes.join(', ')}`,\n ].join('\\n'),\n family: tokenFamily(name),\n };\n });\n}\n\nexport interface TokenHoverDoc {\n signature: string;\n summary: string;\n details: string;\n examples?: string[];\n}\n\nexport function getHoverDocs(): Record<string, TokenHoverDoc> {\n const result: Record<string, TokenHoverDoc> = {};\n for (const name of ALL_TOKEN_NAMES) {\n const meta = TOKEN_METADATA[name]!;\n result[name] = {\n signature: name,\n summary: meta.meaning,\n details: [\n // every entry in TOKEN_METADATA currently has formatCapable:\n // true (verified: 51/51). The 'no' branch reflects real,\n // intended behavior for a future format-incapable token —\n // there's no such token today, so this isn't reachable data,\n // not dead logic. Every other field on this line has real\n // true/false variance across the token table and is exercised\n // by this same loop running over ALL_TOKEN_NAMES.\n /* c8 ignore next */\n `Format-capable: ${meta.formatCapable ? 'yes' : 'no'}`,\n `Parse-capable: ${meta.parseCapable ? 'yes' : 'no'}`,\n `Locale-sensitive: ${meta.localeSensitive ? 'yes' : 'no'}`,\n `Calendar-sensitive: ${meta.calendarSensitive ? 'yes' : 'no'}`,\n `Timezone-sensitive: ${meta.timezoneSensitive ? 'yes' : 'no'}`,\n `Round-trip safe: ${meta.roundTripSafe ? 'yes' : 'no'}`,\n `Supported types: ${meta.supportedTypes.join(', ')}`,\n ].join('\\n'),\n };\n }\n return result;\n}\n\n// Inline diagnostic data for a format string. Returns a list of issues\n// (warnings + errors) with position + message + suggested fix where\n// available. Mirrors analyzeFormat's warnings but adds the position\n// info an editor needs to draw squigglies.\nexport interface InlineDiagnostic {\n startColumn: number;\n endColumn: number;\n severity: 'error' | 'warning' | 'info';\n message: string;\n code: string;\n // Suggested replacement (for quick-fix). Empty when no quick fix exists.\n suggestion?: string;\n}\n\nexport function getInlineDiagnostics(formatStr: string): InlineDiagnostic[] {\n const analysis = analyzeFormat(formatStr);\n const diagnostics: InlineDiagnostic[] = [];\n for (const warning of analysis.warnings) {\n // Find the token that triggered the warning. analyzeFormat doesn't\n // currently surface which token caused which warning — we'd need\n // to extend it to track per-warning source positions. For now,\n // surface as a whole-string diagnostic.\n let message = warning.message;\n let suggestion: string | undefined;\n if (warning.code === 'TWELVE_HOUR_WITHOUT_A') {\n suggestion = 'Add an \"a\" token (e.g. \"h:mm a\") or use \"H:mm\" for 24-hour.';\n } else if (warning.code === 'MIXED_12_AND_24_HOUR') {\n suggestion = 'Pick one form: \"HH:mm\" for 24-hour or \"h:mm a\" for 12-hour.';\n } else if (warning.code === 'AMBIGUOUS_NUMERIC_RUN') {\n suggestion = 'Add a separator or use padded forms (e.g. \"MM\" instead of \"M\").';\n } else if (warning.code === 'FORMAT_ONLY_TOKEN') {\n suggestion = 'Use a parse-capable variant (e.g. \"d\" instead of \"do\").';\n }\n diagnostics.push({\n startColumn: 0,\n endColumn: formatStr.length,\n severity: 'warning',\n message,\n code: warning.code,\n suggestion,\n });\n }\n return diagnostics;\n}\n\n// Day.js / date-fns token conversion hints. Used by the IDE to suggest\n// the temporal-fmt equivalent when a user types a Day.js or date-fns\n// token. Pulls the translation tables from the codemod if available;\n// falls back to inline tables otherwise.\nexport interface TokenConversionHint {\n from: string;\n // null means \"real token in the source library, no temporal-fmt\n // equivalent\" — the codemod throws on these rather than treating\n // them as unrecognized text (see codemod.ts).\n to: string | null;\n notes?: string;\n}\n\n// Day.js → temporal-fmt mappings. Day.js uses Moment-style tokens:\n// `D`/`DD` are day-of-*month* here (unlike date-fns below, where the\n// same letters mean day-of-year). Assumes the AdvancedFormat plugin\n// for `Do`/`Q`/`k`/`kk`/`X`/`x` — see codemod.ts's doc comment for why.\nexport const DAYJS_TO_TEMPORAL_FMT: TokenConversionHint[] = [\n { from: 'YYYY', to: 'yyyy' },\n { from: 'YY', to: 'yy' },\n { from: 'MMMM', to: 'MMMM' },\n { from: 'MMM', to: 'MMM' },\n { from: 'MM', to: 'MM' },\n { from: 'M', to: 'M' },\n { from: 'DD', to: 'dd' },\n { from: 'D', to: 'd' },\n { from: 'Do', to: null, notes: 'Ordinal day (AdvancedFormat) — use temporal-fmt\\'s own \"do\" token instead.' },\n { from: 'dddd', to: 'EEEE' },\n { from: 'ddd', to: 'EEE' },\n { from: 'dd', to: null, notes: 'Min-name weekday (e.g. \"Tu\") — temporal-fmt has no equivalent width.' },\n { from: 'd', to: null, notes: 'Numeric weekday (0-6) — no temporal-fmt equivalent; not the same as \"d\" here, which is day-of-month.' },\n { from: 'HH', to: 'HH' },\n { from: 'H', to: 'H' },\n { from: 'hh', to: 'hh' },\n { from: 'h', to: 'h' },\n { from: 'kk', to: null, notes: 'Hour 1-24 (AdvancedFormat) — no temporal-fmt equivalent.' },\n { from: 'k', to: null, notes: 'Hour 1-24 (AdvancedFormat) — no temporal-fmt equivalent.' },\n { from: 'mm', to: 'mm' },\n { from: 'm', to: 'm' },\n { from: 'ss', to: 'ss' },\n { from: 's', to: 's' },\n // Fractional seconds: Day.js S/SS/SSS are 1/2/3-digit milliseconds,\n // the same widths temporal-fmt's own S/SS/SSS use. These used to be\n // missing from the table entirely, so \"S\"/\"SS\" silently translated\n // to quoted LITERAL text (translateDayjs('S') → \"'S'\") instead of\n // a token.\n { from: 'SSS', to: 'SSS' },\n { from: 'SS', to: 'SS' },\n { from: 'S', to: 'S' },\n { from: 'A', to: 'a', notes: 'Uppercase AM/PM in Day.js — temporal-fmt is always lowercase.' },\n { from: 'a', to: 'a' },\n { from: 'ZZ', to: 'XX', notes: 'Numeric UTC offset, no colon.' },\n { from: 'Z', to: 'XXX', notes: 'Numeric UTC offset with colon.' },\n { from: 'X', to: null, notes: 'Unix timestamp (seconds) — use fromUnixSeconds() instead.' },\n { from: 'x', to: null, notes: 'Unix timestamp (ms) — use fromUnixMilliseconds() instead.' },\n { from: 'Qo', to: null, notes: 'Ordinal quarter (AdvancedFormat) — no temporal-fmt equivalent.' },\n { from: 'Q', to: 'Q' },\n { from: 'Mo', to: null, notes: 'Ordinal month (AdvancedFormat) — no temporal-fmt equivalent.' },\n // Day.js w/ww are LOCALE-aware weeks (default en locale: week starts\n // Sunday, week 1 contains Jan 1) — not the ISO weeks temporal-fmt's\n // ww computes. Mapping silently would print different week numbers\n // than the source library for the same date (e.g. 2016-01-01: Day.js\n // \"1\" vs temporal-fmt \"53\"), so refuse with a note instead.\n { from: 'ww', to: null, notes: 'Locale-aware week of year — temporal-fmt\\'s \"ww\" is a strict ISO week number and disagrees with Day.js\\'s locale week for the same date. Compute locale weeks separately if needed.' },\n { from: 'wo', to: null, notes: 'Ordinal locale week (AdvancedFormat) — no temporal-fmt equivalent.' },\n { from: 'w', to: null, notes: 'Unpadded locale week of year — see the \"ww\" note; temporal-fmt has only ISO weeks.' },\n { from: 'gg', to: null, notes: 'Two-digit locale week-numbering year — no temporal-fmt equivalent (RRRR is 4-digit ISO).' },\n { from: 'gggg', to: 'RRRR', notes: 'Week-numbering year — mapped, but Day.js\\'s is locale-week-based while RRRR is strict ISO; values can differ at year boundaries.' },\n { from: 'L', to: null, notes: 'Localized date format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LL', to: null, notes: 'Localized date format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LLL', to: null, notes: 'Localized date format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LLLL', to: null, notes: 'Localized date format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LT', to: null, notes: 'Localized time format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LTS', to: null, notes: 'Localized time format (AdvancedFormat) — write the format string out explicitly.' },\n];\n\n// date-fns → temporal-fmt mappings. date-fns already uses Unicode/LDML\n// -style tokens close to temporal-fmt's own vocabulary — most strings\n// pass through unchanged. The catch: `D`/`DD` here mean day-of-*year*\n// (same as temporal-fmt's `D`/`DD`), not day-of-month like Day.js's\n// `D`/`DD` above — don't reuse the Day.js table for this, they collide.\nexport const DATE_FNS_TO_TEMPORAL_FMT: TokenConversionHint[] = [\n { from: 'yyyy', to: 'yyyy' },\n { from: 'yy', to: 'yy' },\n // temporal-fmt HAS an unpadded-year token (\"y\", same as date-fns);\n // this used to map to null and throw even though the token passes\n // straight through.\n { from: 'y', to: 'y', notes: 'Unpadded calendar year, opt-in via useAdditionalWeekYearTokens — temporal-fmt has the same \"y\" token.' },\n { from: 'MMMM', to: 'MMMM' },\n { from: 'MMM', to: 'MMM' },\n { from: 'MM', to: 'MM' },\n { from: 'M', to: 'M' },\n { from: 'LLLL', to: 'LLLL' },\n { from: 'LLL', to: 'LLL' },\n { from: 'dd', to: 'dd' },\n { from: 'd', to: 'd' },\n { from: 'do', to: 'do' },\n { from: 'DDD', to: 'DDD' },\n { from: 'DD', to: 'DD' },\n { from: 'D', to: 'D', notes: 'Day-of-year, opt-in via useAdditionalDayOfYearTokens — matches temporal-fmt\\'s own \"D\" already.' },\n { from: 'EEEE', to: 'EEEE' },\n { from: 'EEE', to: 'EEE' },\n { from: 'eeee', to: null, notes: 'Locale-aware numeric weekday — no temporal-fmt equivalent.' },\n { from: 'cccc', to: 'cccc' },\n { from: 'ccc', to: 'ccc' },\n { from: 'HH', to: 'HH' },\n { from: 'H', to: 'H' },\n { from: 'hh', to: 'hh' },\n { from: 'h', to: 'h' },\n { from: 'mm', to: 'mm' },\n { from: 'm', to: 'm' },\n { from: 'ss', to: 'ss' },\n { from: 's', to: 's' },\n // Fractional seconds, same widths as temporal-fmt's own tokens —\n // used to be missing, silently literalizing \"S\"/\"SS\".\n { from: 'SSS', to: 'SSS' },\n { from: 'SS', to: 'SS' },\n { from: 'S', to: 'S' },\n { from: 'a', to: 'a' },\n { from: 'aaa', to: 'a' },\n { from: 'XXX', to: 'XXX' },\n { from: 'XX', to: 'XX' },\n { from: 'X', to: 'X', notes: 'Opt-in via useAdditionalDayOfYearTokens-adjacent rules in date-fns v3+; matches temporal-fmt\\'s own \"X\" already.' },\n { from: 'xxx', to: 'xxx' },\n { from: 'xx', to: 'xx' },\n { from: 'x', to: 'x' },\n { from: 'zzzz', to: 'zzzz' },\n { from: 'zzz', to: 'zzz' },\n { from: 'z', to: 'z' },\n { from: 'QQQ', to: 'QQQ' },\n { from: 'Q', to: 'Q' },\n { from: 'QQQQ', to: null, notes: 'Long quarter name — temporal-fmt has Q (numeric) and QQQ (\"Q1\"-style) only.' },\n { from: 'Qo', to: null, notes: 'Ordinal quarter — no temporal-fmt equivalent.' },\n { from: 'GGGG', to: 'GGGG' },\n { from: 'GGG', to: null, notes: 'Abbreviated era — temporal-fmt only has \"G\" (short) and \"GGGG\" (long).' },\n { from: 'GG', to: null, notes: 'Abbreviated era — temporal-fmt only has \"G\" (short) and \"GGGG\" (long).' },\n { from: 'G', to: 'G' },\n // date-fns w/ww are LOCAL week rules (en-US: week starts Sunday, week\n // 1 contains Jan 1) — temporal-fmt's ww is strict ISO. Silently\n // mapping prints different numbers than the source library (2016-01-01:\n // date-fns \"01\" vs temporal-fmt \"53\"), so refuse with a note.\n { from: 'ww', to: null, notes: 'Local week of year — temporal-fmt\\'s \"ww\" is a strict ISO week number and disagrees with date-fns\\'s locale week for the same date. Compute locale weeks separately if needed.' },\n { from: 'w', to: null, notes: 'Unpadded local week number — temporal-fmt\\'s \"ww\" is ISO-week and always 2-digit.' },\n { from: 'RRRR', to: 'RRRR' },\n { from: 'R', to: null, notes: 'Unpadded ISO week-numbering year — temporal-fmt\\'s \"RRRR\" is always 4-digit.' },\n { from: 'Y', to: null, notes: 'Week-numbering year (locale week rules), opt-in — no temporal-fmt equivalent; \"RRRR\" is ISO week-numbering, a different rule set.' },\n { from: 'PPPP', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'PPP', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'PP', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'P', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'pppp', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'ppp', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'pp', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'p', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n];\n\n// Format preview — for a given format string and a sample Temporal\n// value, returns the formatted string. Editor plugins use this for\n// live preview as the user types.\nexport function previewFormat(formatStr: string, sample?: unknown): string {\n // Use a fixed sample date if none provided — 2026-08-04T15:45:30,\n // built as a REAL Temporal.PlainDateTime. Picked because it exercises\n // every common token: weekday is Tuesday, month name has 5 chars, day\n // is single-digit, hour is 12-hour-style, minute/second both pad.\n // (A plain field bag used to be passed instead, which can't render\n // locale-aware tokens at all — previewFormat('MMMM d') threw \"needs a\n // value that implements toLocaleString\".)\n let value = sample;\n if (value === undefined) {\n const temporal = getTemporal();\n value = temporal.PlainDateTime.from({\n year: 2026, month: 8, day: 4, hour: 15, minute: 45, second: 30, millisecond: 123,\n });\n }\n return builtinFormat(value as Parameters<typeof builtinFormat>[0], formatStr, { locale: 'en-US' });\n}\n\n// Documentation links. Docs used to live under docs/ as one file per\n// token family; they're now consolidated into the root README's \"Token\n// reference\" section, which has no per-token anchors — so this points\n// at the section instead of a token-specific fragment.\nexport function getDocUrl(tokenName: string): string {\n void tokenName;\n return 'README.md#token-reference';\n}\n\n// Re-exports for callers that want everything IDE-related from one module.\nexport { listTokens, TOKEN_METADATA, ALL_TOKEN_NAMES };","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// translates Day.js / date-fns format strings — this is what backs the\n// CLI's `translate` subcommand. the mapping tables were already sitting\n// in ideData.ts (built for the IDE tooling), so this just builds the\n// actual string translator on top instead of pulling in anything else.\n//\n// heads up: this only handles format *strings* (\"YYYY-MM-DD\" -> \"yyyy-MM-dd\"),\n// not an actual AST codemod that goes and rewrites call sites in your code.\n// that's a bigger separate thing — check temporal-fmt-codemod if that's\n// what you actually need\n\nimport { DAYJS_TO_TEMPORAL_FMT, DATE_FNS_TO_TEMPORAL_FMT, type TokenConversionHint } from './ideData.js';\n\ninterface SourcePiece {\n kind: 'token' | 'literal';\n value: string;\n}\n\n// Day.js and date-fns escape literal text with square brackets — [MM]\n// stays as literal \"MM\" — not single quotes like temporal-fmt does.\n// splitting on brackets first keeps the token scan below from accidentally\n// matching stuff inside an escaped span\nfunction splitOnBrackets(source: string): SourcePiece[] {\n const pieces: SourcePiece[] = [];\n let i = 0;\n while (i < source.length) {\n if (source[i] === '[') {\n const end = source.indexOf(']', i + 1);\n if (end === -1) {\n pieces.push({ kind: 'token', value: source.slice(i) });\n break;\n }\n pieces.push({ kind: 'literal', value: source.slice(i + 1, end) });\n i = end + 1;\n } else {\n let j = i;\n while (j < source.length && source[j] !== '[') j += 1;\n pieces.push({ kind: 'token', value: source.slice(i, j) });\n i = j;\n }\n }\n return pieces;\n}\n\n// splits a non-bracketed span into runs, matching greedy-longest against\n// the known token table — basically the same idea as tokenize.ts, just\n// scanning the SOURCE library's tokens here instead of temporal-fmt's own\nfunction splitIntoRuns(span: string, sortedFrom: string[]): SourcePiece[] {\n const pieces: SourcePiece[] = [];\n let i = 0;\n while (i < span.length) {\n const match = sortedFrom.find((tok) => span.startsWith(tok, i));\n if (match) {\n pieces.push({ kind: 'token', value: match });\n i += match.length;\n continue;\n }\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += span[i];\n } else {\n pieces.push({ kind: 'literal', value: span[i] });\n }\n i += 1;\n }\n return pieces;\n}\n\nfunction translate(source: string, table: TokenConversionHint[], sourceLibLabel: string): string {\n const byFrom = new Map(table.map((hint) => [hint.from, hint.to]));\n const sortedFrom = [...byFrom.keys()].sort((a, b) => b.length - a.length);\n\n const bracketPieces = splitOnBrackets(source);\n let out = '';\n for (const piece of bracketPieces) {\n if (piece.kind === 'literal') {\n // re-escape for temporal-fmt's quote syntax — any literal quote\n // char inside the escaped bit needs doubling up\n out += `'${piece.value.replace(/'/g, \"''\")}'`;\n continue;\n }\n for (const run of splitIntoRuns(piece.value, sortedFrom)) {\n if (run.kind === 'token') {\n const mapped = byFrom.get(run.value);\n if (mapped === undefined || mapped === null) {\n throw new Error(\n `temporal-fmt: \"${run.value}\" has no ${sourceLibLabel} -> temporal-fmt mapping ` +\n `(in format string \"${source}\"). Write the equivalent temporal-fmt token in by hand, ` +\n `or wrap it in brackets if it was meant as literal text.`\n );\n }\n out += mapped;\n } else if (/[a-zA-Z]/.test(run.value)) {\n // can't just let unrecognized letters through as-is — temporal-fmt\n // would read them as its own tokens by accident. gotta quote the run\n out += `'${run.value.replace(/'/g, \"''\")}'`;\n } else {\n out += run.value;\n }\n }\n }\n return out;\n}\n\n/**\n * Translates a Day.js format string to the equivalent temporal-fmt\n * token string.\n *\n * ```js\n * translateDayjsFormatString('YYYY-MM-DD HH:mm:ss'); // \"yyyy-MM-dd HH:mm:ss\"\n * translateDayjsFormatString('[Q]Q YYYY'); // \"'Q'Q yyyy\" (bracketed text stays literal)\n * ```\n *\n * Throws if the format string uses a Day.js token with no temporal-fmt\n * equivalent (`Do`, `Mo`, `Qo`, `k`, `kk`, `X`, `x`, the localized\n * `L`-family tokens) — these need to be rewritten by hand, since\n * there's no single temporal-fmt token that means the same thing.\n *\n * Note: `Do`/`Mo`/`Qo`/`k`/`kk`/`X`/`x` only have meaning in Day.js\n * once the `AdvancedFormat` (and, for `X`/`x`, base) plugins are\n * loaded — without them Day.js silently glues the parts together or\n * passes the letters through unrendered instead of erroring. This\n * function assumes the plugin is loaded, since that's the common case\n * for anyone who put these tokens in a format string on purpose.\n */\nexport function translateDayjsFormatString(formatStr: string): string {\n return translate(formatStr, DAYJS_TO_TEMPORAL_FMT, 'Day.js');\n}\n\n/**\n * Translates a date-fns format string to the equivalent temporal-fmt\n * token string. date-fns already uses Unicode-style tokens close to\n * temporal-fmt's own, so most strings pass through with only a case\n * change on the weekday tokens; the notable divergences are date-fns's\n * `D`/`DD` (day-of-year, matches temporal-fmt already) versus its `d`/\n * `dd` (day-of-month, also matches already) and the locale-dependent\n * `P`/`p` composite tokens, which have no single temporal-fmt token\n * and throw.\n */\nexport function translateDateFnsFormatString(formatStr: string): string {\n return translate(formatStr, DATE_FNS_T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AAYO,SAAS,6BAA6B,WAA2B;AACtE,SAAO,UAAU,WAAW,0BAA0B,UAAU;AAClE;","names":["addDays"]}
1
+ {"version":3,"sources":["../src/formatDistance.ts","../src/typeGuards.ts","../src/tokenMetadata.ts","../src/analyze.ts","../src/serialization.ts","../src/relativeGrammar.ts","../src/parseRelative.ts","../src/config.ts","../src/businessCalendar.ts","../src/holidays.ts","../src/extensibility.ts","../src/ideData.ts","../src/codemod.ts"],"sourcesContent":["/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DEFAULT_LOCALE, type FormatOptions } from './tokens.js';\nimport { isGregorianLeapYear, daysFromCivil } from './isoWeek.js';\nimport { normalizeLocaleTag } from './localeVocab.js';\nimport { InvalidLocaleError, InvalidDateError } from './errors.js';\n\n// Reads date fields off a Temporal value in the same minimal-shape style\n// as the rest of the library (TemporalLike) — no Temporal factory needed.\n// Works for PlainDate, PlainDateTime, and ZonedDateTime (since they all\n// expose year/month/day). PlainTime has no date fields; formatDistance()\n// between two PlainTime values isn't really meaningful and isn't\n// supported — it'll throw below when the field read fails.\ninterface DateFieldView {\n year?: number;\n month?: number;\n day?: number;\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n}\n\nfunction readFields(value: unknown, label: string): DateFieldView {\n if (value === null || typeof value !== 'object') {\n throw new Error(\n `temporal-fmt: formatDistance expects Temporal values, got ${label} = ${String(value)}.`\n );\n }\n const obj = value as Record<string, unknown>;\n // Either year/month/day (a real date) or none of them (a PlainTime);\n // anything in between would be a malformed Temporal-like.\n const hasYear = typeof obj.year === 'number';\n const hasMonth = typeof obj.month === 'number';\n const hasDay = typeof obj.day === 'number';\n if (hasYear !== hasMonth || hasMonth !== hasDay) {\n throw new Error(\n `temporal-fmt: formatDistance got a ${label} with a partial date (some of year/month/day missing). ` +\n `Pass a full Temporal.PlainDate / PlainDateTime / ZonedDateTime.`\n );\n }\n // Range validation on the date triple. This function accepts plain\n // field bags (documented duck-typing), so the fields are untrusted\n // caller data, and every downstream consumer assumed a real calendar\n // date: a year of 1e9 used to drive a O(|year|) day-accumulation loop\n // (hundreds of ms per call — a cheap CPU-denial primitive when an app\n // feeds user-controlled parsed values in), and month 0 / Feb 31 fell\n // through to either V8-internal Intl errors or silently-wrong\n // distances. Real Temporal values always pass these checks, so this\n // only ever fires on hostile/hand-rolled bags.\n if (hasYear) {\n const y = obj.year as number;\n const m = obj.month as number;\n const d = obj.day as number;\n if (!Number.isFinite(y) || !Number.isInteger(y) || y < MIN_YEAR || y > MAX_YEAR) {\n throw new InvalidDateError({\n input: label,\n reason: `year ${y} is outside the ${MIN_YEAR}..${MAX_YEAR} range Temporal can represent`,\n });\n }\n if (!Number.isInteger(m) || m < 1 || m > 12) {\n throw new InvalidDateError({\n input: label,\n reason: `month ${m} is not in 1..12`,\n });\n }\n const maxDay = m === 2 && isGregorianLeapYear(y) ? 29 : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1]!;\n if (!Number.isInteger(d) || d < 1 || d > maxDay) {\n throw new InvalidDateError({\n input: label,\n reason: `day ${d} is not valid for year ${y}, month ${m} (max ${maxDay})`,\n });\n }\n }\n return {\n year: hasYear ? (obj.year as number) : undefined,\n month: hasMonth ? (obj.month as number) : undefined,\n day: hasDay ? (obj.day as number) : undefined,\n hour: typeof obj.hour === 'number' ? (obj.hour as number) : undefined,\n minute: typeof obj.minute === 'number' ? (obj.minute as number) : undefined,\n second: typeof obj.second === 'number' ? (obj.second as number) : undefined,\n millisecond: typeof obj.millisecond === 'number' ? (obj.millisecond as number) : undefined,\n };\n}\n\n// Temporal's representable ISO year range (PlainDate accepts -271821\n// through 275760). Values beyond this can't come from a real Temporal\n// object, so they're rejected as malformed input rather than walked.\nconst MIN_YEAR = -271_821;\nconst MAX_YEAR = 275_760;\n\n// Reference epoch for ms-since computation. Jan 1, 2000 UTC is the same\n// anchor isoWeek.ts uses for day-of-week arithmetic; reusing it keeps the\n// reasoning localized to one well-known reference date.\nconst REFERENCE_YEAR = 2000;\nconst MS_PER_SECOND = 1000;\nconst MS_PER_MINUTE = 60 * MS_PER_SECOND;\nconst MS_PER_HOUR = 60 * MS_PER_MINUTE;\nconst MS_PER_DAY = 24 * MS_PER_HOUR;\n\nfunction daysSinceReference(year: number, month: number, day: number): number {\n // O(1): days_from_civil for the target minus days_from_civil for the\n // reference. The old version accumulated 365/366 per year in a loop —\n // identical results for every real date, but O(|year − 2000|), which\n // made hostile field-bag years (1e9+) an accidental CPU-denial\n // primitive. (Range validation in readFields already rejects years\n // Temporal can't represent; this closed form makes even the\n // in-range walk instant.)\n return daysFromCivil(year, month, day) - daysFromCivil(REFERENCE_YEAR, 1, 1);\n}\n\nfunction toEpochMs(fields: DateFieldView): number {\n // A PlainDate has no time fields — treat as midnight. A PlainDateTime\n // has them all. Comparing two PlainDates is a day-resolution diff;\n // comparing two PlainDateTimes is millisecond-resolution. Mixing the\n // two (one PlainDate, one PlainDateTime) is allowed and just means the\n // PlainDate side is treated as midnight, which is what most callers\n // would intuitively expect (\"distance from this date to this moment\").\n if (fields.year === undefined || fields.month === undefined || fields.day === undefined) {\n throw new Error(\n `temporal-fmt: formatDistance needs a Temporal value with year/month/day fields ` +\n `(PlainDate, PlainDateTime, or ZonedDateTime). A PlainTime or other shape ` +\n `has no anchor date to diff against.`\n );\n }\n const days = daysSinceReference(fields.year, fields.month, fields.day);\n const hour = fields.hour ?? 0;\n const minute = fields.minute ?? 0;\n const second = fields.second ?? 0;\n const millisecond = fields.millisecond ?? 0;\n return days * MS_PER_DAY + hour * MS_PER_HOUR + minute * MS_PER_MINUTE + second * MS_PER_SECOND + millisecond;\n}\n\n// Unit selection cutoffs. Mirrors the rough thresholds date-fns uses,\n// trimmed to the units Intl.RelativeTimeFormat supports in every engine\n// (it accepts 'second' through 'year'; 'quarter' and 'week' support\n// varies, so we skip 'week' here — going days → months directly at the\n// 30-day boundary is simpler and avoids the engine-support cliff).\n//\n// |diff| < 60 s → seconds (\"30 seconds ago\")\n// |diff| < 60 min → minutes (\"12 minutes ago\")\n// |diff| < 24 h → hours (\"3 hours ago\")\n// |diff| < 30 d → days (\"5 days ago\")\n// |diff| < 365 d → months (\"2 months ago\")\n// otherwise → years (\"1 year ago\")\n//\n// 30 days is an approximation of a month — a calendar month is 28-31\n// days, so the boundary is inherently fuzzy. Same with 365 days for a\n// year. Documented as approximations, not exact calendar arithmetic.\n//\n// `cutoffs` on FormatDistanceOptions overrides individual boundaries\n// per call. DEFAULT_CUTOFFS holds the same numbers as the old hardcoded\n// UNIT_CUTOFFS so callers passing nothing see the same output as\n// before — verified byte-for-byte against the pre-change baseline.\nconst DEFAULT_CUTOFFS = {\n seconds: 60, // 60 s\n minutes: 60, // 60 min\n hours: 24, // 24 h\n days: 30, // 30 d\n months: 365, // 365 d (in days, since the months→years boundary is day-resolution)\n} as const;\n\ntype CutoffKey = keyof typeof DEFAULT_CUTOFFS;\n\n// Cutoffs the caller can override. Each value is in the unit's own\n// native scale (seconds for `seconds`, minutes for `minutes`, etc.) —\n// `months` is the exception: it's the day count that bounds the\n// months→years crossover, since \"months\" itself isn't a fixed number\n// of days. This mirrors how the original hardcoded table expressed\n// the same boundary (30 * MS_PER_DAY for days, 365 * MS_PER_DAY for\n// the months cap) and lets callers say \"treat anything under 90 days\n// as months\" rather than \"anything under 3 months as months\" (which\n// would require picking a definition of \"month\").\nexport interface DistanceCutoffs {\n seconds?: number;\n minutes?: number;\n hours?: number;\n days?: number;\n months?: number;\n}\n\n// Convert the user-facing cutoffs (per-unit numbers) into the ms\n// thresholds the matching loop needs. Validates each value is a\n// positive finite number, and that the boundaries are monotonically\n// non-decreasing in equivalent ms — without that, the smallest-bound\n// branch always wins and a later branch becomes unreachable, which\n// is never what the caller intended.\nfunction resolveCutoffs(user?: DistanceCutoffs): Array<{ maxMs: number; unit: Intl.RelativeTimeFormatUnit }> {\n const merged: Record<CutoffKey, number> = { ...DEFAULT_CUTOFFS, ...user };\n\n for (const key of Object.keys(merged) as CutoffKey[]) {\n const value = merged[key];\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {\n throw new Error(\n `temporal-fmt: formatDistance cutoff \"${key}\" must be a positive finite number (got ${String(value)}).`\n );\n }\n }\n\n const secondsMs = merged.seconds * MS_PER_SECOND;\n const minutesMs = merged.minutes * MS_PER_MINUTE;\n const hoursMs = merged.hours * MS_PER_HOUR;\n const daysMs = merged.days * MS_PER_DAY;\n // `months` is in days — see DistanceCutoffs comment above.\n const monthsMs = merged.months * MS_PER_DAY;\n\n if (!(secondsMs <= minutesMs && minutesMs <= hoursMs && hoursMs <= daysMs && daysMs <= monthsMs)) {\n throw new Error(\n `temporal-fmt: formatDistance cutoffs must be monotonically non-decreasing in equivalent ms ` +\n `(seconds ≤ minutes ≤ hours ≤ days ≤ months). Got: seconds=${merged.seconds}s, ` +\n `minutes=${merged.minutes}min, hours=${merged.hours}h, days=${merged.days}d, months=${merged.months}d — ` +\n `pick a sequence where each boundary is at least as large as the one before it.`\n );\n }\n\n return [\n { maxMs: secondsMs, unit: 'second' },\n { maxMs: minutesMs, unit: 'minute' },\n { maxMs: hoursMs, unit: 'hour' },\n { maxMs: daysMs, unit: 'day' },\n { maxMs: monthsMs, unit: 'month' },\n ];\n}\n\nconst rtfCache = new Map<string, Intl.RelativeTimeFormat>();\nconst MAX_RTF_CACHE_SIZE = 100;\n\nfunction getRtf(locale: string, numeric: 'always' | 'auto'): Intl.RelativeTimeFormat {\n const key = `${canonicalLocaleKey(locale)}|${numeric}`;\n let rtf = rtfCache.get(key);\n if (rtf) return rtf;\n if (rtfCache.size >= MAX_RTF_CACHE_SIZE) {\n const oldestKey = rtfCache.keys().next().value;\n if (oldestKey !== undefined) rtfCache.delete(oldestKey);\n }\n try {\n rtf = new Intl.RelativeTimeFormat(normalizeLocaleTag(locale), { numeric });\n } catch (err) {\n // Malformed locale tags reach Intl as a bare RangeError; surface the\n // library's typed error instead. (Every failure mode of these\n // constructors with a string locale is a RangeError, so converting\n // unconditionally loses nothing — the original message is preserved\n // in `reason` either way.)\n throw new InvalidLocaleError({ actual: locale, reason: (err as Error).message });\n }\n rtfCache.set(key, rtf);\n return rtf;\n}\n\nfunction canonicalLocaleKey(locale: string): string {\n try {\n return new Intl.Locale(locale.replace(/_/g, '-')).toString().toLowerCase();\n } catch {\n return locale;\n }\n}\n\nexport interface FormatDistanceOptions extends FormatOptions {\n /**\n * 'auto' (default) lets Intl.RelativeTimeFormat use natural forms like\n * \"yesterday\"/\"tomorrow\"/\"now\" when the rounded value lands on ±1 or 0.\n * 'always' forces the strict \"1 day ago\"/\"in 1 day\"/\"in 0 seconds\" form.\n */\n numeric?: 'always' | 'auto';\n /**\n * Override the unit-selection boundaries (seconds→minutes,\n * minutes→hours, hours→days, days→months, months→years). Any\n * subset can be supplied; omitted boundaries fall back to the\n * defaults (60s, 60min, 24h, 30d, 365d). Values are in each\n * unit's native scale except `months`, which is in days — see\n * DistanceCutoffs. Throws descriptively on non-monotonic\n * boundaries or non-positive values, rather than producing\n * confusing output downstream.\n */\n cutoffs?: DistanceCutoffs;\n}\n\n/**\n * Returns a human-readable relative-time string describing `date1`\n * relative to `date2`, e.g. \"3 days ago\", \"in 2 hours\", \"now\". Delegates\n * unit names and pluralization to `Intl.RelativeTimeFormat` so the\n * output localizes the same way the rest of the library's locale-aware\n * tokens do.\n *\n * Convention: the result describes `date1`'s position relative to\n * `date2`. `formatDistance(now, threeDaysAgo)` → `\"3 days ago\"` (the\n * past date is described relative to now). `formatDistance(now, twoHoursFromNow)`\n * → `\"in 2 hours\"`. This matches the natural-language reading \"describe\n * the first date as if standing at the second one.\"\n *\n * Unit-selection cutoffs (seconds → minutes → hours → days → months →\n * years) and the rationale for each are documented in the README under\n * \"formatDistance\".\n *\n * @example\n * formatDistance(threeDaysAgo, today) // \"3 days ago\"\n * formatDistance(twoHoursFromNow, today) // \"in 2 hours\"\n * formatDistance(today, today) // \"now\"\n * formatDistance(futureDate, today, {locale:'fr-FR'}) // \"dans 2 jours\"\n */\nexport function formatDistance(\n date1: unknown,\n date2: unknown,\n options: FormatDistanceOptions = {},\n): string {\n const fields1 = readFields(date1, 'date1');\n const fields2 = readFields(date2, 'date2');\n\n // diff > 0: date1 is later than date2 → \"in X units\" (date1 is in\n // the future relative to date2). diff < 0: date1 is earlier than\n // date2 → \"X units ago\". This convention puts date1 in the\n // \"described\" role and date2 in the \"reference\" role, matching\n // natural-language reading: `formatDistance(threeDaysAgo, today)`\n // = \"describe threeDaysAgo as if standing at today\" = \"3 days ago\".\n const diffMs = toEpochMs(fields1) - toEpochMs(fields2);\n const absMs = Math.abs(diffMs);\n\n const unitCutoffs = resolveCutoffs(options.cutoffs);\n let unit: Intl.RelativeTimeFormatUnit = 'year';\n for (const { maxMs, unit: candidateUnit } of unitCutoffs) {\n if (absMs < maxMs) {\n unit = candidateUnit;\n break;\n }\n }\n\n const divisor = unitToMs(unit);\n const rounded = Math.round(diffMs / divisor);\n\n const numeric = options.numeric ?? 'auto';\n const locale = options.locale ?? DEFAULT_LOCALE;\n const rtf = getRtf(locale, numeric);\n return rtf.format(rounded, unit);\n}\n\n/**\n * Same as formatDistance(date, now), where \"now\" is read from the system\n * clock at call time. Convenience wrapper for the common \"how long ago\n * was this\" case, so the caller doesn't have to construct a reference\n * value themselves.\n *\n * Unlike formatRelativeToNow() (in relativeTime.ts), which only needs\n * calendar-day resolution, this reads the full wall-clock time (hour\n * through millisecond) off the system clock — formatDistance's unit\n * selection is ms-resolution, so a date-only \"now\" would misclassify\n * anything under 24 hours old (e.g. \"1 hour ago\" reading as \"in 23\n * hours\" against a midnight-truncated reference). See the test file\n * for a regression case covering exactly that.\n *\n * The reference is captured fresh on every call, not memoized — each\n * call reflects \"now\" at the moment it runs, same expectation\n * formatRelativeToNow() already sets.\n *\n * @example\n * formatDistanceToNow(threeHoursAgo) // \"3 hours ago\"\n * formatDistanceToNow(tomorrow) // \"in 1 day\" (auto: \"tomorrow\")\n */\nexport function formatDistanceToNow(\n date: unknown,\n options: FormatDistanceOptions = {},\n): string {\n const now = new Date();\n const nowFields = {\n year: now.getFullYear(),\n month: now.getMonth() + 1,\n day: now.getDate(),\n hour: now.getHours(),\n minute: now.getMinutes(),\n second: now.getSeconds(),\n millisecond: now.getMilliseconds(),\n };\n return formatDistance(date, nowFields, options);\n}\n\nfunction unitToMs(unit: Intl.RelativeTimeFormatUnit): number {\n switch (unit) {\n case 'second': return MS_PER_SECOND;\n case 'minute': return MS_PER_MINUTE;\n case 'hour': return MS_PER_HOUR;\n case 'day': return MS_PER_DAY;\n /* c8 ignore start @preserve -- unreachable: unitToMs is only called\n with `unit` values produced by formatDistance's cutoff loop above,\n which only ever yields 'second'/'minute'/'hour'/'day'/'month'\n (from resolveCutoffs' fixed array) or 'year' (the loop's fallback\n default). 'week' and 'quarter' were never wired into\n resolveCutoffs — formatDistance intentionally skips week-\n resolution output (see the comment above DEFAULT_CUTOFFS) — so\n neither can reach this switch. */\n case 'week': return 7 * MS_PER_DAY;\n /* c8 ignore stop @preserve */\n case 'month': return 30 * MS_PER_DAY;\n /* c8 ignore start @preserve -- unreachable, same reason as 'week'\n above: resolveCutoffs never produces 'quarter'. */\n case 'quarter': return 91 * MS_PER_DAY;\n /* c8 ignore stop @preserve */\n case 'year': return 365 * MS_PER_DAY;\n /* c8 ignore start @preserve -- unreachable: every unit\n resolveCutoffs can actually produce ('second' through 'month', or\n 'year' as the loop's fallback default) has an explicit case\n above, so this exhaustive-switch default can't fire at runtime.\n It exists so TS accepts the function as total — the compiler\n can't see through the cutoff-array iteration in formatDistance()\n to know the input is already narrowed. */\n default:\n throw new Error(`temporal-fmt: formatDistance hit unhandled unit \"${String(unit)}\".`);\n /* c8 ignore stop @preserve */\n }\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// type guards for Temporal values. the rest of this lib works off the\n// duck-typed TemporalLike shape (year/month/day/hour/...) instead of\n// `instanceof Temporal.X`, because instanceof just breaks across\n// polyfill/native boundaries — a polyfill's Temporal.PlainDate is a\n// completely different constructor from the native one, so\n// `value instanceof Temporal.PlainDate` would silently fail if the\n// caller's using a polyfill while the guard's looking at native\n// Temporal, or the other way around. same reasoning as tokens.ts's\n// intlSupportsNativeTemporal probe — identity checks just don't survive\n// a polyfill/native swap.\n//\n// so instead these guards check structural shape: does it have the\n// type-discriminating method each Temporal type carries. method\n// presence is part of the actual Temporal spec contract — every\n// implementation, native or polyfill, has to expose the same methods on\n// the same types — so it's a stable signal without needing to import a\n// Temporal namespace at all.\n//\n// per-type discriminators (double checked these against\n// @js-temporal/polyfill's actual prototype method list, matches spec):\n//\n// PlainDate — toPlainDateTime + withCalendar + year/month/day,\n// no hour. (PlainDateTime also has toPlainDateTime's\n// sibling toPlainDate/toPlainTime, but carries hour —\n// that's what distinguishes them.)\n// PlainTime — no toPlainDateTime, no withCalendar. has hour,\n// no year/month/day. (only Temporal date/time type\n// with neither withCalendar nor any toPlainX method.)\n// PlainDateTime — toPlainDate + withPlainTime + year/month/day\n// AND hour. (withPlainTime is unique — only\n// PlainDateTime and ZonedDateTime carry it;\n// ZonedDateTime also carries toInstant, which\n// PlainDateTime doesn't.)\n// ZonedDateTime — toInstant + withTimeZone. (both unique — only\n// ZonedDateTime carries withTimeZone.)\n// Instant — toZonedDateTimeISO, no toInstant. (Instant IS the\n// instant — toInstant belongs to ZonedDateTime.\n// toZonedDateTimeISO exists on both Instant and\n// ZonedDateTime per spec, but on ZonedDateTime it's\n// not actually exposed on the prototype in either\n// native or polyfill — only Instant has it as a real\n// method. checked both to confirm.)\n// PlainYearMonth — toPlainDate (takes a day arg) + year/month, no\n// day. (PlainDate also has a toPlainDate-shaped\n// method but carries day; PlainMonthDay also has\n// toPlainDate but carries day, not year.)\n// PlainMonthDay — toPlainDate + month/day, no year. also lacks\n// add/subtract/until/since (calendar arithmetic\n// doesn't really make sense on a month-day without\n// a year anyway).\n// Duration — total + abs + negated. (all three unique to\n// Duration, nothing else carries any of them.)\n\n// this shape intentionally mirrors TemporalLike over in tokens.ts, but\n// stays loose enough to also match real Temporal objects (which carry\n// the spec methods the field-only TemporalLike doesn't have)\ninterface TemporalInstance {\n toInstant?: () => unknown;\n toPlainDate?: (arg?: unknown) => unknown;\n toPlainDateTime?: (arg?: unknown) => unknown;\n toPlainTime?: () => unknown;\n toPlainYearMonth?: () => unknown;\n toPlainMonthDay?: () => unknown;\n toZonedDateTime?: (arg: unknown) => unknown;\n toZonedDateTimeISO?: (arg: unknown) => unknown;\n withCalendar?: (cal: unknown) => unknown;\n withPlainTime?: (t: unknown) => unknown;\n withTimeZone?: (z: unknown) => unknown;\n getTimeZoneTransition?: (opts: unknown) => unknown;\n startOfDay?: () => unknown;\n sign?: () => number;\n blank?: () => boolean;\n total?: (opts: unknown) => number;\n abs?: () => unknown;\n negated?: () => unknown;\n toString?: () => string;\n // these come from TemporalLike — present on all the date-carrying\n // Temporal types but absent on PlainTime (no calendar position there)\n year?: number;\n month?: number;\n day?: number;\n hour?: number;\n minute?: number;\n second?: number;\n calendarId?: string;\n timeZoneId?: string;\n // PlainMonthDay stores its month as monthCode (like \"M08\") instead of\n // a plain numeric month — without a year there's no way to know which\n // month a calendar-independent numeric month even refers to once\n // leap-year-aware calendars get involved, so the spec uses monthCode\n // instead. PlainMonthDay's the only type that has monthCode but not month\n monthCode?: string;\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null;\n}\n\n// hardening against hostile getters: the guards below read properties\n// (year, hour, Symbol.toStringTag, ...) off whatever value the caller\n// hands us. an object with a throwing getter used to turn isPlainDate(obj)\n// — a function whose entire contract is \"return a boolean\" — into an\n// exception factory instead. every exported guard now goes through this\n// wrapper, so a throw during probing just means \"not one of ours\", not a\n// crash. one shared catch here instead of one per guard also keeps the\n// coverage numbers honest\nfunction guardOrFalse<T>(impl: (value: unknown) => value is T): (value: unknown) => value is T {\n return (value: unknown): value is T => {\n try {\n return impl(value);\n } catch {\n return false;\n }\n };\n}\n\nfunction hasMethod<T extends keyof TemporalInstance>(\n v: TemporalInstance,\n name: T,\n): boolean {\n return typeof v[name] === 'function';\n}\n\n// Symbol.toStringTag is the spec-mandated brand for Temporal types —\n// every Temporal instance carries a tag like \"Temporal.PlainDate\" via\n// this symbol regardless of native vs polyfill. the per-type guards use\n// this as a fast positive check: a tag match is enough on its own, the\n// structural fallback (field presence + method checks) only kicks in\n// when there's no tag set, which can happen with hand-built mocks or\n// partial implementations\nfunction hasTag(value: unknown, typeName: string): boolean {\n if (!isObject(value)) return false;\n const tag = (value as { [Symbol.toStringTag]?: unknown })[Symbol.toStringTag];\n return tag === `Temporal.${typeName}`;\n}\n\nexport const isPlainDate: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainDateImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainDate')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n return typeof v.year === 'number'\n && typeof v.month === 'number'\n && typeof v.day === 'number'\n && typeof v.hour === 'undefined'\n && hasMethod(v, 'toPlainDateTime')\n && hasMethod(v, 'withCalendar');\n});\n\nexport const isPlainTime: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainTimeImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainTime')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // PlainTime is the only type with hour but no year, and neither\n // withCalendar nor any toPlainX method. that combo is unique among\n // all eight types\n return typeof v.hour === 'number'\n && typeof v.year === 'undefined'\n && !hasMethod(v, 'withCalendar')\n && !hasMethod(v, 'toPlainDate')\n && !hasMethod(v, 'toPlainDateTime');\n});\n\nexport const isPlainDateTime: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainDateTimeImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainDateTime')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // withPlainTime shows up on both PlainDateTime and ZonedDateTime, but\n // ZonedDateTime also has toInstant. so \"has withPlainTime, no\n // toInstant\" uniquely picks out PlainDateTime\n return typeof v.year === 'number'\n && typeof v.month === 'number'\n && typeof v.day === 'number'\n && typeof v.hour === 'number'\n && hasMethod(v, 'withPlainTime')\n && !hasMethod(v, 'toInstant');\n});\n\nexport const isZonedDateTime: (value: unknown) => value is TemporalInstance = guardOrFalse(function isZonedDateTimeImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'ZonedDateTime')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // withTimeZone is unique to ZonedDateTime, nothing else has it\n return typeof v.year === 'number'\n && typeof v.month === 'number'\n && typeof v.day === 'number'\n && typeof v.hour === 'number'\n && hasMethod(v, 'withTimeZone')\n && hasMethod(v, 'toInstant');\n});\n\nexport const isInstant: (value: unknown) => value is TemporalInstance = guardOrFalse(function isInstantImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'Instant')) return true;\n if (!isObject(value)) return false;\n // Instant has toZonedDateTimeISO but no toInstant — makes sense, it\n // IS the instant already. also has no year/month/day/hour fields since\n // those only mean anything against a calendar + zone, which Instant\n // alone doesn't carry\n const v = value as TemporalInstance;\n return hasMethod(v, 'toZonedDateTimeISO')\n && !hasMethod(v, 'toInstant')\n && typeof v.year === 'undefined';\n});\n\nexport const isPlainYearMonth: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainYearMonthImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainYearMonth')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // has year+month but no day, carries toPlainDate (used to attach a day\n // later). PlainMonthDay also has toPlainDate but doesn't have year\n return typeof v.year === 'number'\n && typeof v.month === 'number'\n && typeof v.day === 'undefined'\n && hasMethod(v, 'toPlainDate');\n});\n\nexport const isPlainMonthDay: (value: unknown) => value is TemporalInstance = guardOrFalse(function isPlainMonthDayImpl(value: unknown): value is TemporalInstance {\n if (hasTag(value, 'PlainMonthDay')) return true;\n if (!isObject(value)) return false;\n const v = value as TemporalInstance;\n // PlainMonthDay has day and monthCode but no year and no numeric month.\n // monthCode's the discriminator here — every other Temporal type with\n // a month concept either has month (numeric, calendar-aware) or\n // doesn't have months at all (PlainTime, Duration)\n return typeof v.year === 'undefined'\n && typeof v.month === 'undefined'\n && typeof v.day === 'number'\n && typeof v.monthCode === 'string'\n && hasMethod(v, 'toPlainDate');\n});\n\nexport const isDuration: (value: unknown) => value is Record<string, unknown> = guardOrFalse(function isDurationImpl(value: unknown): value is Record<string, unknown> {\n if (hasTag(value, 'Duration')) return true;\n if (!isObject(value)) return false;\n // total is unique to Duration across the whole Temporal set — nothing\n // else has it (checked every prototype to confirm). abs and negated\n // are also Duration-only, checking any one of the three would work;\n // going with total since it's the most semantically distinctive one —\n // a Duration-specific operation nothing else would coincidentally need\n const v = value as TemporalInstance;\n return hasMethod(v, 'total');\n});\n\n// umbrella guard: is this ANY Temporal namespace member. used by\n// assertTemporal below for the \"this needs to be some Temporal thing\"\n// case. checks two signals in order:\n// 1. Symbol.toStringTag — every Temporal type brands itself as\n// Temporal.X via this symbol. spec-mandated, present on native\n// and polyfill instances alike.\n// 2. the discriminating-method fallback — covers whatever future or\n// partial Temporal implementation doesn't bother setting the tag.\n// method presence is part of the spec contract, so combined with\n// equals + with (both on every Temporal instance) it's still a\n// reliable signal even without the tag being set\nexport const isTemporal: (value: unknown) => value is TemporalInstance = guardOrFalse(function isTemporalImpl(value: unknown): value is TemporalInstance {\n if (!isObject(value)) return false;\n const tag = (value as { [Symbol.toStringTag]?: unknown })[Symbol.toStringTag];\n if (typeof tag === 'string' && tag.startsWith('Temporal.')) return true;\n const v = value as TemporalInstance;\n return hasMethod(v, 'toInstant')\n || hasMethod(v, 'toPlainDate')\n || hasMethod(v, 'toPlainDateTime')\n || hasMethod(v, 'toPlainTime')\n || hasMethod(v, 'toPlainYearMonth')\n || hasMethod(v, 'toPlainMonthDay')\n || hasMethod(v, 'toZonedDateTime')\n || hasMethod(v, 'toZonedDateTimeISO')\n || hasMethod(v, 'withCalendar')\n || hasMethod(v, 'withPlainTime')\n || hasMethod(v, 'withTimeZone')\n || hasMethod(v, 'total');\n});\n\n// assertion helpers — throw with a real message instead of just\n// returning false. same convention the rest of this lib uses: descriptive\n// thrown errors instead of failing silently. the thrown error includes\n// a valueType hint so the caller can actually see what they passed in\nfunction describeValue(value: unknown): string {\n if (value === null) return 'null';\n if (Array.isArray(value)) return 'array';\n if (typeof value === 'object') {\n const ctor = (value as { constructor?: { name?: string } }).constructor;\n if (ctor && typeof ctor.name === 'string' && ctor.name !== 'Object') {\n return `instance of ${ctor.name}`;\n }\n return 'plain object';\n }\n return typeof value;\n}\n\nfunction assertImpl(value: unknown, guard: (v: unknown) => boolean, expectedType: string): void {\n if (!guard(value)) {\n throw new Error(\n `temporal-fmt: expected a Temporal.${expectedType}, got ${describeValue(value)}.`\n );\n }\n}\n\nexport function assertTemporal(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isTemporal, 'object (Instant, PlainDate, PlainTime, PlainDateTime, ZonedDateTime, Duration, PlainYearMonth, or PlainMonthDay)');\n}\nexport function assertInstant(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isInstant, 'Instant');\n}\nexport function assertPlainDate(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainDate, 'PlainDate');\n}\nexport function assertPlainTime(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainTime, 'PlainTime');\n}\nexport function assertPlainDateTime(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainDateTime, 'PlainDateTime');\n}\nexport function assertZonedDateTime(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isZonedDateTime, 'ZonedDateTime');\n}\nexport function assertPlainYearMonth(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainYearMonth, 'PlainYearMonth');\n}\nexport function assertPlainMonthDay(value: unknown): asserts value is TemporalInstance {\n assertImpl(value, isPlainMonthDay, 'PlainMonthDay');\n}\nexport function assertDuration(value: unknown): asserts value is Record<string, unknown> {\n assertImpl(value, isDuration, 'Duration');\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Per-token metadata: the structured descriptor this module\n// asks for (meaning, format-capable?, parse-capable?, locale-sensitive?,\n// calendar-sensitive?, timezone-sensitive?, supported Temporal types,\n// round-trip-safe?). One table, kept in sync with TOKENS in tokens.ts\n// by tests (see test/tokenMetadata.test.js — every entry in TOKENS has\n// a metadata entry, and vice versa).\n//\n// This is the single source of truth that analyzeFormat() (section E)\n// and the ESLint plugin / codemod consume — never read the\n// TOKENS array directly for metadata; use TOKEN_METADATA here, or the\n// tokenInfo() / listTokens() wrappers in analyze.ts.\n\nimport type { TemporalLike } from './tokens.js';\n\nexport type TemporalType =\n | 'Instant'\n | 'PlainDate'\n | 'PlainTime'\n | 'PlainDateTime'\n | 'ZonedDateTime'\n | 'PlainYearMonth'\n | 'PlainMonthDay';\n\nexport interface TokenMetadata {\n // Short human-readable description of what the token represents.\n meaning: string;\n // True if format() accepts this token. Every token in TOKENS is\n // format-capable by construction; this flag exists so the table is\n // self-describing for callers (the codemod) that work with token\n // families including format-only tokens from other libraries.\n formatCapable: boolean;\n // True if parse() accepts this token. False for `do`, `ww`, `RRRR`\n // — see FORMAT_ONLY_TOKENS in pattern.ts.\n parseCapable: boolean;\n // True if the output depends on locale (resolves via Intl or\n // custom vocab). MMMM/MMM/EEEE/EEE/a are true; everything else is\n // numeric ASCII and locale-independent.\n localeSensitive: boolean;\n // True if the output depends on the calendar (gregory, hebrew,\n // etc.). Locale-aware tokens inherit calendar sensitivity from\n // the Intl path (a hebrew PlainDate's month name depends on the\n // hebrew calendar). Year/month/day numeric tokens are calendar-\n // sensitive in principle (a Hebrew year/month renders differently\n // than a Gregorian one) but stay ISO-numeric on the format side\n // because tokens.ts reads straight off TemporalLike fields, which\n // are already calendar-specific by the time format() sees them.\n calendarSensitive: boolean;\n // True if the token requires a timeZoneId or offset field — i.e.\n // only ZonedDateTime supports it. zzz and the six offset tokens\n // (X/XX/XXX/x/xx/xxx) are timezone-sensitive.\n timezoneSensitive: boolean;\n // Which Temporal types can supply the field this token needs.\n // PlainTime can't supply year; PlainDate can't supply hour; only\n // ZonedDateTime carries timeZoneId/offset.\n supportedTypes: TemporalType[];\n // True if format(x, fmt) → parse(fmt, output) round-trips back to\n // a value equal to x. False when the format is fundamentally lossy:\n // `do` (ordinal suffix isn't structurally parseable), `ww`/`RRRR`\n // (week + weekday alone can't reconstruct a date without an extra\n // disambiguator), `yy` (two-digit year loses century — strptime\n // heuristic resolves it, but the heuristic isn't symmetric with\n // how `yy` formats BCE years, so round-trip only works for years\n // where 00-68/69-99 lands back on the same century).\n roundTripSafe: boolean;\n}\n\n// Helper: which Temporal types carry each field. Centralized here so\n// the supportedTypes arrays below stay short and the table is easy to\n// audit. Mirrors the field checks in tokens.ts (handler third tuple\n// element).\nconst TYPES_WITH: Record<string, TemporalType[]> = {\n year: ['PlainDate', 'PlainDateTime', 'ZonedDateTime', 'PlainYearMonth'],\n month: ['PlainDate', 'PlainDateTime', 'ZonedDateTime', 'PlainYearMonth', 'PlainMonthDay'],\n day: ['PlainDate', 'PlainDateTime', 'ZonedDateTime', 'PlainMonthDay'],\n // Instant deliberately NOT listed: Temporal.Instant exposes no\n // hour/minute/second/millisecond wall-clock fields (they're\n // zone-dependent), so format(instant, 'HH') throws at the field\n // check — the metadata used to claim Instant was supported, telling\n // analyzer/IDE consumers the opposite of what runtime does.\n hour: ['PlainTime', 'PlainDateTime', 'ZonedDateTime'],\n minute: ['PlainTime', 'PlainDateTime', 'ZonedDateTime'],\n second: ['PlainTime', 'PlainDateTime', 'ZonedDateTime'],\n millisecond: ['PlainTime', 'PlainDateTime', 'ZonedDateTime'],\n dayOfWeek: ['PlainDate', 'PlainDateTime', 'ZonedDateTime'],\n timeZoneId: ['ZonedDateTime'],\n offset: ['ZonedDateTime'],\n};\n\n// Every token in TOKENS gets an entry here. Adding a token to TOKENS\n// without adding one here makes test/tokenMetadata.test.js fail.\nexport const TOKEN_METADATA: Record<string, TokenMetadata> = {\n yyyy: {\n meaning: 'Four-digit year (preserves sign for BCE; no truncation).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: true,\n },\n yy: {\n meaning: 'Two-digit year (year % 100). Throws on negative years.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: false,\n },\n y: {\n meaning: 'Unpadded year, any width (preserves sign for BCE; no truncation, no minimum digits). Cannot sit directly next to another digit-reading token or a literal starting with a digit — there would be no way to tell where it ends.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: true,\n },\n MMMM: {\n meaning: 'Long month name (locale-aware, e.g. \"January\", \"janvier\").',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n MMM: {\n meaning: 'Short month name (locale-aware, e.g. \"Jan\", \"janv.\").',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n MM: {\n meaning: 'Two-digit month (01-12, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n M: {\n meaning: 'One- or two-digit month (1-12, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n dd: {\n meaning: 'Two-digit day-of-month (01-31, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day, roundTripSafe: true,\n },\n d: {\n meaning: 'One- or two-digit day-of-month (1-31, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day, roundTripSafe: true,\n },\n EEEE: {\n meaning: 'Long weekday name (locale-aware, e.g. \"Monday\", \"lundi\"). Parse cross-checks against the parsed date.',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: true,\n },\n EEE: {\n meaning: 'Short weekday name (locale-aware, e.g. \"Mon\", \"lun.\"). Parse cross-checks against the parsed date.',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: true,\n },\n HH: {\n meaning: 'Two-digit hour, 24-hour clock (00-23, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n H: {\n meaning: 'One- or two-digit hour, 24-hour clock (0-23, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n hh: {\n meaning: 'Two-digit hour, 12-hour clock (01-12, zero-padded). Requires `a` token on parse.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n h: {\n meaning: 'One- or two-digit hour, 12-hour clock (1-12, no padding). Requires `a` token on parse.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n mm: {\n meaning: 'Two-digit minute (00-59, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.minute, roundTripSafe: true,\n },\n m: {\n meaning: 'One- or two-digit minute (0-59, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.minute, roundTripSafe: true,\n },\n ss: {\n meaning: 'Two-digit second (00-59, zero-padded).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.second, roundTripSafe: true,\n },\n s: {\n meaning: 'One- or two-digit second (0-59, no padding).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.second, roundTripSafe: true,\n },\n S: {\n meaning: 'Fractional second, 1 digit (tenths of a second).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SS: {\n meaning: 'Fractional second, 2 digits (hundredths of a second).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSS: {\n meaning: 'Fractional second, 3 digits (milliseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSS: {\n meaning: 'Fractional second, 4 digits (tens of microseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSS: {\n meaning: 'Fractional second, 5 digits (hundred-thousandths of a second).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSSS: {\n meaning: 'Fractional second, 6 digits (microseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSSSS: {\n meaning: 'Fractional second, 7 digits (tens of nanoseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSSSSS: {\n meaning: 'Fractional second, 8 digits (hundred-millionths of a second).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n SSSSSSSSS: {\n meaning: 'Fractional second, 9 digits (nanoseconds).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.millisecond, roundTripSafe: true,\n },\n a: {\n meaning: 'Day period (locale-aware: \"AM\"/\"PM\", \"午前\"/\"午後\", etc.). Required alongside 12-hour tokens on parse.',\n formatCapable: true, parseCapable: true, localeSensitive: true, calendarSensitive: false, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.hour, roundTripSafe: true,\n },\n zzz: {\n meaning: 'IANA time zone id (e.g. \"America/New_York\") or fixed offset (\"+05:30\"). Requires full date+time on parse.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.timeZoneId, roundTripSafe: true,\n },\n X: {\n meaning: 'Numeric UTC offset, short (Z for UTC, ±HH[MM] otherwise). Minutes omitted when zero.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n XX: {\n meaning: 'Numeric UTC offset, no colon (Z for UTC, ±HHMM otherwise).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n XXX: {\n meaning: 'Numeric UTC offset, with colon (Z for UTC, ±HH:MM otherwise).',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n x: {\n meaning: 'Numeric UTC offset, short, never Z (always ±HH[MM]). Lowercase variant of X.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n xx: {\n meaning: 'Numeric UTC offset, no colon, never Z (always ±HHMM). Lowercase variant of XX.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n xxx: {\n meaning: 'Numeric UTC offset, with colon, never Z (always ±HH:MM). Lowercase variant of XXX.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.offset, roundTripSafe: true,\n },\n do: {\n meaning: 'Ordinal day-of-month with English suffix (\"1st\", \"2nd\", \"3rd\", \"4th\", ... 21st, 22nd, ...). Format-only — not parseable.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day, roundTripSafe: false,\n },\n Q: {\n meaning: 'Quarter as a digit (1-4). Derived from month.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n QQQ: {\n meaning: 'Quarter with \"Q\" prefix (\"Q1\"..\"Q4\"). Derived from month.',\n formatCapable: true, parseCapable: true, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n ww: {\n meaning: 'ISO 8601 week number (01-53). Format-only — week alone can\\'t reconstruct a date.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: false,\n },\n RRRR: {\n meaning: 'ISO 8601 week-numbering year (4-digit, may differ from calendar year at year boundaries). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: false,\n },\n // Day-of-year is leap-adjusted, so it needs a YEAR — PlainMonthDay\n // (month+day with no year) used to be listed as supported here while\n // format() computed a non-leap day-of-year for it.\n D: {\n meaning: 'Day of year, unpadded (1-366). Format-only — parsing requires resolving against a year.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day.filter((t) => t !== 'PlainMonthDay'), roundTripSafe: false,\n },\n DD: {\n meaning: 'Day of year, 2-digit minimum (01-366). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day.filter((t) => t !== 'PlainMonthDay'), roundTripSafe: false,\n },\n DDD: {\n meaning: 'Day of year, 3-digit zero-padded (001-366). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: false, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.day.filter((t) => t !== 'PlainMonthDay'), roundTripSafe: false,\n },\n LLLL: {\n meaning: 'Stand-alone long month name (nominative case in Slavic locales). Identical to MMMM in most locales.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n LLL: {\n meaning: 'Stand-alone short month name. Identical to MMM in most locales.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.month, roundTripSafe: true,\n },\n cccc: {\n meaning: 'Stand-alone long weekday name. Identical to EEEE in most locales.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: true,\n },\n ccc: {\n meaning: 'Stand-alone short weekday name. Identical to EEE in most locales.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.dayOfWeek, roundTripSafe: true,\n },\n GGGG: {\n meaning: 'Long era name (locale-aware, e.g. \"Anno Domini\"/\"Before Christ\"). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: false,\n },\n G: {\n meaning: 'Short era name (locale-aware, e.g. \"AD\"/\"BC\"). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: true, timezoneSensitive: false,\n supportedTypes: TYPES_WITH.year, roundTripSafe: false,\n },\n zzzz: {\n meaning: 'Localized long timezone name (e.g. \"Eastern Standard Time\"). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.timeZoneId, roundTripSafe: false,\n },\n z: {\n meaning: 'Localized short timezone name (e.g. \"EST\"). Format-only.',\n formatCapable: true, parseCapable: false, localeSensitive: true, calendarSensitive: false, timezoneSensitive: true,\n supportedTypes: TYPES_WITH.timeZoneId, roundTripSafe: false,\n },\n\n};\n\nexport const ALL_TOKEN_NAMES: string[] = Object.keys(TOKEN_METADATA);","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Format-string analysis and introspection. Single source of truth for\n// \"what does this format string need / accept / produce\" — consumed by\n// the ESLint plugin and the codemod\n// so they don't each carry their own token table that drifts out of\n// sync with the runtime. Everything here reads from TOKENS in\n// tokens.ts and TOKEN_METADATA in tokenMetadata.ts, so adding a token\n// to those two tables automatically makes it visible to analyze()\n// without touching this file.\n\nimport { TOKENS, type TemporalLike } from './tokens.js';\nimport { TOKEN_METADATA, type TokenMetadata, type TemporalType } from './tokenMetadata.js';\nimport { tokenize, tokenizeWithSpans, type Piece } from './tokenize.js';\nimport { _handlerFor } from './format.js';\nimport { UNPADDED_NUMERIC_TOKENS, FORMAT_ONLY_TOKENS } from './pattern.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\n\n// Re-exported so callers can import everything analyzer-related from a\n// single entry point — analyze.ts is the introspection surface.\nexport type { TokenMetadata, TemporalType } from './tokenMetadata.js';\nexport type { Piece } from './tokenize.js';\n\n// tokenizeFormat is the same tokenize() the runtime uses, exposed\n// under a name that signals \"this is the introspection entry point.\"\n// Same implementation, different name — callers reading analyze.ts\n// see a coherent API surface rather than having to know that the\n// runtime tokenizer is the right thing to call.\nexport function tokenizeFormat(formatStr: string): Piece[] {\n return tokenize(formatStr);\n}\n\n// listTokens: every token the runtime recognizes, with metadata. Used\n// by IDE autocomplete data (section AC) and the codemod's \"can this\n// source-library token be translated?\" lookup (section Z).\nexport function listTokens(): Array<{ name: string; metadata: TokenMetadata }> {\n return TOKENS.map(([name]) => ({ name, metadata: TOKEN_METADATA[name]! }));\n}\n\n// tokenInfo: one token's metadata. Returns undefined for unknown\n// tokens rather than throwing — callers (autocomplete, hover docs)\n// want a sentinel, not an exception, when a user types a partial token.\nexport function tokenInfo(name: string): TokenMetadata | undefined {\n return TOKEN_METADATA[name];\n}\n\nexport interface AnalyzedToken {\n name: string;\n // Position in the format string, 0-indexed. Useful for IDE diagnostics\n // that highlight a specific token.\n position: number;\n metadata: TokenMetadata;\n}\n\nexport interface FormatAnalysis {\n // Every token in the format string, in order, with metadata.\n tokens: AnalyzedToken[];\n // Fields (year/month/day/hour/...) any token in this format string\n // reads off the input. Lets a caller statically check \"does this\n // format string need a field PlainDate doesn't have?\"\n requiredFields: string[];\n // Temporal types that can supply every required field. The intersection\n // across all tokens — a format string with both `yyyy` (needs year)\n // and `HH` (needs hour) is compatible only with types carrying both,\n // i.e. PlainDateTime/ZonedDateTime.\n compatibleTypes: TemporalType[];\n // Can parse() accept this format string? False when any token is\n // format-only (do/ww/RRRR per FORMAT_ONLY_TOKENS in pattern.ts).\n parseable: boolean;\n // Does the format string contain any locale-aware token (MMMM/MMM/\n // EEEE/EEE/a)? True means the output depends on the locale option\n // and a registered custom vocab can override the result.\n localeSensitive: boolean;\n // Does the format string contain any calendar-sensitive token?\n // Almost every date/weekday token is, since its output depends on\n // the object's calendar (a hebrew PlainDate's \"MMMM\" is a hebrew\n // month name). Pure-time tokens (HH/mm/ss) are not.\n calendarSensitive: boolean;\n // Does the format string contain zzz or any offset token? If yes,\n // only ZonedDateTime can supply the field.\n timezoneSensitive: boolean;\n // Does the format string contain a run of 2+ adjacent unpadded\n // numeric tokens with no literal between them (Md, dM, Hms, ...)?\n // Such runs can be ambiguous at parse time — strict mode throws,\n // lenient mode picks one split via the documented heuristic.\n ambiguous: boolean;\n // Does format(x, fmt) → parse(fmt, output) round-trip? False when\n // any token is format-only OR when yy is used (century loss).\n roundTripSafe: boolean;\n // Non-fatal issues found during analysis. Each carries a `code`\n // the IDE plugin / CLI can switch on. Empty for clean format strings.\n warnings: Array<{ code: string; message: string }>;\n}\n\nexport function analyzeFormat(formatStr: string): FormatAnalysis {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(\n `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`\n );\n }\n const pieces = tokenizeWithSpans(formatStr);\n const tokens: AnalyzedToken[] = [];\n const requiredFields = new Set<string>();\n const compatibleTypesSet = new Set<TemporalType>();\n let parseable = true;\n let localeSensitive = false;\n let calendarSensitive = false;\n let timezoneSensitive = false;\n let roundTripSafe = true;\n const warnings: Array<{ code: string; message: string }> = [];\n\n // Walk pieces, building up the analysis. Each token's `position` is\n // its exact source index in the ORIGINAL format string (from\n // tokenizeWithSpans) — decoded literal lengths used to be accumulated\n // instead, which under-counted every quoted span ('a b' is 5 source\n // chars, 3 decoded; '' is 2 source chars, 1 decoded), so every token\n // after any quote escape reported a position that was too small.\n const unpaddedRun: string[] = [];\n const flushRun = () => {\n if (unpaddedRun.length >= 2) {\n warnings.push({\n code: 'AMBIGUOUS_NUMERIC_RUN',\n message: `Adjacent unpadded numeric tokens \"${unpaddedRun.join('')}\" with no separator can be ambiguous to parse. Add a separator or use the padded form (e.g. \"MM\" instead of \"M\").`,\n });\n }\n unpaddedRun.length = 0;\n };\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n flushRun();\n continue;\n }\n const metadata = TOKEN_METADATA[piece.value];\n // Dead by construction, confirmed via listTokens(): every token in\n // TOKENS has a matching TOKEN_METADATA entry (51/51), and tokenize()\n // already throws on any string that isn't in TOKENS before this loop\n // ever runs. Kept as a guard against the two tables drifting apart.\n /* c8 ignore start */\n if (!metadata) {\n warnings.push({\n code: 'UNKNOWN_TOKEN_NO_METADATA',\n message: `Token \"${piece.value}\" is recognized by the tokenizer but has no metadata entry in tokenMetadata.ts — this is a bug in temporal-fmt.`,\n });\n continue;\n }\n /* c8 ignore stop */\n tokens.push({ name: piece.value, position: piece.start, metadata });\n\n // Required fields: read off the handler map (the source of truth\n // for \"what field does this token need\"). Falls back to the\n // metadata's supportedTypes-derived field set if the handler isn't\n // found, which also shouldn't happen.\n const handler = _handlerFor(piece.value);\n if (handler) {\n requiredFields.add(handler.field as string);\n }\n\n // compatibleTypes: intersect every token's supportedTypes. The\n // first token seeds the set; subsequent tokens narrow it.\n if (tokens.length === 1) {\n for (const t of metadata.supportedTypes) compatibleTypesSet.add(t);\n } else {\n const stillCompatible = new Set<TemporalType>();\n for (const t of compatibleTypesSet) {\n if (metadata.supportedTypes.includes(t)) stillCompatible.add(t);\n }\n compatibleTypesSet.clear();\n for (const t of stillCompatible) compatibleTypesSet.add(t);\n }\n\n if (!metadata.parseCapable) {\n parseable = false;\n warnings.push({\n code: 'FORMAT_ONLY_TOKEN',\n message: `Token \"${piece.value}\" is format-only — it can't be parsed back into a value. Use a parse-capable variant (e.g. \"d\" instead of \"do\") if you need round-trip.`,\n });\n }\n if (metadata.localeSensitive) localeSensitive = true;\n if (metadata.calendarSensitive) calendarSensitive = true;\n if (metadata.timezoneSensitive) timezoneSensitive = true;\n if (!metadata.roundTripSafe) roundTripSafe = false;\n\n // Track runs of adjacent unpadded numeric tokens — same definition\n // as parsePattern.ts uses (UNPADDED_NUMERIC_TOKENS). A literal\n // between tokens breaks the run; this is checked by the flushRun\n // call above.\n if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {\n unpaddedRun.push(piece.value);\n } else {\n flushRun();\n }\n }\n flushRun();\n\n // Cross-token checks the runtime parse() performs. Mirroring them\n // here lets the ESLint plugin flag them statically without having\n // to re-derive the logic.\n const tokenNames = tokens.map((t) => t.name);\n const has12Hour = tokenNames.some((t) => t === 'hh' || t === 'h');\n const has24Hour = tokenNames.some((t) => t === 'HH' || t === 'H');\n const hasAPeriod = tokenNames.some((t) => t === 'a');\n if (has12Hour && !hasAPeriod) {\n warnings.push({\n code: 'TWELVE_HOUR_WITHOUT_A',\n message: '12-hour token (\"hh\"/\"h\") used without an \"a\" (AM/PM) token — parse() can\\'t tell AM from PM and throws at runtime.',\n });\n }\n if (has12Hour && has24Hour) {\n warnings.push({\n code: 'MIXED_12_AND_24_HOUR',\n message: 'Mixing 24-hour and 12-hour tokens — parse() refuses to guess which is authoritative and throws at runtime.',\n });\n }\n\n const hasOffset = tokenNames.some((t) => t === 'X' || t === 'XX' || t === 'XXX' || t === 'x' || t === 'xx' || t === 'xxx');\n const hasZzz = tokenNames.some((t) => t === 'zzz');\n if (hasOffset && hasZzz) {\n warnings.push({\n code: 'ZZZ_WITH_OFFSET_TOKEN',\n message: 'Format string has both \"zzz\" and an offset token — parse() cross-checks them and throws if the parsed offset disagrees with the zone\\'s actual offset.',\n });\n }\n if (hasOffset && !requiredFields.has('year')) {\n warnings.push({\n code: 'OFFSET_WITHOUT_FULL_DATE',\n message: 'Offset token used without a full date — parse() needs a complete date and time to build a ZonedDateTime and throws at runtime otherwise.',\n });\n }\n\n return {\n tokens,\n requiredFields: [...requiredFields].sort(),\n compatibleTypes: [...compatibleTypesSet].sort(),\n parseable,\n localeSensitive,\n calendarSensitive,\n timezoneSensitive,\n // Ambiguous iff at least one warning fired about an ambiguous run.\n ambiguous: warnings.some((w) => w.code === 'AMBIGUOUS_NUMERIC_RUN'),\n roundTripSafe: roundTripSafe && parseable,\n warnings,\n };\n}\n\n// explainFormat: human-readable rendering of analyzeFormat's output.\n// Used by the CLI (section AD) for `temporal-fmt inspect <fmt>` and by\n// the IDE for hover docs on a format string. Plain prose, no JSON —\n// callers wanting machine-readable output should call analyzeFormat()\n// directly.\nexport function explainFormat(formatStr: string): string {\n const analysis = analyzeFormat(formatStr);\n const lines: string[] = [];\n lines.push(`Format string: \"${formatStr}\"`);\n lines.push(`Tokens (${analysis.tokens.length}):`);\n for (const t of analysis.tokens) {\n lines.push(` ${t.name} @${t.position} — ${t.metadata.meaning}`);\n }\n if (analysis.requiredFields.length > 0) {\n lines.push(`Required fields: ${analysis.requiredFields.join(', ')}`);\n }\n if (analysis.compatibleTypes.length > 0) {\n lines.push(`Compatible Temporal types: ${analysis.compatibleTypes.join(', ')}`);\n }\n lines.push(`Parseable: ${analysis.parseable ? 'yes' : 'no'}`);\n lines.push(`Locale-sensitive: ${analysis.localeSensitive ? 'yes' : 'no'}`);\n lines.push(`Calendar-sensitive: ${analysis.calendarSensitive ? 'yes' : 'no'}`);\n lines.push(`Timezone-sensitive: ${analysis.timezoneSensitive ? 'yes' : 'no'}`);\n lines.push(`Ambiguous: ${analysis.ambiguous ? 'yes' : 'no'}`);\n lines.push(`Round-trip safe: ${analysis.roundTripSafe ? 'yes' : 'no'}`);\n if (analysis.warnings.length > 0) {\n lines.push('Warnings:');\n for (const w of analysis.warnings) {\n lines.push(` [${w.code}] ${w.message}`);\n }\n }\n return lines.join('\\n');\n}\n\n// isValidFormat: true iff tokenize() accepts the string without\n// throwing. Distinct from analyzeFormat's `parseable` flag — a format\n// string can be valid (tokenizes cleanly) but not parseable (contains\n// a format-only token like `do`). Both checks are exposed since callers\n// want different things: validity for \"will format() throw\", parseability\n// for \"will parse() throw\".\nexport function isValidFormat(formatStr: string): boolean {\n if (formatStr.length > MAX_FORMAT_LENGTH) return false;\n try {\n tokenize(formatStr);\n return true;\n } catch {\n return false;\n }\n}\n\n// validateFormat: throws on invalid format strings instead of\n// returning a boolean. Mirrors the existing strict-validation\n// convention (descriptive thrown errors, never silent failures).\n// Returns the analysis for callers who want both — validate-then-use.\nexport function validateFormat(formatStr: string): FormatAnalysis {\n const analysis = analyzeFormat(formatStr);\n return analysis;\n}\n\n// Exported for callers that want to query the token table without\n// touching internals. Kept here rather than re-exported from\n// tokenMetadata.ts so this module is the single import for \"anything\n// analyzer-related.\"\nexport { TOKEN_METADATA, ALL_TOKEN_NAMES } from './tokenMetadata.js';\n\n// Re-export FORMAT_ONLY_TOKENS so callers don't have to import from\n// pattern.ts (which is a lower-level module they shouldn't need to\n// know about).\nexport { FORMAT_ONLY_TOKENS } from './pattern.js';\n\n// Used by callers that need to look up which field a token requires —\n// e.g. the ESLint plugin's \"type mismatch\" check (section Y) wants to\n// answer \"does the type the caller passed to format() carry this\n// field?\" without having to actually call format() and catch the\n// thrown error. Mirrors the same lookup format.ts does internally.\nexport function fieldForToken(token: string): keyof TemporalLike | undefined {\n return _handlerFor(token)?.field;\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Serialization / interop helpers. Standardized\n// parse/format pairs for ISO 8601, RFC 3339, RFC 2822, HTTP-date,\n// plus epoch conversions to/from unix seconds/ms/µs/ns.\n//\n// All of these wrap the existing parse()/format() surface rather than\n// reimplementing the formats — same convention as the rest of the\n// library (one tokenizer, one parser, one constructor path). The\n// standard-format helpers are essentially pre-baked format strings\n// with the right tokens, plus stricter input validation where the\n// standard demands it (e.g. RFC 3339 requires UTC-offset-only zones,\n// not named IANA zones).\n\nimport { parse } from './parse.js';\nimport { format } from './format.js';\nimport { getTemporal, type TemporalNamespace } from './temporalProvider.js';\nimport { FormatSyntaxError, InvalidDateError } from './errors.js';\n\n// Build a Temporal instance from a field bag. Used by the parse helpers\n// to construct PlainDate / PlainDateTime / ZonedDateTime / Instant from\n// the fields the standard format carries. Throws on construction errors\n// (Feb 30, etc.) wrapped in InvalidDateError so callers get the typed\n// error surface.\nfunction constructFromFields(fields: Record<string, unknown>, kind: 'PlainDate' | 'PlainDateTime' | 'ZonedDateTime' | 'Instant'): unknown {\n const temporal = getTemporal();\n try {\n switch (kind) {\n case 'PlainDate':\n return temporal.PlainDate.from(fields as Record<string, number | string | undefined>, { overflow: 'reject' });\n case 'PlainDateTime':\n return temporal.PlainDateTime.from(fields as Record<string, number | string | undefined>, { overflow: 'reject' });\n case 'ZonedDateTime':\n return temporal.ZonedDateTime.from(fields as Record<string, number | string | undefined>, { overflow: 'reject' });\n case 'Instant': {\n // Instant.from takes an ISO string, not a field bag. Build the\n // ISO string ourselves and parse it.\n const iso = buildISOFromFields(fields);\n if (!temporal.Instant) {\n throw new Error('temporal-fmt: Temporal.Instant is not available in this implementation.');\n }\n return temporal.Instant.from(iso);\n }\n }\n } catch (err) {\n throw new InvalidDateError({ input: JSON.stringify(fields), reason: (err as Error).message });\n }\n}\n\nfunction buildISOFromFields(fields: Record<string, unknown>): string {\n const y = String(fields.year).padStart(4, '0');\n const m = String(fields.month).padStart(2, '0');\n const d = String(fields.day).padStart(2, '0');\n const h = fields.hour !== undefined ? `T${String(fields.hour).padStart(2, '0')}` : '';\n const min = fields.minute !== undefined ? `:${String(fields.minute).padStart(2, '0')}` : '';\n const sec = fields.second !== undefined ? `:${String(fields.second).padStart(2, '0')}` : '';\n const frac = fields.millisecond !== undefined && (fields.millisecond as number) > 0\n ? `.${String(fields.millisecond).padStart(3, '0')}`\n : '';\n const tz = typeof fields.timeZone === 'string' ? fields.timeZone : 'Z';\n return `${y}-${m}-${d}${h}${min}${sec}${frac}${tz}`;\n}\n\n// ISO 8601 is the most permissive of the standards here — accepts\n// calendar dates, week dates, ordinal dates, times with optional\n// fractional seconds, timezone offsets or 'Z'. Delegates to\n// Temporal's own ISO parsing (which is ISO 8601-compliant) by\n// constructing from the raw ISO string.\n\nexport function parseISO(input: string): unknown {\n const temporal = getTemporal();\n // Detect what kind of Temporal object the ISO string describes.\n // ISO 8601 strings have a date part, optional time part, optional\n // timezone. We dispatch to the right Temporal constructor based on\n // which parts are present.\n try {\n if (/^\\d{4}-\\d{2}-\\d{2}T/.test(input) || /T\\d{2}:\\d{2}/.test(input)) {\n // Has a time component.\n if (/[zZ]$/.test(input) || /[+-]\\d{2}:?\\d{2}$/.test(input)) {\n // ZonedDateTime. Temporal.ZonedDateTime.from accepts ISO with\n // a zone bracket (e.g. \"2026-08-04T15:45:30[UTC]\") but rejects\n // a bare offset with no bracket. For \"Z\" suffix, expand to\n // \"+00:00[UTC]\"; for a numeric offset, append that same offset\n // as the bracket (e.g. \"+05:30\" → \"+05:30[+05:30]\").\n let iso = input;\n if (/[zZ]$/.test(iso)) {\n iso = iso.slice(0, -1) + '+00:00[UTC]';\n } else {\n const offsetMatch = /([+-]\\d{2}:?\\d{2})$/.exec(iso);\n if (offsetMatch) {\n iso = `${iso}[${offsetMatch[1]}]`;\n }\n }\n return temporal.ZonedDateTime.from(iso as unknown as Record<string, number | string | undefined>, { overflow: 'reject' });\n }\n return temporal.PlainDateTime.from(input as unknown as Record<string, number | string | undefined>, { overflow: 'reject' });\n }\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(input)) {\n return temporal.PlainDate.from(input as unknown as Record<string, number | string | undefined>, { overflow: 'reject' });\n }\n if (/^\\d{2}:\\d{2}/.test(input)) {\n return temporal.PlainTime.from(input as unknown as Record<string, number | string | undefined>);\n }\n throw new Error(`temporal-fmt: parseISO(\"${input}\") doesn't look like an ISO 8601 string.`);\n } catch (err) {\n throw new InvalidDateError({ input, reason: (err as Error).message });\n }\n}\n\nexport function formatISO(value: unknown): string {\n // Temporal objects expose toString() which produces ISO 8601 output\n // by spec. So formatting IS just toString().\n const v = value as { toString?: () => string };\n if (typeof v?.toString !== 'function') {\n throw new FormatSyntaxError({ reason: `formatISO() expects a Temporal value with toString(), got ${typeof value}.` });\n }\n return v.toString();\n}\n\n// RFC 3339 is a profile of ISO 8601 used in network protocols (HTTP,\n// JSON-RPC, etc.). Stricter than ISO 8601: requires full date+time,\n// requires seconds, requires UTC offset or 'Z', disallows IANA zone\n// names. Delegates to parseISO then validates the constraints.\n\nexport function parseRFC3339(input: string): unknown {\n // RFC 3339 grammar (https://www.rfc-editor.org/rfc/rfc3339#section-5.6):\n // date-fullyear = 4DIGIT\n // date-month = 2DIGIT ; 01-12\n // date-mday = 2DIGIT ; 01-28, 01-29, 01-30, 01-31\n // time-hour = 2DIGIT ; 00-23\n // time-minute = 2DIGIT ; 00-59\n // time-second = 2DIGIT ; 00-58, 00-59, 00-60 (leap second)\n // time-secfrac = \".\" 1*DIGIT\n // time-numoffset = (\"+\" / \"-\") time-hour \":\" time-minute\n // time-offset = \"Z\" / time-numoffset\n // partial-time = time-hour \":\" time-minute \":\" time-second [time-secfrac]\n // full-date = date-fullyear \"-\" date-month \"-\" date-mday\n // full-time = partial-time time-offset\n // date-time = full-date \"T\" full-time\n const re = /^(\\d{4})-(\\d{2})-(\\d{2})[Tt](\\d{2}):(\\d{2}):(\\d{2})(\\.\\d+)?([Zz]|[+-]\\d{2}:\\d{2})$/;\n const m = re.exec(input);\n if (!m) {\n throw new FormatSyntaxError({ input, reason: 'does not match RFC 3339 date-time grammar' });\n }\n // Construct via parseISO with the same expansion for bare Z.\n const iso = input.replace(/[tT]/, 'T').replace(/[zZ]$/, '+00:00[UTC]');\n return parseISO(iso);\n}\n\nexport function formatRFC3339(value: unknown): string {\n // RFC 3339 output is ISO 8601 with a UTC offset. toString() on a\n // ZonedDateTime produces this shape; we just verify the result looks\n // like RFC 3339 and pass it through.\n const s = formatISO(value);\n if (!/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$/.test(s)) {\n throw new FormatSyntaxError({ input: s, reason: 'value did not produce RFC 3339-compliant output' });\n }\n return s;\n}\n\n// RFC 2822 date-time (used in email Message-ID headers, etc.). Format:\n// day-of-week, day month year hour:minute:second zone\n// e.g. \"Mon, 04 Aug 2026 15:45:30 +0000\"\n// JS Date can parse this natively, so we use Date.parse and convert\n// to a Temporal.Instant. (Date.parse's RFC 2822 support is universal\n// across engines, unlike its ISO 8601 support which varies.)\n\nexport function parseRFC2822(input: string): unknown {\n // Strict shape pre-check: Date.parse is far more permissive than RFC 2822\n // (it happily accepts ISO 8601 and other dialects), so without this gate\n // parseRFC2822(\"2026-08-04\") would succeed despite not being an RFC 2822\n // date at all. The regex mirrors RFC 2822 §3.3's date-time grammar:\n // optional day-of-week, 1-2 digit day, month name, 2-4 digit year (the\n // obsolete two-digit form included), time with optional seconds, and a\n // zone that is either a numeric ±HHMM offset or an alphabetic zone name.\n const RFC2822_SHAPE =\n /^(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\\s+)?\\d{1,2}\\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\s+\\d{2,4}\\s+\\d{2}:\\d{2}(?::\\d{2})?\\s+(?:[+-]\\d{4}|[A-Za-z]{1,5})$/;\n if (!RFC2822_SHAPE.test(input.trim())) {\n throw new FormatSyntaxError({ input, reason: 'not a valid RFC 2822 date' });\n }\n const ms = Date.parse(input);\n if (Number.isNaN(ms)) {\n throw new FormatSyntaxError({ input, reason: 'not a valid RFC 2822 date' });\n }\n return requireInstant().fromEpochMilliseconds(ms);\n}\n\nexport function formatRFC2822(value: unknown): string {\n // Format using format() with the right tokens, then construct via\n // the value's epoch ms. RFC 2822 requires a fixed offset, not an\n // IANA zone, so we read the value's offset directly.\n const v = value as { toEpochMilliseconds?: () => number; epochMilliseconds?: number; toInstant?: () => { epochMilliseconds: number } };\n let ms: number | undefined;\n if (typeof v?.toEpochMilliseconds === 'function') {\n ms = v.toEpochMilliseconds();\n } else if (typeof v?.epochMilliseconds === 'number') {\n // Temporal.Instant exposes epochMilliseconds as a property.\n ms = v.epochMilliseconds;\n } else if (typeof v?.toInstant === 'function') {\n // ZonedDateTime.toInstant() → Instant.\n const inst = v.toInstant();\n if (typeof (inst as { epochMilliseconds?: number }).epochMilliseconds === 'number') {\n ms = (inst as { epochMilliseconds: number }).epochMilliseconds;\n }\n }\n if (ms === undefined) {\n throw new FormatSyntaxError({ reason: `formatRFC2822() expects a value with epochMilliseconds, toEpochMilliseconds(), or toInstant(), got ${typeof value}.` });\n }\n return formatRFC2822FromMs(ms);\n}\n\nfunction formatRFC2822FromMs(ms: number): string {\n // Use Intl.DateTimeFormat with the en-US POSIX locale and the rfc822\n // format option. Modern Node ships Intl with this option; if not\n // available, fall back to manual formatting.\n try {\n const fmt = new Intl.DateTimeFormat('en-US', {\n weekday: 'short', day: '2-digit', month: 'short', year: 'numeric',\n hour: '2-digit', minute: '2-digit', second: '2-digit',\n timeZone: 'UTC', timeZoneName: 'shortOffset',\n hour12: false,\n });\n const parts = fmt.formatToParts(new Date(ms));\n /* c8 ignore start -- every part type get() is called with (weekday,\n day, month, year, hour, minute, second, timeZoneName) is always\n present given the fixed options above, so the ?? '' fallback\n can't fire without a different Intl implementation. */\n const get = (t: string) => parts.find((p) => p.type === t)?.value ?? '';\n /* c8 ignore stop */\n const tzRaw = get('timeZoneName');\n // Intl's shortOffset returns \"GMT+0\", \"GMT-8\", \"GMT+5:30\", etc.\n // RFC 2822 wants \"+0000\", \"-0800\", \"+0530\". Parse and reformat.\n const tzMatch = tzRaw?.match(/GMT([+-])(\\d+)(?::(\\d+))?/);\n let tz: string;\n if (tzMatch) {\n const sign = tzMatch[1]!;\n const hours = tzMatch[2]!.padStart(2, '0');\n const minutes = (tzMatch[3] ?? '0').padStart(2, '0');\n tz = `${sign}${hours}${minutes}`;\n /* c8 ignore start @preserve -- timeZone is hardcoded to 'UTC' above,\n which always resolves cleanly, so shortOffset always returns a\n parseable \"GMT+0\"-shaped string in this environment's ICU. This\n branch only guards against an ICU build whose shortOffset output\n doesn't match the regex; can't trigger it without mocking Intl.\n The ignore starts before the closing brace of the if-block so it\n covers the whole else-branch node c8 tracks as a single unit. */\n } else {\n tz = '+0000';\n }\n /* c8 ignore stop @preserve */\n let hour = get('hour');\n /* c8 ignore start @preserve -- hour12:false with a fixed UTC zone\n never yields \"24\" in this environment's ICU (midnight formats as\n \"00\"). Some ICU versions/locales are documented to emit \"24\" for\n hour12:false, so this stays as a defensive normalization; not\n reachable here without mocking Intl.DateTimeFormat's output. */\n if (hour === '24') hour = '00';\n /* c8 ignore stop @preserve */\n return `${get('weekday')}, ${get('day')} ${get('month')} ${get('year')} ${hour}:${get('minute')}:${get('second')} ${tz}`;\n /* c8 ignore start @preserve -- Intl.DateTimeFormat is constructed\n above with a literal, always-valid timeZone: 'UTC' and no other\n user input reaches the constructor or formatToParts call, so this\n catch can't be triggered through the public API in a normal Intl\n environment (e.g. Node with full-icu). Kept as a genuine fallback\n for runtimes with a broken or absent Intl implementation. */\n } catch {\n // Fallback: hand-rolled RFC 2822 format via Date's UTC methods.\n const d = new Date(ms);\n const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\n const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n const wd = days[d.getUTCDay()];\n const dd = String(d.getUTCDate()).padStart(2, '0');\n const mon = months[d.getUTCMonth()]!;\n const yyyy = d.getUTCFullYear();\n const hh = String(d.getUTCHours()).padStart(2, '0');\n const mm = String(d.getUTCMinutes()).padStart(2, '0');\n const ss = String(d.getUTCSeconds()).padStart(2, '0');\n return `${wd}, ${dd} ${mon} ${yyyy} ${hh}:${mm}:${ss} +0000`;\n }\n /* c8 ignore stop @preserve */\n}\n\n// RFC 7231 defines three formats: IMF-fixdate, RFC 850, asctime.\n// The canonical format is IMF-fixdate (RFC 2822-like with required\n// seconds and UTC-only). Delegates to Date.parse for parsing and to\n// formatRFC2822 for formatting (they're nearly identical).\n\nexport function parseHTTPDate(input: string): unknown {\n const trimmed = input.trim();\n const ms = Date.parse(trimmed);\n if (Number.isNaN(ms)) {\n throw new FormatSyntaxError({ input, reason: 'not a valid HTTP-date' });\n }\n return requireInstant().fromEpochMilliseconds(ms);\n}\n\nexport function formatHTTPDate(value: unknown): string {\n // IMF-fixdate format: \"Sun, 06 Nov 1994 08:49:37 GMT\"\n const instant = (value as { toInstant?: () => { epochMilliseconds: number } })?.toInstant?.()\n ?? (value as { epochMilliseconds?: number });\n const ms = typeof instant === 'object' && instant !== null && 'epochMilliseconds' in instant\n ? (instant as { epochMilliseconds: number }).epochMilliseconds\n : (() => { throw new FormatSyntaxError({ reason: `formatHTTPDate() expects an Instant or ZonedDateTime, got ${typeof value}.` }); })();\n const d = new Date(ms);\n const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];\n const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n const wd = days[d.getUTCDay()];\n const dd = String(d.getUTCDate()).padStart(2, '0');\n const mon = months[d.getUTCMonth()]!;\n const yyyy = d.getUTCFullYear();\n const hh = String(d.getUTCHours()).padStart(2, '0');\n const mm = String(d.getUTCMinutes()).padStart(2, '0');\n const ss = String(d.getUTCSeconds()).padStart(2, '0');\n return `${wd}, ${dd} ${mon} ${yyyy} ${hh}:${mm}:${ss} GMT`;\n}\n\n// All epoch conversions go through Temporal.Instant, which has spec\n// methods for each epoch granularity. Wrapped here for the\n// temporal-fmt surface so callers don't have to import Temporal\n// directly.\n\nfunction getInstant(value: unknown): { epochMilliseconds: number; epochNanoseconds: bigint } {\n const v = value as { toInstant?: () => { epochMilliseconds: number; epochNanoseconds: bigint }; epochMilliseconds?: number; epochNanoseconds?: bigint };\n if (typeof v?.toInstant === 'function') {\n const inst = v.toInstant();\n // Prefer the instant's own epochNanoseconds when present — same\n // precision reasoning as below, since toInstant() can return a\n // real Temporal.Instant carrying both fields.\n if (typeof (inst as { epochNanoseconds?: bigint }).epochNanoseconds === 'bigint') {\n return { epochMilliseconds: inst.epochMilliseconds, epochNanoseconds: (inst as { epochNanoseconds: bigint }).epochNanoseconds };\n }\n return { epochMilliseconds: inst.epochMilliseconds, epochNanoseconds: BigInt(inst.epochMilliseconds) * 1_000_000n };\n }\n // Check epochNanoseconds before epochMilliseconds: a real\n // Temporal.Instant exposes both, and epochMilliseconds is truncated\n // to millisecond precision. Deriving epochNanoseconds by scaling\n // epochMilliseconds back up would silently drop sub-ms precision\n // that was available on the object all along.\n if (typeof v?.epochNanoseconds === 'bigint') {\n return { epochMilliseconds: Number(v.epochNanoseconds / 1_000_000n), epochNanoseconds: v.epochNanoseconds };\n }\n if (typeof v?.epochMilliseconds === 'number') {\n return { epochMilliseconds: v.epochMilliseconds, epochNanoseconds: BigInt(v.epochMilliseconds) * 1_000_000n };\n }\n throw new FormatSyntaxError({ reason: `expected an Instant or ZonedDateTime, got ${typeof value}.` });\n}\n\nfunction requireInstant(): NonNullable<TemporalNamespace['Instant']> {\n const t = getTemporal().Instant;\n if (!t) throw new Error('temporal-fmt: Temporal.Instant is not available in this implementation.');\n return t;\n}\n\nexport function toUnixSeconds(value: unknown): number {\n return getInstant(value).epochMilliseconds / 1000;\n}\n\nexport function fromUnixSeconds(seconds: number): unknown {\n return requireInstant().fromEpochMilliseconds(seconds * 1000);\n}\n\nexport function fromUnixMilliseconds(ms: number): unknown {\n return requireInstant().fromEpochMilliseconds(ms);\n}\n\nexport function fromUnixMicroseconds(µs: number): unknown {\n // Temporal.Instant has no fromEpochMicroseconds in the spec — only\n // fromEpochMilliseconds and fromEpochNanoseconds. Convert via ns.\n return requireInstant().fromEpochNanoseconds(BigInt(µs) * 1_000n);\n}\n\nexport function fromUnixNanoseconds(ns: bigint): unknown {\n return requireInstant().fromEpochNanoseconds(ns);\n}\n\nexport function toUnixMilliseconds(value: unknown): number {\n return getInstant(value).epochMilliseconds;\n}\n\nexport function toUnixMicroseconds(value: unknown): number {\n const { epochNanoseconds } = getInstant(value);\n return Number(epochNanoseconds / 1_000n);\n}\n\nexport function toUnixNanoseconds(value: unknown): bigint {\n return getInstant(value).epochNanoseconds;\n}\n\n// SQL-oriented helpers. SQL date/time formats are simpler than the\n// network standards above — just 'YYYY-MM-DD' for dates, 'HH:MM:SS'\n// for times, 'YYYY-MM-DD HH:MM:SS' for datetimes. Delegating to\n// parse() with the right format strings keeps the validation surface\n// consistent.\nexport function parseSQL(input: string): unknown {\n const trimmed = input.trim();\n if (/^\\d{4}-\\d{2}-\\d{2}$/.test(trimmed)) {\n return parse('yyyy-MM-dd', trimmed);\n }\n if (/^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}$/.test(trimmed)) {\n return parse('yyyy-MM-dd HH:mm:ss', trimmed);\n }\n if (/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}/.test(trimmed)) {\n return parseISO(trimmed);\n }\n throw new FormatSyntaxError({ input, reason: 'not a recognized SQL date/time format' });\n}\n\nexport function formatSQL(value: unknown): string {\n // Detect what kind of Temporal value this is and pick the format.\n const v = value as { year?: number; hour?: number };\n if (typeof v?.hour === 'number') {\n return format(value as Parameters<typeof format>[0], 'yyyy-MM-dd HH:mm:ss');\n }\n return format(value as Parameters<typeof format>[0], 'yyyy-MM-dd');\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// lets people register their own relative-date grammars on top of\n// parseRelative.ts, which only ships with English/Spanish/French/German\n// baked in.\n//\n// parseRelative() looks at the locale option, figures out the language,\n// and dispatches. registerRelativeGrammar() means someone can bolt on\n// a new language without touching parseRelative.ts itself.\n//\n// a grammar is just a list of matchers, each one either resolves to a\n// Temporal field bag or returns null. tries them in order, first match\n// wins — same shape as the ENGLISH/SPANISH/FRENCH/GERMAN_GRAMMAR objects\n// parseRelative already has internally, just made pluggable\n\nimport { getTemporal, type TemporalNamespace } from './temporalProvider.js';\n\nexport interface RelativeGrammarMatch {\n // whatever fields the matcher figured out, gets fed to Temporal.PlainDate.from()\n year?: number;\n month?: number;\n day?: number;\n // for cases like \"next Tuesday\" where you can't compute the fields\n // without knowing the reference date's weekday first — pass a function\n // instead of raw fields\n resolve?: (reference: { year: number; month: number; day: number; dayOfWeek: number }) => { year: number; month: number; day: number };\n}\n\nexport interface RelativeGrammar {\n // language subtag ('en', 'es', etc), matched against the locale option\n language: string;\n // tried top to bottom, first one that matches wins\n matchers: Array<(input: string) => RelativeGrammarMatch | null>;\n}\n\n// cap so nobody can loop registerRelativeGrammar() and blow up the array\n// (and the scan in tryRegisteredGrammar with it) forever. re-registering\n// an existing language doesn't count against this, only actually new ones.\n// same idea as what registerLocaleVocab does for custom vocabs\nconst MAX_REGISTERED_GRAMMARS = 100;\n\nconst registeredGrammars: RelativeGrammar[] = [];\n\nexport function registerRelativeGrammar(grammar: RelativeGrammar): void {\n if (typeof grammar.language !== 'string' || grammar.language.length === 0) {\n throw new Error('temporal-fmt: registerRelativeGrammar requires a non-empty language string.');\n }\n if (grammar.language.length > 35) {\n throw new RangeError(`temporal-fmt: registerRelativeGrammar language tags must be at most 35 characters (got ${grammar.language.length}).`);\n }\n if (!Array.isArray(grammar.matchers) || grammar.matchers.length === 0) {\n throw new Error('temporal-fmt: registerRelativeGrammar requires at least one matcher.');\n }\n // Every matcher runs on untrusted parseRelative input — a non-function\n // entry used to register fine and then blow up every subsequent\n // parseRelative() call for that locale with a raw V8 TypeError\n // (\"matcher is not a function\"). Cap the count for the same reason the\n // grammar count is capped: every registered matcher is scanned per\n // parseRelative call.\n if (grammar.matchers.length > 1000) {\n throw new RangeError(`temporal-fmt: registerRelativeGrammar accepts at most 1000 matchers (got ${grammar.matchers.length}).`);\n }\n if (!grammar.matchers.every((m) => typeof m === 'function')) {\n throw new Error('temporal-fmt: registerRelativeGrammar matchers must all be functions.');\n }\n // if this language's already registered, just swap it out\n const existingIdx = registeredGrammars.findIndex((g) => g.language === grammar.language);\n if (existingIdx >= 0) {\n registeredGrammars[existingIdx] = grammar;\n } else {\n if (registeredGrammars.length >= MAX_REGISTERED_GRAMMARS) {\n throw new RangeError(`temporal-fmt: registerRelativeGrammar reached the ${MAX_REGISTERED_GRAMMARS}-grammar limit.`);\n }\n registeredGrammars.push(grammar);\n }\n}\n\n// parseRelative() calls this first, before falling back to the built-ins.\n// null means nothing registered matched\nexport function tryRegisteredGrammar(\n language: string,\n input: string,\n reference: { year: number; month: number; day: number; dayOfWeek: number },\n): unknown | null {\n for (const grammar of registeredGrammars) {\n if (grammar.language !== language) continue;\n for (const matcher of grammar.matchers) {\n // One throwing matcher shouldn't take parseRelative() down with a\n // raw error — treat it as \"no match\" and let the next matcher (or\n // the built-in grammars) try. Registered matchers are third-party\n // code; isolating their failures is the registration boundary's\n // job.\n let match: RelativeGrammarMatch | null;\n try {\n match = matcher(input);\n } catch {\n continue;\n }\n if (match === null) continue;\n const temporal = getTemporal();\n if (match.resolve) {\n const fields = match.resolve(reference);\n return temporal.PlainDate.from(fields, { overflow: 'reject' });\n }\n return temporal.PlainDate.from(\n { year: match.year ?? reference.year, month: match.month ?? reference.month, day: match.day ?? reference.day },\n { overflow: 'reject' },\n );\n }\n }\n return null;\n}\n\n// just for introspection, lists what's registered\nexport function listRegisteredGrammars(): string[] {\n return registeredGrammars.map((g) => g.language);\n}\n\n// this is just here so TS doesn't complain about the unused import —\n// TemporalNamespace shows up in the type signature above but not as a\n// real runtime reference\nvoid (undefined as unknown as TemporalNamespace);\n","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getTemporal } from './temporalProvider.js';\nimport { type TemporalNamespace } from './temporalProvider.js';\nimport { tryRegisteredGrammar } from './relativeGrammar.js';\nimport { DEFAULT_LOCALE, type FormatOptions } from './tokens.js';\n\n// parseRelative resolves common relative-date phrases (\"next Tuesday\",\n// \"in 3 days\", \"March 5th\") against a reference date, returning a\n// Temporal.PlainDate. It's a different subsystem from the token-based\n// parse(): the input is free natural-language text, not a structurally-\n// typed format string, so this module owns its own grammar rather than\n// bolting a natural-language layer onto the existing tokenizer.\n//\n// Per-language grammars: each locale's grammar lives in its own\n// clearly-labeled section below (ENGLISH_GRAMMAR, SPANISH_GRAMMAR,\n// FRENCH_GRAMMAR, GERMAN_GRAMMAR). The vocabulary and phrase patterns\n// are NOT shared across languages — Spanish \"hace 2 semanas\" and\n// French \"il y a 2 semaines\" are different idioms and get their own\n// regexes. What IS shared is the matching engine (iterate matchers in\n// order, first match wins, throw on no match) and the resolution\n// helpers (addDays, addUnits, weekdayOffset, resolveToNextOccurrence).\n// Same approach the humanizing skill calls \"solve each recurring\n// problem once\": the matching strategy is shared, the per-language\n// vocabulary is not.\n//\n// Default locale (no `locale` option) uses English — matches the\n// pre-change behavior byte-for-byte. Passing `locale: 'es'`,\n// `locale: 'fr'`, or `locale: 'de'` (or any locale tag with that\n// language subtag) routes to the corresponding grammar. Unrecognized\n// languages fall back to English rather than throwing — a caller\n// passing `locale: 'it-IT'` still gets *some* result, just from the\n// English grammar. (We could throw instead; the current contract is\n// \"best effort.\" If the caller wanted Italian specifically, they'd\n// pass an Italian grammar via registerLocaleVocab-style extension —\n// not implemented here.)\n\n// Lowercase + expand German umlauts (ä→ae, ö→oe, ü→ue, ß→ss) + strip\n// remaining diacritics. Three things going on at once:\n//\n// 1. Lowercase — case-insensitive matching without forcing the\n// regex flag to do it (also keeps the captured groups lowercase\n// for the resolver's comparisons).\n// 2. Expand German umlaut transliterations. Germans without an\n// umlaut key write \"ä\" as \"ae\" — the standard transliteration.\n// Expanding \"ä\" → \"ae\" (before NFD stripping) means both \"März\"\n// and \"Maerz\" normalize to \"maerz\" and match the same pattern.\n// The reverse (ae → ä) would be wrong: \"Tage\" has \"ae\" as a\n// coincidence, not as an umlaut transliteration. Forward expansion\n// is unambiguous because the source string already has the\n// umlaut — the expansion only affects the matched form.\n// 3. Strip combining marks via NFD. \"Miércoles\" → \"Miercoles\",\n// \"février\" → \"fevrier\", \"août\" → \"aout\". Pairs with the umlaut\n// expansion above so all four languages' accented forms collapse\n// to one canonical unaccented form for matching.\n//\n// Both sides of the match — input string AND the weekday/month name\n// lists — get the same normalization applied, so this is symmetric.\nfunction normalizeForMatch(s: string): string {\n return s.toLowerCase()\n .replace(/ä/g, 'ae')\n .replace(/ö/g, 'oe')\n .replace(/ü/g, 'ue')\n .replace(/ß/g, 'ss')\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '');\n}\n\n// Standard Levenshtein edit distance (insert/delete/substitute, cost 1\n// each). Used only by the opt-in fuzzy layer below — the exact matcher\n// pass never calls this. Iterative DP over two rows, not the full\n// matrix, since only the previous row is ever needed.\nfunction levenshtein(a: string, b: string): number {\n /* c8 ignore start @preserve -- unreachable through the only call\n * site (fuzzyCorrectEnglish): `a` is always a word that already\n * failed the `vocabulary.includes(word)` exact-match check, so\n * a === b never holds against any `b` drawn from that same\n * vocabulary; and neither `a` (split from a non-empty normalized\n * string) nor `b` (a vocabulary entry) is ever empty. Kept as\n * general-purpose guards in case levenshtein() gets a second caller\n * later. */\n if (a === b) return 0;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n /* c8 ignore stop @preserve */\n let prev = new Array(b.length + 1);\n let curr = new Array(b.length + 1);\n for (let j = 0; j <= b.length; j++) prev[j] = j;\n for (let i = 1; i <= a.length; i++) {\n curr[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n curr[j] = Math.min(\n prev[j] + 1, // deletion\n curr[j - 1] + 1, // insertion\n prev[j - 1] + cost, // substitution\n );\n }\n [prev, curr] = [curr, prev];\n }\n return prev[b.length];\n}\n\n// Max edit distance a fuzzy correction is allowed to bridge. 2 covers\n// the common single-finger-slip and single-transposed-letter typo cases\n// (\"tommorow\" is distance 1 from \"tomorrow\"; \"tuesady\" is distance 2\n// from \"tuesday\" — a transposition costs 2 under simple Levenshtein,\n// which doesn't special-case adjacent-swap as a single edit) without\n// opening the door to correcting a word into something only vaguely\n// similar. Deliberately conservative — this is a typo-tolerance layer,\n// not a \"guess what they meant\" layer; the library's whole design\n// philosophy elsewhere (parse()'s strict-by-default ambiguity handling,\n// the lenient opt-in) is to bound how much guessing is allowed and make\n// the caller ask for it explicitly.\nconst FUZZY_MAX_DISTANCE = 2;\nconst MAX_RELATIVE_INPUT_LENGTH = 4096;\nconst MAX_RELATIVE_WORDS = 32;\n\n// English-only fuzzy vocabulary. Anything a matcher's regex treats as a\n// fixed keyword (not a captured number) belongs here — weekday names,\n// month names (long and short), and the marker words the matchers\n// switch on (today/tomorrow/yesterday/next/last/this/in/ago and the\n// unit words day/week/month/year). Numbers and ordinal suffixes are\n// deliberately excluded: \"5th\" vs \"5tj\" isn't a word-shaped typo this\n// layer is trying to solve, and correcting digits is a much easier way\n// to silently produce a wrong date than correcting a weekday name is.\n//\n// Scoped to English only for this pass — the other three grammars have\n// enough positional/multi-word-marker variation (French's \"il y a\",\n// Spanish's dual pre/post weekday-modifier shapes) that a single\n// word-substitution corrector isn't a good fit for all of them without\n// per-language tuning this change doesn't attempt. parseRelative()\n// throws a clear scope-limited error if { fuzzy: true } is combined\n// with a non-English locale, rather than silently no-op-ing.\nfunction buildEnglishFuzzyVocabulary(): string[] {\n return [\n ...ENGLISH_WEEKDAYS,\n ...ENGLISH_MONTHS,\n ...ENGLISH_MONTH_SHORT,\n 'today', 'tomorrow', 'yesterday',\n 'next', 'last', 'this',\n 'in', 'ago',\n 'day', 'days', 'week', 'weeks', 'month', 'months', 'year', 'years',\n ].map(normalizeForMatch);\n}\n\n// Lazily built and cached — the vocabulary is static per process, no\n// need to rebuild the normalized list on every fuzzy call.\nlet englishFuzzyVocabulary: readonly string[] | undefined;\nfunction getEnglishFuzzyVocabulary(): readonly string[] {\n if (!englishFuzzyVocabulary) englishFuzzyVocabulary = Object.freeze(buildEnglishFuzzyVocabulary());\n return englishFuzzyVocabulary;\n}\n\n// Attempts a word-level fuzzy correction of `normalized` against the\n// English vocabulary, returning a corrected string or undefined if no\n// correction was needed/possible. Tokenizes on whitespace; each token\n// that isn't already an exact vocabulary word (or a pure number/ordinal,\n// which passes through untouched) gets replaced with its closest\n// vocabulary match, if one exists within FUZZY_MAX_DISTANCE. If a token\n// has no sufficiently-close vocabulary match, it's left as-is — the\n// re-attempted exact match will then fail on that token same as before,\n// which is the correct outcome for \"this word isn't a typo of anything\n// we know, it's just not a phrase we support.\"\nfunction fuzzyCorrectEnglish(normalized: string): string | undefined {\n const vocabulary = getEnglishFuzzyVocabulary();\n const words = normalized.split(' ');\n if (normalized.length > MAX_RELATIVE_INPUT_LENGTH || words.length > MAX_RELATIVE_WORDS) {\n throw new RangeError(\n `temporal-fmt: parseRelative fuzzy input is too large (maximum ${MAX_RELATIVE_INPUT_LENGTH} characters and ${MAX_RELATIVE_WORDS} words).`,\n );\n }\n let changed = false;\n const corrected = words.map((word) => {\n // Pure digits, or digits with an ordinal suffix (st/nd/rd/th) —\n // never touched by fuzzy correction. See the vocabulary comment\n // above for why.\n if (/^\\d+(?:st|nd|rd|th)?$/.test(word)) return word;\n // Already an exact vocabulary word — nothing to correct.\n if (vocabulary.includes(word)) return word;\n\n let best: string | undefined;\n let bestDist = FUZZY_MAX_DISTANCE + 1;\n for (const candidate of vocabulary) {\n const dist = levenshtein(word, candidate);\n if (dist < bestDist) {\n bestDist = dist;\n best = candidate;\n }\n }\n if (best !== undefined && bestDist <= FUZZY_MAX_DISTANCE) {\n changed = true;\n return best;\n }\n return word;\n });\n\n return changed ? corrected.join(' ') : undefined;\n}\n\ninterface TemporalFieldBag {\n year?: number;\n month?: number;\n day?: number;\n dayOfWeek?: number;\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n}\n\nfunction readYear(reference: TemporalFieldBag): number {\n if (typeof reference.year !== 'number') {\n throw new Error('temporal-fmt: parseRelative reference date is missing year.');\n }\n return reference.year;\n}\nfunction readMonth(reference: TemporalFieldBag): number {\n if (typeof reference.month !== 'number') {\n throw new Error('temporal-fmt: parseRelative reference date is missing month.');\n }\n return reference.month;\n}\nfunction readDay(reference: TemporalFieldBag): number {\n if (typeof reference.day !== 'number') {\n throw new Error('temporal-fmt: parseRelative reference date is missing day.');\n }\n return reference.day;\n}\n\nfunction extractDayOfWeek(reference: TemporalFieldBag): number {\n const dow = reference.dayOfWeek;\n if (typeof dow !== 'number') {\n throw new Error(\n 'temporal-fmt: parseRelative needs a reference date exposing dayOfWeek (a Temporal.PlainDate / PlainDateTime / ZonedDateTime).'\n );\n }\n return dow;\n}\n\n// Build an alternation regex fragment from a name list, normalized for\n// matching. Longest-first so \"September\" wins over \"Sep\" in the same\n// match position. The caller is responsible for any wrapping groups\n// or anchors — this just produces the inner alternation.\nfunction nameAlternation(names: string[]): string {\n const normalized = names.map(normalizeForMatch);\n // Dedupe — some locales render the long and short form identically\n // (English \"May\" is the same in both MMMM and MMM lists). Keep both\n // in the alternation rather than deduping, since duplicates in a\n // regex alternation don't change behavior and the dedupe would just\n // be a micro-optimization.\n // Sort longest-first so a longer name wins over its own prefix.\n const sorted = [...normalized].sort((a, b) => b.length - a.length);\n // Escape regex metacharacters — names shouldn't contain any, but\n // belt-and-braces avoids a future \"M+1\" month name from breaking\n // the alternation silently.\n return sorted.map((n) => n.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')).join('|');\n}\n\n// Resolves to a PlainDate by adding `days` to the reference. Used for\n// weekday refs and the today/tomorrow/yesterday family.\nfunction buildPlainDate(temporal: { PlainDate: { from: (fields: Record<string, number>, options?: { overflow?: 'constrain' | 'reject' }) => unknown } }, year: number, month: number, day: number): unknown {\n return temporal.PlainDate.from({ year, month, day }, { overflow: 'reject' });\n}\n\nfunction addDays(\n temporal: { PlainDate: { from: (fields: Record<string, number>) => unknown } },\n reference: TemporalFieldBag,\n days: number,\n): unknown {\n // Build the reference as a real PlainDate so we can use Temporal's\n // own add() for date arithmetic — calendar-correct (handles month\n // boundaries, leap years, etc.) so we don't have to reimplement it.\n const refDate = temporal.PlainDate.from({\n year: readYear(reference),\n month: readMonth(reference),\n day: readDay(reference),\n }) as { add: (duration: Record<string, number>) => unknown };\n return refDate.add({ days });\n}\n\nfunction addUnits(\n temporal: { PlainDate: { from: (fields: Record<string, number>) => unknown } },\n reference: TemporalFieldBag,\n count: number,\n unit: 'day' | 'week' | 'month' | 'year',\n): unknown {\n const refDate = temporal.PlainDate.from({\n year: readYear(reference),\n month: readMonth(reference),\n day: readDay(reference),\n }) as { add: (duration: Record<string, number>) => unknown };\n const duration: Record<string, number> = {};\n if (unit === 'day') duration.days = count;\n if (unit === 'week') duration.weeks = count;\n if (unit === 'month') duration.months = count;\n if (unit === 'year') duration.years = count;\n return refDate.add(duration);\n}\n\n// \"next X\" — strictly future next occurrence. Said on a Tuesday:\n// \"next Tuesday\" = 7 days from now, not today. Rationale: \"this\n// Tuesday\" handles the same-week case, so \"next Tuesday\" staying\n// strictly-future gives the two phrases distinct, non-overlapping\n// meanings. Documented in README \"parseRelative\".\n//\n// \"last X\" — strictly past most recent occurrence. Symmetric to \"next\".\n//\n// \"this X\" — the X of the current ISO week (Mon..Sun). Can land on\n// today, past, or future depending on where in the week today falls.\n//\n// All three resolve the same way across the four supported languages\n// (en/es/fr/de): the equivalent idiom in each language maps to one of\n// these three rel words. The natural-language reading is consistent\n// — \"next Tuesday\" said on a Tuesday means next week's Tuesday in\n// every language we support.\nfunction weekdayOffset(rel: 'next' | 'last' | 'this', refDow: number, targetDow: number): number {\n // refDow and targetDow are both 1..7 (ISO Mon=1..Sun=7).\n if (rel === 'next') {\n let diff = targetDow - refDow;\n if (diff <= 0) diff += 7; // 0 (today) → 7, negative → wrap forward\n return diff; // 1..7\n }\n if (rel === 'last') {\n let diff = targetDow - refDow;\n if (diff >= 0) diff -= 7; // 0 (today) → -7, positive → wrap backward\n return diff; // -7..-1\n }\n // rel === 'this' — X of the current week. Can be today, past, or future.\n return targetDow - refDow; // -6..+6\n}\n\n// \"March 5th\" without a year → resolve to the next occurrence of that\n// month/day. If today is that date, return today. Otherwise, if it's\n// already past this year, return next year's occurrence.\n//\n// \"Next occurrence\" semantics: future-leaning. Documented in README\n// as the chosen behavior. The alternative (\"nearest in time, past or\n// future\") would mean \"March 5th\" said on March 6 returns yesterday —\n// counterintuitive for the typical \"next birthday\"/\"next deadline\"\n// use case this kind of phrase tends to drive.\nfunction resolveToNextOccurrence(\n temporal: {\n PlainDate: {\n from: (fields: Record<string, number>, options?: { overflow?: 'constrain' | 'reject' }) => unknown;\n compare?: (one: unknown, two: unknown) => number;\n };\n },\n reference: TemporalFieldBag,\n month: number,\n day: number,\n): unknown {\n const refYear = readYear(reference);\n const refDate = temporal.PlainDate.from({\n year: refYear,\n month: readMonth(reference),\n day: readDay(reference),\n });\n // PlainDate.compare is a static method on the namespace, not an\n // instance method — that's why it's called off temporal.PlainDate\n // rather than off an instance below. Checked outside the try/catch\n // below on purpose: that block's catch is scoped to Feb-29-style\n // overflow errors from from(), and silently retries with next year's\n // date. A missing-compare error thrown from inside that try would get\n // caught by the same handler and swallowed by that retry (next year's\n // from() usually succeeds), masking the real problem instead of\n // surfacing it.\n if (!temporal.PlainDate.compare) {\n throw new Error('temporal-fmt: parseRelative needs Temporal.PlainDate.compare to resolve month-day phrases; the active implementation does not expose it.');\n }\n // try this year first; if Feb 29 in a non-leap year, Temporal will\n // throw via overflow: 'reject' — fall through to next year.\n try {\n const thisYear = temporal.PlainDate.from({ year: refYear, month, day }, { overflow: 'reject' });\n // Returns -1 / 0 / 1.\n if (temporal.PlainDate.compare(thisYear, refDate) >= 0) {\n // today or in the future → use this year's occurrence\n return thisYear;\n }\n // already past this year → next year's occurrence\n return temporal.PlainDate.from({ year: refYear + 1, month, day }, { overflow: 'reject' });\n } catch (err) {\n // Feb 29 in a non-leap year, or similar. Try next year — if the\n // caller asked for \"Feb 29\" said in a non-leap year, next year may\n // also not be leap, in which case the inner from() will throw and\n // surface a clear error rather than silently landing on Feb 28.\n try {\n return temporal.PlainDate.from({ year: refYear + 1, month, day }, { overflow: 'reject' });\n } catch {\n throw new Error(\n `temporal-fmt: parseRelative can't resolve month ${month} day ${day} — ` +\n `it isn't a valid date in either ${refYear} or ${refYear + 1}. ` +\n `Original error: ${(err as Error).message}`\n );\n }\n }\n}\n\n// Each language provides a list of matchers. The shared engine\n// iterates them in order and returns the first match. A matcher is a\n// (regex, resolver) pair — the regex captures the structural pieces\n// (count, unit name, weekday name, etc.), the resolver turns them\n// into a Temporal.PlainDate using the shared helpers above.\ninterface ResolveContext {\n temporal: TemporalNamespace;\n reference: TemporalFieldBag;\n}\n\ninterface Matcher {\n pattern: RegExp;\n resolve: (match: RegExpMatchArray, ctx: ResolveContext) => unknown;\n}\n\ninterface RelativeDateGrammar {\n // Single-line description of supported phrase classes, included in\n // the \"doesn't recognize\" error so the caller knows what to try.\n supportedHint: string;\n // Ordered matchers; first match wins.\n matchers: Matcher[];\n}\n\nfunction weekdayIndexFromName(name: string, names: string[]): number {\n const normalized = normalizeForMatch(name);\n const idx = names.findIndex((n) => normalizeForMatch(n) === normalized);\n /* c8 ignore start @preserve -- unreachable: every caller passes a\n * name captured by nameAlternation(names), which builds its regex\n * alternation from this same list under the same normalizeForMatch\n * transform. The regex can't match anything findIndex() wouldn't\n * also find here. Defensive throw kept for the type checker and as\n * a tripwire if that invariant ever breaks. Ignore comment sits on\n * the `if` itself, not just the throw inside it — c8 tracks the\n * branch outcome (was the true side ever taken) separately from the\n * statements inside, so excluding only the inner throw still leaves\n * the branch itself flagged as uncovered. */\n /* c8 ignore next */\n if (idx < 0) {\n throw new Error(`temporal-fmt: parseRelative internal error — weekday \"${name}\" not in names list.`);\n }\n /* c8 ignore stop @preserve */\n return idx + 1;\n}\n\nfunction monthIndexFromName(name: string, longNames: string[], shortNames: string[] = []): number {\n const normalized = normalizeForMatch(name);\n const longIdx = longNames.findIndex((n) => normalizeForMatch(n) === normalized);\n if (longIdx >= 0) return longIdx + 1;\n const shortIdx = shortNames.findIndex((n) => normalizeForMatch(n) === normalized);\n /* c8 ignore next */\n if (shortIdx >= 0) return shortIdx + 1;\n /* c8 ignore start @preserve -- unreachable: every caller passes a name\n * captured by nameAlternation([...longNames, ...shortNames]), so the\n * regex alternation and these two findIndex() scans are built from\n * the same lists under the same normalizeForMatch transform. Kept as\n * a tripwire for the type checker in case that invariant ever breaks. */\n throw new Error(`temporal-fmt: parseRelative internal error — month \"${name}\" not in names list.`);\n /* c8 ignore stop @preserve */\n /* c8 ignore next -- defensive block is unreachable by construction. */\n}\n\n// English grammar — also the default when no locale is supplied. The\n// regexes here are the same ones the pre-change parseRelative() used\n// inline; they've just been pulled into a matcher list so the matching\n// engine can iterate them the same way it does for es/fr/de.\nconst ENGLISH_WEEKDAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];\nconst ENGLISH_MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\nconst ENGLISH_MONTH_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\n\nconst ENGLISH_GRAMMAR: RelativeDateGrammar = {\n supportedHint: 'Supported: weekday refs (\"next Tuesday\"), day offsets (\"today\"/\"tomorrow\"/\"yesterday\"), unit offsets (\"in 3 days\", \"2 weeks ago\"), and month-day (\"March 5th\").',\n matchers: [\n // today / tomorrow / yesterday — exact match, most rigid shape.\n // Checked first because they're the most common phrase class.\n {\n pattern: /^today$/i,\n resolve: (_m, ctx) => buildPlainDate(ctx.temporal, readYear(ctx.reference), readMonth(ctx.reference), readDay(ctx.reference)),\n },\n {\n pattern: /^tomorrow$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, 1),\n },\n {\n pattern: /^yesterday$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, -1),\n },\n // weekday references: \"next/last/this Tuesday\". Capture the relative\n // word and the weekday name separately, then resolve via +7 / -7.\n {\n pattern: new RegExp(`^(next|last|this)\\\\s+(${nameAlternation(ENGLISH_WEEKDAYS)})$`, 'i'),\n resolve: (m, ctx) => {\n const rel = m[1]!.toLowerCase() as 'next' | 'last' | 'this';\n const targetDow = weekdayIndexFromName(m[2]!, ENGLISH_WEEKDAYS);\n const refDow = extractDayOfWeek(ctx.reference);\n return addDays(ctx.temporal, ctx.reference, weekdayOffset(rel, refDow, targetDow));\n },\n },\n // unit offsets: \"in 3 days\", \"2 weeks ago\", \"in 1 month\", \"1 year ago\".\n // Two shapes share this matcher — leading \"in\" (future) or trailing\n // \"ago\" (past). Both lead with <number> <unit>.\n {\n pattern: /^(in\\s+)?(\\d+)\\s+(day|week|month|year)s?(?:\\s+ago)?$/i,\n resolve: (m, ctx) => {\n const inPrefix = m[1];\n const count = m[2]!;\n const unitName = m[3]!.toLowerCase() as 'day' | 'week' | 'month' | 'year';\n // Disambiguate future vs past: \"in N units\" is always future; \"N\n // units ago\" is always past. A bare \"N units\" without either is\n // a sign error — throw, since neither direction is implied and\n // guessing is exactly what this library refuses to do.\n const hasIn = !!inPrefix;\n const hasAgo = /\\bago\\b/i.test(m[0]!);\n if (!hasIn && !hasAgo) {\n throw new Error(\n `temporal-fmt: parseRelative can't tell whether \"${m[0]}\" is past or future — ` +\n `use \"in ${count} ${unitName}s\" or \"${count} ${unitName}s ago\".`\n );\n }\n // Contradictory markers: the regex tolerates \"in 3 days ago\"\n // (both a leading \"in\" and a trailing \"ago\"), which used to\n // silently resolve as FUTURE. The library's whole posture is\n // throw-rather-than-guess — a contradiction is worse than a\n // missing marker, not something to quietly pick a side on.\n if (hasIn && hasAgo) {\n throw new Error(\n `temporal-fmt: parseRelative got contradictory direction markers in \"${m[0]}\" — ` +\n `\"in N ${unitName}s\" is future and \"N ${unitName}s ago\" is past; use one or the other.`\n );\n }\n const sign = hasIn ? 1 : -1;\n return addUnits(ctx.temporal, ctx.reference, sign * Number(count), unitName);\n },\n },\n // month-day without year, e.g. \"March 5th\", \"March 5\", \"March 5, 2026\"\n // (year is ignored if present). The ordinal suffix is decorative —\n // strip it. The day-of-month is a 1- or 2-digit number.\n {\n pattern: new RegExp(`^(${nameAlternation([...ENGLISH_MONTHS, ...ENGLISH_MONTH_SHORT])})\\\\s+(\\\\d{1,2})(?:st|nd|rd|th)?(?:,?\\\\s*(\\\\d{4}))?$`, 'i'),\n resolve: (m, ctx) => {\n const month = monthIndexFromName(m[1]!, ENGLISH_MONTHS, ENGLISH_MONTH_SHORT);\n const day = Number(m[2]!);\n return resolveToNextOccurrence(ctx.temporal, ctx.reference, month, day);\n },\n },\n ],\n};\n\n// Spanish grammar. Distinct phrase shapes from English:\n// - \"hace 2 semanas\" (past unit offset) — distinct word \"hace\", not\n// the English \"X units ago\" suffix shape.\n// - \"5 de marzo\" — day-first, with required \"de\" between day and\n// month, opposite of English \"March 5\".\n// - \"el próximo lunes\" / \"lunes pasado\" — weekday ref has the relative\n// word sometimes as a prefix with article, sometimes as a suffix.\n//\n// All four phrase classes the English grammar supports have Spanish\n// equivalents here.\nconst SPANISH_WEEKDAYS = ['lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado', 'domingo'];\nconst SPANISH_MONTHS = ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', 'julio', 'agosto', 'septiembre', 'octubre', 'noviembre', 'diciembre'];\n// Spanish month abbreviations vary by region (\"set\" vs \"sept\" for\n// September). Sticking with the most common ICU form per locale.\nconst SPANISH_MONTH_SHORT = ['ene', 'feb', 'mar', 'abr', 'may', 'jun', 'jul', 'ago', 'sept', 'oct', 'nov', 'dic'];\n\nconst SPANISH_GRAMMAR: RelativeDateGrammar = {\n supportedHint: 'Frases soportadas: referencias de día de la semana (\"el próximo lunes\", \"el lunes pasado\", \"este martes\"), offsets de día (\"hoy\"/\"mañana\"/\"ayer\"), offsets de unidad (\"en 3 días\", \"hace 2 semanas\"), y mes-día (\"5 de marzo\").',\n matchers: [\n {\n pattern: /^hoy$/i,\n resolve: (_m, ctx) => buildPlainDate(ctx.temporal, readYear(ctx.reference), readMonth(ctx.reference), readDay(ctx.reference)),\n },\n {\n pattern: /^ma[ñn]ana$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, 1),\n },\n {\n pattern: /^ayer$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, -1),\n },\n // weekday references. Spanish has three common shapes, all meaning\n // the same thing per rel word:\n // \"el próximo lunes\" / \"próximo lunes\" → next\n // \"el lunes próximo\" → next (suffix variant)\n // \"el lunes pasado\" / \"lunes pasado\" → last\n // \"este lunes\" → this\n // Capture the rel word from whichever shape matched, then resolve\n // the same way English does.\n {\n pattern: new RegExp(\n `^(?:el\\\\s+)?(?:(pr[oó]ximo|pasado)\\\\s+(${nameAlternation(SPANISH_WEEKDAYS)})|(${nameAlternation(SPANISH_WEEKDAYS)})\\\\s+(pr[oó]ximo|pasado)|este\\\\s+(${nameAlternation(SPANISH_WEEKDAYS)}))$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n let relWord: string;\n let weekdayName: string;\n if (m[1] && m[2]) {\n // prefix variant: \"próximo lunes\" / \"pasado lunes\"\n relWord = m[1]!;\n weekdayName = m[2]!;\n } else if (m[3] && m[4]) {\n // suffix variant: \"lunes próximo\" / \"lunes pasado\"\n weekdayName = m[3]!;\n relWord = m[4]!;\n } else {\n // \"este lunes\"\n relWord = 'este';\n weekdayName = m[5]!;\n }\n const rel = normalizeForMatch(relWord) === 'proximo' ? 'next' : relWord.toLowerCase() === 'este' ? 'this' : 'last';\n const targetDow = weekdayIndexFromName(weekdayName, SPANISH_WEEKDAYS);\n const refDow = extractDayOfWeek(ctx.reference);\n return addDays(ctx.temporal, ctx.reference, weekdayOffset(rel, refDow, targetDow));\n },\n },\n // unit offsets. Spanish uses distinct markers:\n // \"en 3 días\" / \"dentro de 3 días\" → future\n // \"hace 2 semanas\" → past\n // Both shapes lead with the marker, unlike English where one\n // shape leads and the other trails.\n {\n pattern: new RegExp(\n `^(?:(en|dentro\\\\s+de)\\\\s+(\\\\d+)\\\\s+(d[ií]a|semana|mes|a[ñn]o)s?|(\\\\d+)\\\\s+(d[ií]a|semana|mes|a[ñn]o)s?\\\\s+(hace))$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n let count: string;\n let unitWord: string;\n let sign: number;\n if (m[1] && m[2] && m[3]) {\n // future: \"en 3 días\" / \"dentro de 3 días\"\n count = m[2]!;\n unitWord = m[3]!;\n sign = 1;\n } else {\n // past: \"2 semanas hace\" — but the more natural Spanish is\n // \"hace 2 semanas\" (marker first). The regex above only\n // matches \"N units hace\"; that's a less common but\n // grammatical alternative. The primary past form \"hace N\n // unidades\" is matched by the next matcher.\n count = m[4]!;\n unitWord = m[5]!;\n sign = -1;\n }\n const unit = unitWordToEnglish(unitWord);\n return addUnits(ctx.temporal, ctx.reference, sign * Number(count), unit);\n },\n },\n // \"hace 2 semanas\" — the primary past-offset shape. Matcher kept\n // separate from the future \"en/dentro de\" matcher above because\n // Spanish word order differs between the two (marker-first for\n // past, marker-first for future too, but with different markers).\n {\n pattern: new RegExp(`^hace\\\\s+(\\\\d+)\\\\s+(d[ií]a|semana|mes|a[ñn]o)s?$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, -count, unit);\n },\n },\n // bare \"N <unit>\" without \"en\" / \"hace\" — throw, since direction\n // is ambiguous. Matched AFTER the directional shapes so the\n // directional ones win when their marker is present.\n {\n pattern: new RegExp(`^(\\\\d+)\\\\s+(d[ií]a|semana|mes|a[ñn]o)s?$`, 'i'),\n resolve: (m, _ctx) => {\n throw new Error(\n `temporal-fmt: parseRelative no puede decidir si \"${m[0]}\" es pasado o futuro — ` +\n `usa \"en ${m[1]} ${m[2]}s\" o \"hace ${m[1]} ${m[2]}s\".`\n );\n },\n },\n // month-day: \"5 de marzo\" (day first), \"5 de marzo de 2026\" (year\n // ignored if present). Day is 1-2 digits, with optional trailing\n // \".\" (rare in Spanish but tolerated).\n {\n pattern: new RegExp(\n `^(\\\\d{1,2})\\\\.?\\\\s+de\\\\s+(${nameAlternation([...SPANISH_MONTHS, ...SPANISH_MONTH_SHORT])})(?:\\\\s+de\\\\s+(\\\\d{4}))?$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n const day = Number(m[1]!);\n const month = monthIndexFromName(m[2]!, SPANISH_MONTHS, SPANISH_MONTH_SHORT);\n return resolveToNextOccurrence(ctx.temporal, ctx.reference, month, day);\n },\n },\n ],\n};\n\n// French grammar. Distinct from English/Spanish:\n// - \"il y a 2 semaines\" (past marker is a 3-word phrase, not a single word).\n// - \"mardi prochain\" — relative word is a SUFFIX on the weekday,\n// opposite of English \"next Tuesday\".\n// - \"5 mars\" — day-first, no \"de\" between day and month (unlike\n// Spanish's \"5 de marzo\").\nconst FRENCH_WEEKDAYS = ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'];\nconst FRENCH_MONTHS = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'];\nconst FRENCH_MONTH_SHORT = ['janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.', 'déc.'];\n\nconst FRENCH_GRAMMAR: RelativeDateGrammar = {\n supportedHint: 'Phrases prises en charge : références de jour de la semaine (\"lundi prochain\", \"mardi dernier\", \"ce mercredi\"), décalages de jour (\"aujourd\\'hui\"/\"demain\"/\"hier\"), décalages d\\'unité (\"dans 3 jours\", \"il y a 2 semaines\"), et mois-jour (\"5 mars\").',\n matchers: [\n {\n pattern: /^aujourd'hui$/i,\n resolve: (_m, ctx) => buildPlainDate(ctx.temporal, readYear(ctx.reference), readMonth(ctx.reference), readDay(ctx.reference)),\n },\n {\n pattern: /^demain$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, 1),\n },\n {\n pattern: /^hier$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, -1),\n },\n // weekday references: \"lundi prochain\" (next), \"lundi dernier\"\n // (last), \"ce lundi\" (this). The relative word follows the\n // weekday for next/last, precedes it for this.\n {\n pattern: new RegExp(\n `^(?:(${nameAlternation(FRENCH_WEEKDAYS)})\\\\s+(prochain|dernier)|ce\\\\s+(${nameAlternation(FRENCH_WEEKDAYS)}))$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n let rel: 'next' | 'last' | 'this';\n let weekdayName: string;\n if (m[1] && m[2]) {\n weekdayName = m[1]!;\n rel = m[2]!.toLowerCase() === 'prochain' ? 'next' : 'last';\n } else {\n rel = 'this';\n weekdayName = m[3]!;\n }\n const targetDow = weekdayIndexFromName(weekdayName, FRENCH_WEEKDAYS);\n const refDow = extractDayOfWeek(ctx.reference);\n return addDays(ctx.temporal, ctx.reference, weekdayOffset(rel, refDow, targetDow));\n },\n },\n // past: \"il y a 2 semaines\" — multi-word marker.\n {\n pattern: new RegExp(`^il\\\\s+y\\\\s+a\\\\s+(\\\\d+)\\\\s+(jour|semaine|mois|an|ann[eée]e)s?$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, -count, unit);\n },\n },\n // future: \"dans 3 jours\"\n {\n pattern: new RegExp(`^dans\\\\s+(\\\\d+)\\\\s+(jour|semaine|mois|an|ann[eée]e)s?$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, count, unit);\n },\n },\n // bare \"N <unit>\" without marker — throw.\n {\n pattern: new RegExp(`^(\\\\d+)\\\\s+(jour|semaine|mois|an|ann[eée]e)s?$`, 'i'),\n resolve: (m, _ctx) => {\n throw new Error(\n `temporal-fmt: parseRelative ne peut pas déterminer si \"${m[0]}\" est passé ou futur — ` +\n `utilisez \"dans ${m[1]} ${m[2]}s\" ou \"il y a ${m[1]} ${m[2]}s\".`\n );\n },\n },\n // month-day: \"5 mars\" (day first, no separator word). Year ignored.\n {\n pattern: new RegExp(\n `^(\\\\d{1,2})\\\\s+(${nameAlternation([...FRENCH_MONTHS, ...FRENCH_MONTH_SHORT])})(?:\\\\s+(\\\\d{4}))?$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n const day = Number(m[1]!);\n const month = monthIndexFromName(m[2]!, FRENCH_MONTHS, FRENCH_MONTH_SHORT);\n return resolveToNextOccurrence(ctx.temporal, ctx.reference, month, day);\n },\n },\n ],\n};\n\n// German grammar. Distinct from the others:\n// - Unit words pluralize with -n in the dative after \"in\"/\"vor\":\n// \"in 3 Tagen\" (vs nominative \"3 Tage\"). The regex accepts both\n// since callers may not always get the case right, and accepting\n// both doesn't introduce ambiguity.\n// - \"nächsten Dienstag\" — relative word precedes weekday as a\n// declined adjective, with the weekday capitalized as a noun.\n// - \"5. März\" — day-first with a period after the day number,\n// matching German date convention.\nconst GERMAN_WEEKDAYS = ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag'];\nconst GERMAN_MONTHS = ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'];\nconst GERMAN_MONTH_SHORT = ['Jan', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'];\n\nconst GERMAN_GRAMMAR: RelativeDateGrammar = {\n supportedHint: 'Unterstützte Phrasen: Wochentag-Bezüge (\"nächsten Dienstag\", \"letzten Freitag\", \"diesen Montag\"), Tages-Offsets (\"heute\"/\"morgen\"/\"gestern\"), Einheiten-Offsets (\"in 3 Tagen\", \"vor 2 Wochen\"), und Monat-Tag (\"5. März\").',\n matchers: [\n {\n pattern: /^heute$/i,\n resolve: (_m, ctx) => buildPlainDate(ctx.temporal, readYear(ctx.reference), readMonth(ctx.reference), readDay(ctx.reference)),\n },\n {\n pattern: /^morgen$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, 1),\n },\n {\n pattern: /^gestern$/i,\n resolve: (_m, ctx) => addDays(ctx.temporal, ctx.reference, -1),\n },\n // weekday references: \"nächsten Dienstag\" (next), \"letzten\n // Dienstag\" (last), \"diesen Dienstag\" (this). Adjective precedes\n // the weekday; case varies (nächsten/letzten/diesen all take the\n // weak-declension -en/-en/-en ending when no article, which is\n // convenient — one regex alternation covers all three.\n {\n pattern: new RegExp(`^(n(?:ae|a|ä)chsten|letzten|diesen)\\\\s+(${nameAlternation(GERMAN_WEEKDAYS)})$`, 'i'),\n resolve: (m, ctx) => {\n const adj = normalizeForMatch(m[1]!);\n const rel: 'next' | 'last' | 'this' = (adj === 'nachsten' || adj === 'naechsten') ? 'next' : adj === 'diesen' ? 'this' : 'last';\n const targetDow = weekdayIndexFromName(m[2]!, GERMAN_WEEKDAYS);\n const refDow = extractDayOfWeek(ctx.reference);\n return addDays(ctx.temporal, ctx.reference, weekdayOffset(rel, refDow, targetDow));\n },\n },\n // past: \"vor 2 Wochen\"\n {\n pattern: new RegExp(`^vor\\\\s+(\\\\d+)\\\\s+(Tag(?:e|n|en)?|Woche(?:n)?|Monat(?:e|n|en)?|Jahr(?:e|n|en)?)$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, -count, unit);\n },\n },\n // future: \"in 3 Tagen\"\n {\n pattern: new RegExp(`^in\\\\s+(\\\\d+)\\\\s+(Tag(?:e|n|en)?|Woche(?:n)?|Monat(?:e|n|en)?|Jahr(?:e|n|en)?)$`, 'i'),\n resolve: (m, ctx) => {\n const count = Number(m[1]!);\n const unit = unitWordToEnglish(m[2]!);\n return addUnits(ctx.temporal, ctx.reference, count, unit);\n },\n },\n // bare \"N <unit>\" without \"in\" or \"vor\" — throw.\n {\n pattern: new RegExp(`^(\\\\d+)\\\\s+(Tag(?:e|n|en)?|Woche(?:n)?|Monat(?:e|n|en)?|Jahr(?:e|n|en)?)$`, 'i'),\n resolve: (m, _ctx) => {\n throw new Error(\n `temporal-fmt: parseRelative kann nicht erkennen, ob \"${m[0]}\" Vergangenheit oder Zukunft ist — ` +\n `verwende \"in ${m[1]} ${m[2]}\" oder \"vor ${m[1]} ${m[2]}\".`\n );\n },\n },\n // month-day: \"5. März\" (day-first with period). Year ignored.\n {\n pattern: new RegExp(\n `^(\\\\d{1,2})\\\\.?\\\\s+(${nameAlternation([...GERMAN_MONTHS, ...GERMAN_MONTH_SHORT, 'Maerz', 'Maer'])})(?:\\\\s+(\\\\d{4}))?$`,\n 'i',\n ),\n resolve: (m, ctx) => {\n const day = Number(m[1]!);\n const month = monthIndexFromName(m[2]!, GERMAN_MONTHS, GERMAN_MONTH_SHORT);\n return resolveToNextOccurrence(ctx.temporal, ctx.reference, month, day);\n },\n },\n ],\n};\n\nconst GRAMMARS: Record<string, RelativeDateGrammar> = {\n en: ENGLISH_GRAMMAR,\n es: SPANISH_GRAMMAR,\n fr: FRENCH_GRAMMAR,\n de: GERMAN_GRAMMAR,\n};\n\n// Pick a grammar for a locale. Falls back to English for languages we\n// don't have a grammar for (Italian, Portuguese, etc.) rather than\n// throwing — best-effort, matches how formatDistance treats unknown\n// locales (Intl.RelativeTimeFormat accepts them; here we fall back to\n// English so the call still succeeds with reasonable output).\nfunction grammarForLocale(locale: string | undefined): RelativeDateGrammar {\n if (!locale) return ENGLISH_GRAMMAR;\n try {\n // Intl.Locale requires BCP-47 hyphens — same normalization as the\n // other locale-handling code in this library.\n const tag = new Intl.Locale(locale.replace(/_/g, '-'));\n const lang = tag.language.toLowerCase();\n return GRAMMARS[lang] ?? ENGLISH_GRAMMAR;\n } catch {\n // Malformed locale tag — fall back to English. The actual Intl\n // call downstream will throw if the tag is genuinely unusable,\n // which is a better surface for that error than here.\n return ENGLISH_GRAMMAR;\n }\n}\n\n// Language subtag of a locale option, for dispatching to grammars\n// registered via registerRelativeGrammar(). Mirrors grammarForLocale's\n// normalization and fallback.\nfunction languageOf(locale: string | undefined): string {\n if (!locale) return 'en';\n try {\n return new Intl.Locale(locale.replace(/_/g, '-')).language.toLowerCase();\n } catch {\n return 'en';\n }\n}\n\n// Map a per-language unit word back to the English unit name the\n// shared addUnits() helper expects. Each language contributes its own\n// regex alternation of unit words; this function normalizes the\n// captured word back to a unit enum value.\nfunction unitWordToEnglish(word: string): 'day' | 'week' | 'month' | 'year' {\n const w = normalizeForMatch(word);\n // English\n /* c8 ignore next */\n if (w === 'day' || w === 'week' || w === 'month' || w === 'year') return w;\n // Spanish (accent-stripped)\n if (w === 'dia') return 'day';\n if (w === 'semana') return 'week';\n if (w === 'mes') return 'month';\n if (w === 'ano' || w === 'año') return 'year';\n // French\n if (w === 'jour') return 'day';\n if (w === 'semaine') return 'week';\n if (w === 'mois') return 'month';\n if (w === 'an' || w === 'annee') return 'year';\n // German\n if (w === 'tag' || w === 'tagen') return 'day';\n if (w === 'woche' || w === 'wochen') return 'week';\n if (w === 'monat' || w === 'monaten') return 'month';\n /* c8 ignore next */\n if (w === 'jahr' || w === 'jahren') return 'year';\n /* c8 ignore start @preserve -- unreachable: every caller passes a word\n * captured by a regex alternation built from exactly these unit-word\n * forms (day/week/month/year across en/es/fr/de), so the branches\n * above already cover every string that can reach this function.\n * Kept as a tripwire for the type checker in case a grammar adds a\n * unit word here without a matching regex update. */\n throw new Error(`temporal-fmt: parseRelative internal error — unrecognized unit word \"${word}\".`);\n /* c8 ignore stop @preserve */\n /* c8 ignore next -- defensive block is unreachable by construction. */\n}\n\n// Reference: kept exported for the unit tests that need it. The other\n// helpers above are not exported since tests only need to drive\n// parseRelative() through the public API + this one constant for the\n// Tuesday-on-Tuesday fixture.\nexport const WEEKDAY_NAMES = ENGLISH_WEEKDAYS;\nexport const MONTH_NAMES = ENGLISH_MONTHS;\n// Exported for the localeVocab-style stub-test pattern in case a future\n// test wants to verify a grammar's name list against Intl's actual\n// output for that locale — same pattern localeVocab.test.js uses to\n// catch a mismatch between what format() produces and what parse()\n// expects.\nexport const SPANISH_MONTH_NAMES = SPANISH_MONTHS;\nexport const FRENCH_MONTH_NAMES = FRENCH_MONTHS;\nexport const GERMAN_MONTH_NAMES = GERMAN_MONTHS;\nexport const SPANISH_WEEKDAY_NAMES = SPANISH_WEEKDAYS;\nexport const FRENCH_WEEKDAY_NAMES = FRENCH_WEEKDAYS;\nexport const GERMAN_WEEKDAY_NAMES = GERMAN_WEEKDAYS;\nvoid WEEKDAY_NAMES;\nvoid MONTH_NAMES;\n\nexport interface ParseRelativeOptions extends FormatOptions {\n /**\n * Opt-in typo tolerance. When the input doesn't match any phrase\n * exactly, retry after correcting individual words (weekday names,\n * month names, and marker words like \"next\"/\"ago\"/\"tomorrow\") that\n * are within a small edit distance of a known word — e.g.\n * \"tommorow\" → \"tomorrow\", \"next tuesady\" → \"next tuesday\". Numbers\n * are never touched.\n *\n * Off by default, matching this library's throw-rather-than-guess\n * philosophy elsewhere (parse()'s `lenient` option is the same shape\n * of opt-in). English only for this option currently — combining\n * `fuzzy: true` with a non-English `locale` throws rather than\n * silently skipping the fuzzy pass.\n *\n * If no correction produces a recognized phrase, throws the same\n * \"doesn't recognize\" error the exact pass would have thrown.\n */\n fuzzy?: boolean;\n}\n\n/**\n * Resolve common relative-date phrases against a reference date,\n * returning a Temporal.PlainDate. Supports English by default, plus\n * Spanish (es), French (fr), and German (de) via the `locale` option.\n *\n * Supported phrase classes (with examples per language):\n *\n * - weekday refs: \"next Tuesday\" / \"el próximo martes\" / \"mardi prochain\" / \"nächsten Dienstag\"\n * - day offsets: \"today\" / \"hoy\" / \"aujourd'hui\" / \"heute\" (and tomorrow/yesterday equivalents)\n * - unit offsets: \"in 3 days\" / \"en 3 días\" / \"dans 3 jours\" / \"in 3 Tagen\"\n * - month-day without year: \"March 5th\" / \"5 de marzo\" / \"5 mars\" / \"5. März\"\n *\n * Ambiguous-case handling is consistent across all four languages:\n * \"next X\" said on X (today is the named weekday) means 7 days from\n * now, not today. \"last X\" said on X means 7 days ago. See README\n * \"parseRelative\" for the documented behavior of each ambiguous case.\n *\n * Throws a descriptive error for any phrase it doesn't recognize in\n * the target language, rather than guessing. A bare \"5 days\" without\n * \"in\" or \"ago\" (or the per-language equivalent) throws with a message\n * pointing at the disambiguation options.\n *\n * Returns a Temporal.PlainDate for every supported phrase. Time-of-day\n * extensions like \"next Tuesday at 3pm\" aren't supported in this pass.\n */\nexport function parseRelative(\n input: string,\n referenceDate: unknown,\n options: ParseRelativeOptions = {},\n): unknown {\n const reference = referenceDate as TemporalFieldBag;\n const temporal = getTemporal();\n\n // Trim, collapse internal whitespace, strip diacritics, and lowercase.\n // Whitespace normalization is shared with the pre-change behavior;\n // diacritic stripping pairs with nameAlternation()'s normalization so\n // \"mi[eé]rcoles\" and \"miercoles\" both match the same pattern.\n // Lowercasing matches the case-insensitive regex flag explicitly so\n // the user's input never gets case-swapped on its way through the\n // matcher (the regexes are 'i'-flagged, but normalizing here keeps\n // the original-trimmed-string echo in error messages predictable).\n const trimmed = (input ?? '').trim().replace(/\\s+/g, ' ');\n if (trimmed.length === 0) {\n throw new Error('temporal-fmt: parseRelative got an empty input string.');\n }\n if (trimmed.length > MAX_RELATIVE_INPUT_LENGTH) {\n throw new RangeError(\n `temporal-fmt: parseRelative input is too large (maximum ${MAX_RELATIVE_INPUT_LENGTH} characters).`,\n );\n }\n // For error messages, keep the user's original spelling (with accents)\n // so the echo in the \"doesn't recognize\" error matches what they\n // typed. The matching itself uses the diacritic-stripped form so\n // \"mi[eé]rcoles\" / \"miercoles\" / \"MI[ÉE]RCOLES\" all match the same\n // pattern without forcing the user to remember the accent.\n const normalized = normalizeForMatch(trimmed);\n\n const grammar = grammarForLocale(options.locale);\n const ctx: ResolveContext = { temporal, reference };\n\n // Registered grammars (registerRelativeGrammar) take precedence over\n // the built-in ones for their language — that's the documented\n // contract in relativeGrammar.ts (\"try registered grammars before\n // falling back to the built-in ones\"). This wiring was missing\n // entirely before: registered grammars were stored and listed but\n // never consulted, so the extension point silently did nothing.\n // Returns null quickly when nothing is registered for the language.\n const registered = tryRegisteredGrammar(languageOf(options.locale), trimmed, {\n year: reference.year as number,\n month: reference.month as number,\n day: reference.day as number,\n dayOfWeek: reference.dayOfWeek as number,\n });\n if (registered !== null) {\n return registered;\n }\n\n const tryMatch = (text: string): unknown | typeof NO_MATCH => {\n for (const matcher of grammar.matchers) {\n const match = text.match(matcher.pattern);\n if (match) {\n return matcher.resolve(match, ctx);\n }\n }\n return NO_MATCH;\n };\n\n const exactResult = tryMatch(normalized);\n if (exactResult !== NO_MATCH) {\n return exactResult;\n }\n\n if (options.fuzzy) {\n // Fuzzy mode is English-only for this pass — see the vocabulary\n // comment above fuzzyCorrectEnglish for why the other three\n // grammars aren't covered. Fail loudly rather than silently\n // skipping the fuzzy attempt, so a caller relying on fuzzy mode\n // for, say, French input doesn't get a confusing \"doesn't\n // recognize\" error with no indication fuzzy matching never ran.\n if (grammar !== ENGLISH_GRAMMAR) {\n throw new Error(\n `temporal-fmt: parseRelative's { fuzzy: true } option currently only supports English. ` +\n `Pass no locale (or locale: 'en'), or omit { fuzzy: true } for this locale.`\n );\n }\n const corrected = fuzzyCorrectEnglish(normalized);\n if (corrected !== undefined) {\n const fuzzyResult = tryMatch(corrected);\n if (fuzzyResult !== NO_MATCH) {\n return fuzzyResult;\n }\n }\n }\n\n throw new Error(\n `temporal-fmt: parseRelative doesn't recognize \"${trimmed}\". ` +\n grammar.supportedHint\n );\n}\n\n// Sentinel distinguishing \"no matcher matched\" from a legitimate\n// resolve() return value of `undefined`/`null` (matchers can throw\n// their own errors, e.g. the ambiguous-direction case, but none\n// currently return a nullish PlainDate — this sentinel just makes the\n// \"no match\" case unambiguous regardless).\nconst NO_MATCH = Symbol('temporal-fmt: parseRelative no match');\n\n// DEFAULT_LOCALE is imported for the option's default-value documentation\n// above (no locale → English). The symbol itself isn't read at runtime\n// here, but the import keeps the dependency edge explicit so future\n// changes to the default-locale constant propagate here too.\nvoid DEFAULT_LOCALE;","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// central config stuff. per-call options is the convention we use\n// everywhere else in this lib (formatDistance's cutoffs did it this way\n// first — deliberately NOT a global). so this module just gives callers\n// a typed config object they can build once and pass around, defaults\n// match whatever the per-call defaults already were.\n//\n// no global mutable state, on purpose. don't want a setConfig() anywhere —\n// createConfig() just hands back a frozen object and that's it.\n\nimport { DEFAULT_LOCALE } from './tokens.js';\nimport type { NumberingSystemOption } from './numbering.js';\n\nexport interface TemporalFmtConfig {\n // BCP-47 tag, defaults to 'en-US'\n locale: string;\n // 'gregory', 'hebrew', whatever — leave undefined and it'll just use\n // whatever the locale defaults to\n calendar?: string;\n // IANA id like 'America/New_York', or leave it undefined for system tz\n timezone?: string;\n // defaults to 'latn'. 'auto' is accepted too — resolved per call from\n // the effective locale via Intl (see numbering.ts), so one config can\n // drive different digits per locale instead of pinning a single system\n numberingSystem: NumberingSystemOption;\n // 1 = Monday, 7 = Sunday. default's 1, matches what isoWeek.ts already does\n firstDayOfWeek: 1 | 7;\n // for round()/roundDuration(), defaults to 'nearest'\n roundingMode: 'nearest' | 'floor' | 'ceil' | 'trunc';\n // what to do when a ZonedDateTime construction hits a gap/overlap.\n // defaults to 'compatible' since that's Temporal's own default too\n disambiguation: 'compatible' | 'earlier' | 'later' | 'reject';\n // handles stuff like Feb 30 when building fields. defaults to 'reject',\n // same as what parse() already did before this existed\n overflow: 'constrain' | 'reject';\n // strict by default (false)\n parseLenient: boolean;\n // false by default so zero values just get omitted, not printed\n durationShowZeroValues: boolean;\n}\n\nexport const DEFAULT_CONFIG: Readonly<TemporalFmtConfig> = Object.freeze({\n locale: DEFAULT_LOCALE,\n numberingSystem: 'latn',\n firstDayOfWeek: 1,\n roundingMode: 'nearest',\n disambiguation: 'compatible',\n overflow: 'reject',\n parseLenient: false,\n durationShowZeroValues: false,\n});\n// Frozen: this is exported shared module state, and the module's own\n// header promises \"no global mutable state\" — but DEFAULT_CONFIG was\n// assignable, so one import site writing DEFAULT_CONFIG.locale = 'fr-FR'\n// changed what every subsequent createConfig() in the process returned.\n// Spread ({...DEFAULT_CONFIG}) still makes un-frozen copies wherever\n// defaults feed a merge, so freezing costs nothing.\n\n// merges whatever overrides get passed in on top of the defaults, then\n// freezes it so nobody can mutate it after — Temporal's own options\n// work this way too so figured we'd match that\nexport function createConfig(overrides: Partial<TemporalFmtConfig> = {}): Readonly<TemporalFmtConfig> {\n const merged: TemporalFmtConfig = { ...DEFAULT_CONFIG, ...overrides };\n // sanity checks before we freeze it\n if (typeof merged.locale !== 'string' || merged.locale.length === 0) {\n throw new Error(`temporal-fmt: config.locale must be a non-empty string (got ${String(merged.locale)}).`);\n }\n if (merged.numberingSystem !== undefined && typeof merged.numberingSystem !== 'string') {\n throw new Error(`temporal-fmt: config.numberingSystem must be a string (got ${String(merged.numberingSystem)}).`);\n }\n if (merged.firstDayOfWeek !== 1 && merged.firstDayOfWeek !== 7) {\n throw new Error(`temporal-fmt: config.firstDayOfWeek must be 1 (Monday) or 7 (Sunday) (got ${merged.firstDayOfWeek}).`);\n }\n if (!['nearest', 'floor', 'ceil', 'trunc'].includes(merged.roundingMode)) {\n throw new Error(`temporal-fmt: config.roundingMode \"${merged.roundingMode}\" is not recognized.`);\n }\n if (!['compatible', 'earlier', 'later', 'reject'].includes(merged.disambiguation)) {\n throw new Error(`temporal-fmt: config.disambiguation \"${merged.disambiguation}\" is not recognized.`);\n }\n if (!['constrain', 'reject'].includes(merged.overflow)) {\n throw new Error(`temporal-fmt: config.overflow \"${merged.overflow}\" is not recognized.`);\n }\n return Object.freeze(merged);\n}\n\n// merges a config into per-call options — whatever's already set in\n// per-call wins. format()/parse()/etc use this to fold config in\ninterface ConfigOverrides {\n locale?: string;\n calendar?: string;\n timezone?: string;\n numberingSystem?: string;\n lenient?: boolean;\n}\n\nexport function mergeWithConfig<T extends Record<string, unknown>>(\n config: Readonly<TemporalFmtConfig> | undefined,\n perCall: T,\n): Record<string, unknown> & ConfigOverrides {\n if (!config) return perCall;\n // Returns a fresh object typed by its own actual shape (perCall's\n // fields plus these five, each optionally overridden) instead of\n // asserting the result back into the generic T. A `{ ...perCall } as T\n // & {...}` cast here previously claimed a freshly spread object was\n // still exactly T, which isn't something a spread can guarantee for an\n // arbitrary caller-supplied T — tsc rightly rejected that once this\n // generic got exercised through a real call site. Nothing in this codebase\n // currently calls mergeWithConfig and relies on getting T back rather than this\n // wider shape, so there's no correctness cost to being honest about\n // what's actually returned.\n const extras: ConfigOverrides = {};\n if (perCall.locale === undefined) extras.locale = config.locale;\n if (perCall.calendar === undefined && config.calendar !== undefined) extras.calendar = config.calendar;\n if (perCall.timezone === undefined && config.timezone !== undefined) extras.timezone = config.timezone;\n if (perCall.numberingSystem === undefined) extras.numberingSystem = config.numberingSystem;\n if (perCall.lenient === undefined && config.parseLenient) extras.lenient = true;\n return { ...perCall, ...extras };\n}","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// business calendar stuff — configurable weekends, holiday sets, observed\n// holidays, working hours, half days if you need em. holiday checking\n// itself is handed off to a HolidayCalendar (holidays.ts) so this file\n// can just worry about the weekday-vs-weekend part\n\nimport { add } from './arithmetic.js';\nimport { dayOfWeekFromCivil } from './isoWeek.js';\nimport type { HolidayCalendar } from './holidays.js';\n\nexport interface BusinessCalendarOptions {\n // defaults to [6, 7] (Sat/Sun). ISO weekday numbers, 1-7\n weekend?: number[];\n // pass a holiday calendar if you want holidays factored in too —\n // skip it and you just get weekend logic\n holidays?: HolidayCalendar;\n // hours per weekday, 1=Mon..7=Sun. defaults to 8hrs weekdays, 0 weekend.\n // addBusinessDays() uses this for partial-day math\n workingHours?: Record<number, number>;\n // which weekdays get reduced hours. empty by default\n halfDays?: number[];\n}\n\nexport interface BusinessCalendar {\n weekend: Set<number>;\n holidays?: HolidayCalendar;\n workingHours: Record<number, number>;\n halfDays: Set<number>;\n}\n\nexport function createBusinessCalendar(options: BusinessCalendarOptions = {}): BusinessCalendar {\n const weekend = new Set(options.weekend ?? [6, 7]);\n // gotta copy this before filling in defaults — used to write the missing\n // weekday entries straight into options.workingHours, which mutated\n // the caller's actual object. so someone's { 1: 6 } would silently grow\n // keys 2-7 just from \"creating\" a calendar, and if they reused that\n // object across calendars, the first one's defaults leaked into all of them\n const workingHours: Record<number, number> = { ...(options.workingHours ?? {}) };\n for (let i = 1; i <= 7; i++) {\n if (workingHours[i] === undefined) {\n workingHours[i] = weekend.has(i) ? 0 : 8;\n }\n }\n return {\n weekend,\n holidays: options.holidays,\n workingHours,\n halfDays: new Set(options.halfDays ?? []),\n };\n}\n\nexport function isBusinessDay(cal: BusinessCalendar, value: unknown): boolean {\n const v = value as { dayOfWeek?: number; year?: number; month?: number; day?: number };\n // add() over in arithmetic.ts doesn't touch dayOfWeek — it just hands back\n // whatever dayOfWeek the input had, stale or not. so recompute it from\n // year/month/day whenever we've got those, don't trust the cached value\n let dow = v.dayOfWeek;\n if (typeof v.year === 'number' && typeof v.month === 'number' && typeof v.day === 'number') {\n // dayOfWeekFromCivil: O(1) proleptic-Gregorian weekday. The old\n // Date.UTC remapping of years 0-99 to 1900-1999 made a genuine\n // Sunday PlainDate('0050-01-02') count as a business day here —\n // and this recomputation OVERWRITES the value's own correct\n // dayOfWeek, so real Temporal input was affected too.\n dow = dayOfWeekFromCivil(v.year, v.month, v.day);\n }\n if (typeof dow !== 'number') {\n throw new Error('temporal-fmt: isBusinessDay() needs a value with dayOfWeek (or year/month/day to compute it).');\n }\n if (cal.weekend.has(dow)) return false;\n if (cal.holidays && cal.holidays.isHoliday(value)) return false;\n return true;\n}\n\nexport function nextBusinessDay(cal: BusinessCalendar, value: unknown): unknown {\n let candidate = add(value, 1, 'days');\n // keep going till we hit a business day. capped at 14 just to be safe —\n // a week is really the natural bound even with weekend + holidays combined\n for (let i = 0; i < 14; i++) {\n if (isBusinessDay(cal, candidate)) return candidate;\n candidate = add(candidate, 1, 'days');\n }\n throw new Error('temporal-fmt: nextBusinessDay() gave up after 14 days — likely a misconfigured calendar (e.g. all days are weekends or holidays).');\n}\n\nexport function previousBusinessDay(cal: BusinessCalendar, value: unknown): unknown {\n let candidate = add(value, -1, 'days');\n for (let i = 0; i < 14; i++) {\n if (isBusinessDay(cal, candidate)) return candidate;\n candidate = add(candidate, -1, 'days');\n }\n throw new Error('temporal-fmt: previousBusinessDay() gave up after 14 days — likely a misconfigured calendar.');\n}\n\nconst MAX_BUSINESS_DAY_TRAVERSAL = 100_000;\n\nfunction assertBusinessDayCount(days: number): void {\n if (!Number.isSafeInteger(days)) {\n throw new RangeError(\n `temporal-fmt: business-day count must be a finite safe integer (got ${days}).`,\n );\n }\n}\n\nfunction compareDateFields(a: unknown, b: unknown): number {\n const av = a as { year: number; month: number; day: number };\n const bv = b as { year: number; month: number; day: number };\n const ay = av.year * 10000 + av.month * 100 + av.day;\n const by = bv.year * 10000 + bv.month * 100 + bv.day;\n return ay - by;\n}\n\nexport function addBusinessDays(cal: BusinessCalendar, value: unknown, days: number): unknown {\n assertBusinessDayCount(days);\n if (days === 0) return value;\n const sign = days > 0 ? 1 : -1;\n const absDays = Math.abs(days);\n if (absDays > MAX_BUSINESS_DAY_TRAVERSAL) {\n throw new RangeError(\n `temporal-fmt: addBusinessDays() exceeded the ${MAX_BUSINESS_DAY_TRAVERSAL}-day limit.`,\n );\n }\n let candidate = value;\n for (let i = 0; i < absDays; i++) {\n candidate = sign > 0 ? nextBusinessDay(cal, candidate) : previousBusinessDay(cal, candidate);\n }\n return candidate;\n}\n\nexport function subtractBusinessDays(cal: BusinessCalendar, value: unknown, days: number): unknown {\n assertBusinessDayCount(days);\n return addBusinessDays(cal, value, -days);\n}\n\nexport function differenceInBusinessDays(cal: BusinessCalendar, a: unknown, b: unknown): number {\n const rawDirection = compareDateFields(b, a);\n if (rawDirection === 0) return 0;\n\n const direction = rawDirection > 0 ? 1 : -1;\n let candidate = a;\n let count = 0;\n let traversedDays = 0;\n\n while (compareDateFields(candidate, b) !== 0) {\n candidate = add(candidate, direction, 'days');\n traversedDays++;\n if (traversedDays > MAX_BUSINESS_DAY_TRAVERSAL) {\n throw new RangeError(\n `temporal-fmt: differenceInBusinessDays() exceeded the ${MAX_BUSINESS_DAY_TRAVERSAL}-day traversal limit.`,\n );\n }\n if (isBusinessDay(cal, candidate)) count += direction;\n }\n\n return count;\n}\n","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// holiday framework. core just gives you the abstraction — actual\n// country-specific holiday lists live outside this package, could be\n// their own ecosystem packages built on top. a holiday calendar is\n// basically a date -> boolean function (\"is this a holiday\") plus some\n// iteration helpers (nextHoliday, previousHoliday, holidaysBetween)\n\nimport { add } from './arithmetic.js';\nimport { compare } from './comparison.js';\n\nexport interface HolidayCalendar {\n isHoliday(value: unknown): boolean;\n // everything in [start, end], inclusive on both ends\n holidaysBetween(start: unknown, end: unknown): unknown[];\n}\n\nexport interface HolidaySpec {\n // for fixed-date holidays, like Jan 1 for New Year's\n month?: number;\n day?: number;\n // for the floating ones — give it a year, get back { month, day } for\n // that year. this is how you'd do \"last Monday of May\" type rules\n compute?: (year: number) => { month: number; day: number };\n // just a name, mostly for debugging\n name?: string;\n}\n\n// cap on how many years holidaysBetween() will walk through. it's a\n// year-by-year loop with no bounds checking on the inputs, so someone\n// passing year 1 to year 300000 would've made it iterate (and cache!)\n// every single year in between. either an accident or someone being\n// hostile, either way that used to just hang the process. 5000 matches\n// the same walk-cap businessCalendar.ts and recurrence.ts already use\nconst MAX_HOLIDAY_YEAR_RANGE = 5_000;\n\nexport function createHolidayCalendar(specs: HolidaySpec[]): HolidayCalendar {\n // computes a year's holiday list lazily, then caches it\n const cache = new Map<number, Array<{ month: number; day: number; name?: string }>>();\n // The per-instance cache never evicted: isHoliday/nextHoliday/\n // previousHoliday over N distinct years grew N entries forever (a\n // calendar asked for many years — hostile or just long-lived — held\n // every year's list in memory permanently). FIFO-evict past the cap,\n // same convention as the library's other bounded caches. Rebuilding\n // an evicted year is O(specs), which is the same cost the first\n // computation already paid.\n const MAX_CACHE_YEARS = 1000;\n function forYear(year: number) {\n let list = cache.get(year);\n if (list) return list;\n if (cache.size >= MAX_CACHE_YEARS) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined) cache.delete(oldest);\n }\n list = specs.map((s) => {\n let md: { month: number; day: number };\n if (s.compute) {\n md = s.compute(year);\n } else {\n md = { month: s.month!, day: s.day! };\n }\n return { ...md, name: s.name };\n });\n cache.set(year, list);\n return list;\n }\n return {\n isHoliday(value: unknown) {\n const v = value as { year?: number; month?: number; day?: number };\n if (typeof v.year !== 'number' || typeof v.month !== 'number' || typeof v.day !== 'number') {\n throw new Error('temporal-fmt: isHoliday() needs a value with year/month/day.');\n }\n const list = forYear(v.year);\n return list.some((h) => h.month === v.month && h.day === v.day);\n },\n holidaysBetween(start: unknown, end: unknown) {\n const sv = start as { year: number; month: number; day: number };\n const ev = end as { year: number; month: number; day: number };\n if (typeof sv?.year !== 'number' || typeof ev?.year !== 'number') {\n throw new Error('temporal-fmt: holidaysBetween() needs start/end values with year/month/day.');\n }\n if (ev.year - sv.year > MAX_HOLIDAY_YEAR_RANGE) {\n throw new RangeError(\n `temporal-fmt: holidaysBetween() year range (${sv.year}–${ev.year}) exceeds the ` +\n `${MAX_HOLIDAY_YEAR_RANGE}-year limit. Split the query into smaller ranges.`\n );\n }\n const result: unknown[] = [];\n for (let y = sv.year; y <= ev.year; y++) {\n const list = forYear(y);\n for (const h of list) {\n const date = { year: y, month: h.month, day: h.day };\n if (compare(date, sv) >= 0 && compare(date, ev) <= 0) {\n result.push({ year: y, month: h.month, day: h.day });\n }\n }\n }\n return result;\n },\n };\n}\n\n// finds the next holiday strictly after `value`. gives up and returns\n// undefined if nothing shows up within 5 years — sanity cap so this\n// can't loop forever on an empty calendar\nexport function nextHoliday(cal: HolidayCalendar, value: unknown): unknown | undefined {\n let candidate = add(value, 1, 'days');\n for (let i = 0; i < 365 * 5; i++) {\n if (cal.isHoliday(candidate)) return candidate;\n candidate = add(candidate, 1, 'days');\n }\n return undefined;\n}\n\nexport function previousHoliday(cal: HolidayCalendar, value: unknown): unknown | undefined {\n let candidate = add(value, -1, 'days');\n for (let i = 0; i < 365 * 5; i++) {\n if (cal.isHoliday(candidate)) return candidate;\n candidate = add(candidate, -1, 'days');\n }\n return undefined;\n}\n\n// holidaysBetween already exists as a method on HolidayCalendar (above),\n// this is just a standalone version so you don't have to type cal.holidaysBetween\nexport function holidaysBetween(cal: HolidayCalendar, start: unknown, end: unknown): unknown[] {\n return cal.holidaysBetween(start, end);\n}\n","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Extensibility. Controlled extensibility via\n// createFormatter({ tokens: ... }) rather than uncontrolled global\n// mutation. Custom tokens are passed at formatter-creation time;\n// built-in behavior stays deterministic regardless of what's registered.\n//\n// The existing registerLocaleVocab() is a global-registration escape\n// hatch for the locale-vocabulary case; createFormatter is the\n// per-formatter alternative for custom tokens.\n\nimport { type FormattedPart, type CompiledFormat } from './format.js';\nimport { TOKENS, type TemporalLike, type FormatOptions, DEFAULT_LOCALE } from './tokens.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\nimport { UnknownTokenError } from './errors.js';\n\nexport type TokenHandler = (t: TemporalLike, locale: string) => string;\nexport type TokenField = keyof TemporalLike;\n\nexport interface CustomToken {\n name: string;\n handler: TokenHandler;\n field: TokenField;\n}\n\nexport interface FormatterOptions {\n // Custom tokens to add (or override). Built-in tokens with the same\n // name are replaced by the custom one.\n tokens?: CustomToken[];\n // Default locale for this formatter. Callers can still override per-call.\n defaultLocale?: string;\n}\n\nexport interface Formatter {\n format(temporal: TemporalLike, formatStr: string, options?: FormatOptions): string;\n formatToParts(temporal: TemporalLike, formatStr: string, options?: FormatOptions): FormattedPart[];\n compileFormat(formatStr: string): CompiledFormat;\n}\n\nexport function createFormatter(options: FormatterOptions = {}): Formatter {\n // Build a merged token table: built-ins plus overrides.\n const mergedTokens: Array<[string, TokenHandler, TokenField]> = [...TOKENS];\n const customTokenNames = new Set<string>();\n for (const custom of options.tokens ?? []) {\n customTokenNames.add(custom.name);\n }\n // Replace existing tokens with the same name; append new ones.\n for (const custom of options.tokens ?? []) {\n const existingIdx = mergedTokens.findIndex(([name]) => name === custom.name);\n if (existingIdx >= 0) {\n mergedTokens[existingIdx] = [custom.name, custom.handler, custom.field];\n } else {\n mergedTokens.push([custom.name, custom.handler, custom.field]);\n }\n }\n // Sort longest-first for the greedy tokenizer.\n mergedTokens.sort((a, b) => b[0].length - a[0].length);\n const handlerByToken = new Map(mergedTokens.map(([name, handler, field]) => [name, { handler, field }]));\n const sortedTokenStrings = mergedTokens.map(([name]) => name);\n\n function customTokenize(formatStr: string) {\n const pieces: Array<{ kind: 'token' | 'literal'; value: string }> = [];\n let i = 0;\n while (i < formatStr.length) {\n const ch = formatStr[i];\n if (ch === \"'\") {\n // Quoted literal handling — same as tokenize.ts.\n if (formatStr[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\n }\n let j = i + 1;\n let literal = '';\n let closed = false;\n while (j < formatStr.length) {\n if (formatStr[j] === \"'\") {\n if (formatStr[j + 1] === \"'\") {\n literal += \"'\";\n j += 2;\n continue;\n }\n closed = true;\n j += 1;\n break;\n }\n literal += formatStr[j]!;\n j += 1;\n }\n if (!closed) throw new Error(`temporal-fmt: unterminated quote in format string \"${formatStr}\"`);\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n const match = sortedTokenStrings.find((tok) => formatStr.startsWith(tok, i));\n if (match) {\n // Overlong-run guard, same rule as tokenize.ts: a greedy match of N\n // chars followed by one more of the same letter (\"MMMMM\", \"ddddd\")\n // is not a valid token of any width — emitting it as \"token +\n // literal\" would silently splice an unrelated field onto this one,\n // exactly the misreading the main tokenizer rejects. Same\n // UnknownTokenError shape tokenize.ts throws.\n const runChar = match[match.length - 1];\n if (formatStr[i + match.length] === runChar) {\n let end = i + match.length;\n while (formatStr[end] === runChar) end += 1;\n throw new UnknownTokenError({\n token: formatStr.slice(i, end),\n format: formatStr,\n message:\n `temporal-fmt: \"${formatStr.slice(i, end)}\" in format string \"${formatStr}\" isn't a recognized token — ` +\n `did you mean \"${match}\"?`,\n });\n }\n pieces.push({ kind: 'token', value: match });\n i += match.length;\n continue;\n }\n appendLiteral(pieces, ch);\n i += 1;\n }\n return pieces;\n }\n\n function appendLiteral(pieces: Array<{ kind: 'token' | 'literal'; value: string }>, value: string): void {\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += value;\n } else {\n pieces.push({ kind: 'literal', value });\n }\n }\n\n const defaultLocale = options.defaultLocale ?? DEFAULT_LOCALE;\n\n return {\n format(temporal: TemporalLike, formatStr: string, opts: FormatOptions = {}) {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(`temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters (got ${formatStr.length}).`);\n }\n const locale = opts.locale ?? defaultLocale;\n const pieces = customTokenize(formatStr);\n let result = '';\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n result += piece.value;\n continue;\n }\n const handler = handlerByToken.get(piece.value);\n /* c8 ignore start @preserve -- unreachable: customTokenize only ever produces a\n `kind: 'token'` piece via sortedTokenStrings.find(...), and\n handlerByToken is built from that same mergedTokens array, so\n every token piece is guaranteed a handler entry. Guards against a\n future customTokenize change that decouples the two lookups. */\n if (!handler) throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n /* c8 ignore stop @preserve */\n if (temporal[handler.field] === undefined) {\n throw new Error(\n `temporal-fmt: token \"${piece.value}\" requires \"${String(handler.field)}\", which this Temporal object doesn't have.`\n );\n }\n result += handler.handler(temporal, locale);\n }\n return result;\n },\n formatToParts(temporal: TemporalLike, formatStr: string, opts: FormatOptions = {}) {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(`temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters (got ${formatStr.length}).`);\n }\n const locale = opts.locale ?? defaultLocale;\n const pieces = customTokenize(formatStr);\n const out: FormattedPart[] = [];\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n const last = out[out.length - 1];\n /* c8 ignore start @preserve -- unreachable: customTokenize's own\n appendLiteral() already merges adjacent literal chars/quoted\n spans into a single piece before this loop ever sees them, so\n two literal pieces are never adjacent here. Kept as a guard\n against a future customTokenize change that stops merging. */\n if (last && last.type === 'literal') last.value += piece.value;\n /* c8 ignore stop @preserve */\n else out.push({ type: 'literal', value: piece.value });\n continue;\n }\n const handler = handlerByToken.get(piece.value);\n /* c8 ignore start @preserve -- unreachable: customTokenize only emits\n kind:'token' pieces found in sortedTokenStrings, the same array\n handlerByToken is built from, so every token piece is guaranteed\n a handler entry. Guards against future decoupling of the two. */\n if (!handler) throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n /* c8 ignore stop @preserve */\n if (temporal[handler.field] === undefined) {\n throw new Error(`temporal-fmt: token \"${piece.value}\" requires \"${String(handler.field)}\".`);\n }\n out.push({ type: 'token', value: handler.handler(temporal, locale), token: piece.value });\n }\n return out;\n },\n compileFormat(formatStr: string): CompiledFormat {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(`temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters (got ${formatStr.length}).`);\n }\n const pieces = customTokenize(formatStr);\n return {\n formatStr,\n pieces: pieces.map((p) => p as { kind: 'token' | 'literal'; value: string }),\n format(temporal: TemporalLike, opts: FormatOptions = {}) {\n const locale = opts.locale ?? defaultLocale;\n let result = '';\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n result += piece.value;\n continue;\n }\n const handler = handlerByToken.get(piece.value);\n /* c8 ignore start @preserve -- unreachable, see the same guard's comment\n above in the un-compiled format(). */\n if (!handler) throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n /* c8 ignore stop @preserve */\n if (temporal[handler.field] === undefined) {\n throw new Error(`temporal-fmt: token \"${piece.value}\" requires \"${String(handler.field)}\".`);\n }\n result += handler.handler(temporal, locale);\n }\n return result;\n },\n formatToParts(temporal: TemporalLike, opts: FormatOptions = {}) {\n const locale = opts.locale ?? defaultLocale;\n const out: FormattedPart[] = [];\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n const last = out[out.length - 1];\n /* c8 ignore start @preserve -- unreachable, see the same guard's\n comment above in the un-compiled formatToParts. */\n if (last && last.type === 'literal') last.value += piece.value;\n /* c8 ignore stop @preserve */\n else out.push({ type: 'literal', value: piece.value });\n continue;\n }\n const handler = handlerByToken.get(piece.value);\n /* c8 ignore start @preserve -- unreachable, see the same guard's\n comment above in the un-compiled formatToParts. */\n if (!handler) throw new Error(`temporal-fmt: unknown token \"${piece.value}\"`);\n /* c8 ignore stop @preserve */\n if (temporal[handler.field] === undefined) {\n throw new Error(`temporal-fmt: token \"${piece.value}\" requires \"${String(handler.field)}\".`);\n }\n out.push({ type: 'token', value: handler.handler(temporal, locale), token: piece.value });\n }\n return out;\n },\n };\n },\n };\n}\n\n","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// IDE tooling data exports. Provides structured data editor plugins can\n// consume for: token autocomplete, hover docs, inline diagnostics,\n// quick fixes, format preview, token conversion hints from\n// Day.js/date-fns, documentation links.\n//\n// This is the data layer only — an actual VS Code extension is out of\n// scope for this package. A separate package can build the extension\n// on top of these exports.\n\nimport { TOKEN_METADATA, ALL_TOKEN_NAMES } from './tokenMetadata.js';\nimport { analyzeFormat, listTokens } from './analyze.js';\nimport { format as builtinFormat } from './format.js';\nimport { getTemporal } from './temporalProvider.js';\n\nexport interface TokenAutocompleteEntry {\n label: string;\n detail: string;\n documentation: string;\n // Sort group — same-family tokens sort together in the autocomplete list.\n family: string;\n}\n\n// Token family grouping for autocomplete organization: year, month,\n// day, etc.\nfunction tokenFamily(name: string): string {\n if (/^y+$/.test(name)) return 'Year';\n if (/^[ML]+$/.test(name)) return 'Month';\n if (/^[decD]+$/.test(name)) return 'Day';\n if (/^[Ec]+$/.test(name)) return 'Weekday';\n if (/^[Qq]+$/.test(name)) return 'Quarter';\n if (/^[Gg]+$/.test(name)) return 'Era';\n if (/^[Hh]+$/.test(name)) return 'Hour';\n if (/^m+$/.test(name)) return 'Minute';\n if (/^s+$/.test(name)) return 'Second';\n if (/^S+$/.test(name)) return 'Fractional Second';\n if (name === 'a') return 'Day Period';\n // z/zzz/zzzz are all zone tokens — only exact 'zzz' used to be\n // special-cased, leaving 'z' and 'zzzz' filed under 'Other'.\n if (name === 'z' || name === 'zzz' || name === 'zzzz') return 'Time Zone';\n if (/^[Xx]+$/.test(name)) return 'UTC Offset';\n if (name === 'do') return 'Ordinal Day';\n // Unreachable with the current token set: every name in ALL_TOKEN_NAMES\n // (the only input — see getAutocompleteData) matches a family above, so\n // the fall-through below only exists as the catch-all for tokens added\n // in the future. The first ignored line is the ww/RRRR if, whose V8\n // fall-through block remaps onto it; the second is the return itself;\n // the third is the function's implicit end-of-body statement.\n /* c8 ignore next 3 @preserve */\n if (name === 'ww' || name === 'RRRR') return 'ISO Week';\n return 'Other';\n}\n\nexport function getAutocompleteData(): TokenAutocompleteEntry[] {\n return ALL_TOKEN_NAMES.map((name) => {\n const meta = TOKEN_METADATA[name]!;\n return {\n label: name,\n detail: meta.meaning,\n documentation: [\n meta.meaning,\n ``,\n `Format-capable: ${meta.formatCapable}`,\n `Parse-capable: ${meta.parseCapable}`,\n `Locale-sensitive: ${meta.localeSensitive}`,\n `Calendar-sensitive: ${meta.calendarSensitive}`,\n `Timezone-sensitive: ${meta.timezoneSensitive}`,\n `Round-trip safe: ${meta.roundTripSafe}`,\n `Supported types: ${meta.supportedTypes.join(', ')}`,\n ].join('\\n'),\n family: tokenFamily(name),\n };\n });\n}\n\nexport interface TokenHoverDoc {\n signature: string;\n summary: string;\n details: string;\n examples?: string[];\n}\n\nexport function getHoverDocs(): Record<string, TokenHoverDoc> {\n const result: Record<string, TokenHoverDoc> = {};\n for (const name of ALL_TOKEN_NAMES) {\n const meta = TOKEN_METADATA[name]!;\n result[name] = {\n signature: name,\n summary: meta.meaning,\n details: [\n // every entry in TOKEN_METADATA currently has formatCapable:\n // true (verified: 51/51). The 'no' branch reflects real,\n // intended behavior for a future format-incapable token —\n // there's no such token today, so this isn't reachable data,\n // not dead logic. Every other field on this line has real\n // true/false variance across the token table and is exercised\n // by this same loop running over ALL_TOKEN_NAMES.\n /* c8 ignore next */\n `Format-capable: ${meta.formatCapable ? 'yes' : 'no'}`,\n `Parse-capable: ${meta.parseCapable ? 'yes' : 'no'}`,\n `Locale-sensitive: ${meta.localeSensitive ? 'yes' : 'no'}`,\n `Calendar-sensitive: ${meta.calendarSensitive ? 'yes' : 'no'}`,\n `Timezone-sensitive: ${meta.timezoneSensitive ? 'yes' : 'no'}`,\n `Round-trip safe: ${meta.roundTripSafe ? 'yes' : 'no'}`,\n `Supported types: ${meta.supportedTypes.join(', ')}`,\n ].join('\\n'),\n };\n }\n return result;\n}\n\n// Inline diagnostic data for a format string. Returns a list of issues\n// (warnings + errors) with position + message + suggested fix where\n// available. Mirrors analyzeFormat's warnings but adds the position\n// info an editor needs to draw squigglies.\nexport interface InlineDiagnostic {\n startColumn: number;\n endColumn: number;\n severity: 'error' | 'warning' | 'info';\n message: string;\n code: string;\n // Suggested replacement (for quick-fix). Empty when no quick fix exists.\n suggestion?: string;\n}\n\nexport function getInlineDiagnostics(formatStr: string): InlineDiagnostic[] {\n const analysis = analyzeFormat(formatStr);\n const diagnostics: InlineDiagnostic[] = [];\n for (const warning of analysis.warnings) {\n // Find the token that triggered the warning. analyzeFormat doesn't\n // currently surface which token caused which warning — we'd need\n // to extend it to track per-warning source positions. For now,\n // surface as a whole-string diagnostic.\n let message = warning.message;\n let suggestion: string | undefined;\n if (warning.code === 'TWELVE_HOUR_WITHOUT_A') {\n suggestion = 'Add an \"a\" token (e.g. \"h:mm a\") or use \"H:mm\" for 24-hour.';\n } else if (warning.code === 'MIXED_12_AND_24_HOUR') {\n suggestion = 'Pick one form: \"HH:mm\" for 24-hour or \"h:mm a\" for 12-hour.';\n } else if (warning.code === 'AMBIGUOUS_NUMERIC_RUN') {\n suggestion = 'Add a separator or use padded forms (e.g. \"MM\" instead of \"M\").';\n } else if (warning.code === 'FORMAT_ONLY_TOKEN') {\n suggestion = 'Use a parse-capable variant (e.g. \"d\" instead of \"do\").';\n }\n diagnostics.push({\n startColumn: 0,\n endColumn: formatStr.length,\n severity: 'warning',\n message,\n code: warning.code,\n suggestion,\n });\n }\n return diagnostics;\n}\n\n// Day.js / date-fns token conversion hints. Used by the IDE to suggest\n// the temporal-fmt equivalent when a user types a Day.js or date-fns\n// token. Pulls the translation tables from the codemod if available;\n// falls back to inline tables otherwise.\nexport interface TokenConversionHint {\n from: string;\n // null means \"real token in the source library, no temporal-fmt\n // equivalent\" — the codemod throws on these rather than treating\n // them as unrecognized text (see codemod.ts).\n to: string | null;\n notes?: string;\n}\n\n// Day.js → temporal-fmt mappings. Day.js uses Moment-style tokens:\n// `D`/`DD` are day-of-*month* here (unlike date-fns below, where the\n// same letters mean day-of-year). Assumes the AdvancedFormat plugin\n// for `Do`/`Q`/`k`/`kk`/`X`/`x` — see codemod.ts's doc comment for why.\nexport const DAYJS_TO_TEMPORAL_FMT: TokenConversionHint[] = [\n { from: 'YYYY', to: 'yyyy' },\n { from: 'YY', to: 'yy' },\n { from: 'MMMM', to: 'MMMM' },\n { from: 'MMM', to: 'MMM' },\n { from: 'MM', to: 'MM' },\n { from: 'M', to: 'M' },\n { from: 'DD', to: 'dd' },\n { from: 'D', to: 'd' },\n { from: 'Do', to: null, notes: 'Ordinal day (AdvancedFormat) — use temporal-fmt\\'s own \"do\" token instead.' },\n { from: 'dddd', to: 'EEEE' },\n { from: 'ddd', to: 'EEE' },\n { from: 'dd', to: null, notes: 'Min-name weekday (e.g. \"Tu\") — temporal-fmt has no equivalent width.' },\n { from: 'd', to: null, notes: 'Numeric weekday (0-6) — no temporal-fmt equivalent; not the same as \"d\" here, which is day-of-month.' },\n { from: 'HH', to: 'HH' },\n { from: 'H', to: 'H' },\n { from: 'hh', to: 'hh' },\n { from: 'h', to: 'h' },\n { from: 'kk', to: null, notes: 'Hour 1-24 (AdvancedFormat) — no temporal-fmt equivalent.' },\n { from: 'k', to: null, notes: 'Hour 1-24 (AdvancedFormat) — no temporal-fmt equivalent.' },\n { from: 'mm', to: 'mm' },\n { from: 'm', to: 'm' },\n { from: 'ss', to: 'ss' },\n { from: 's', to: 's' },\n // Fractional seconds: Day.js S/SS/SSS are 1/2/3-digit milliseconds,\n // the same widths temporal-fmt's own S/SS/SSS use. These used to be\n // missing from the table entirely, so \"S\"/\"SS\" silently translated\n // to quoted LITERAL text (translateDayjs('S') → \"'S'\") instead of\n // a token.\n { from: 'SSS', to: 'SSS' },\n { from: 'SS', to: 'SS' },\n { from: 'S', to: 'S' },\n { from: 'A', to: 'a', notes: 'Uppercase AM/PM in Day.js — temporal-fmt is always lowercase.' },\n { from: 'a', to: 'a' },\n { from: 'ZZ', to: 'XX', notes: 'Numeric UTC offset, no colon.' },\n { from: 'Z', to: 'XXX', notes: 'Numeric UTC offset with colon.' },\n { from: 'X', to: null, notes: 'Unix timestamp (seconds) — use fromUnixSeconds() instead.' },\n { from: 'x', to: null, notes: 'Unix timestamp (ms) — use fromUnixMilliseconds() instead.' },\n { from: 'Qo', to: null, notes: 'Ordinal quarter (AdvancedFormat) — no temporal-fmt equivalent.' },\n { from: 'Q', to: 'Q' },\n { from: 'Mo', to: null, notes: 'Ordinal month (AdvancedFormat) — no temporal-fmt equivalent.' },\n // Day.js w/ww are LOCALE-aware weeks (default en locale: week starts\n // Sunday, week 1 contains Jan 1) — not the ISO weeks temporal-fmt's\n // ww computes. Mapping silently would print different week numbers\n // than the source library for the same date (e.g. 2016-01-01: Day.js\n // \"1\" vs temporal-fmt \"53\"), so refuse with a note instead.\n { from: 'ww', to: null, notes: 'Locale-aware week of year — temporal-fmt\\'s \"ww\" is a strict ISO week number and disagrees with Day.js\\'s locale week for the same date. Compute locale weeks separately if needed.' },\n { from: 'wo', to: null, notes: 'Ordinal locale week (AdvancedFormat) — no temporal-fmt equivalent.' },\n { from: 'w', to: null, notes: 'Unpadded locale week of year — see the \"ww\" note; temporal-fmt has only ISO weeks.' },\n { from: 'gg', to: null, notes: 'Two-digit locale week-numbering year — no temporal-fmt equivalent (RRRR is 4-digit ISO).' },\n { from: 'gggg', to: 'RRRR', notes: 'Week-numbering year — mapped, but Day.js\\'s is locale-week-based while RRRR is strict ISO; values can differ at year boundaries.' },\n { from: 'L', to: null, notes: 'Localized date format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LL', to: null, notes: 'Localized date format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LLL', to: null, notes: 'Localized date format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LLLL', to: null, notes: 'Localized date format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LT', to: null, notes: 'Localized time format (AdvancedFormat) — write the format string out explicitly.' },\n { from: 'LTS', to: null, notes: 'Localized time format (AdvancedFormat) — write the format string out explicitly.' },\n];\n\n// date-fns → temporal-fmt mappings. date-fns already uses Unicode/LDML\n// -style tokens close to temporal-fmt's own vocabulary — most strings\n// pass through unchanged. The catch: `D`/`DD` here mean day-of-*year*\n// (same as temporal-fmt's `D`/`DD`), not day-of-month like Day.js's\n// `D`/`DD` above — don't reuse the Day.js table for this, they collide.\nexport const DATE_FNS_TO_TEMPORAL_FMT: TokenConversionHint[] = [\n { from: 'yyyy', to: 'yyyy' },\n { from: 'yy', to: 'yy' },\n // temporal-fmt HAS an unpadded-year token (\"y\", same as date-fns);\n // this used to map to null and throw even though the token passes\n // straight through.\n { from: 'y', to: 'y', notes: 'Unpadded calendar year, opt-in via useAdditionalWeekYearTokens — temporal-fmt has the same \"y\" token.' },\n { from: 'MMMM', to: 'MMMM' },\n { from: 'MMM', to: 'MMM' },\n { from: 'MM', to: 'MM' },\n { from: 'M', to: 'M' },\n { from: 'LLLL', to: 'LLLL' },\n { from: 'LLL', to: 'LLL' },\n { from: 'dd', to: 'dd' },\n { from: 'd', to: 'd' },\n { from: 'do', to: 'do' },\n { from: 'DDD', to: 'DDD' },\n { from: 'DD', to: 'DD' },\n { from: 'D', to: 'D', notes: 'Day-of-year, opt-in via useAdditionalDayOfYearTokens — matches temporal-fmt\\'s own \"D\" already.' },\n { from: 'EEEE', to: 'EEEE' },\n { from: 'EEE', to: 'EEE' },\n { from: 'eeee', to: null, notes: 'Locale-aware numeric weekday — no temporal-fmt equivalent.' },\n { from: 'cccc', to: 'cccc' },\n { from: 'ccc', to: 'ccc' },\n { from: 'HH', to: 'HH' },\n { from: 'H', to: 'H' },\n { from: 'hh', to: 'hh' },\n { from: 'h', to: 'h' },\n { from: 'mm', to: 'mm' },\n { from: 'm', to: 'm' },\n { from: 'ss', to: 'ss' },\n { from: 's', to: 's' },\n // Fractional seconds, same widths as temporal-fmt's own tokens —\n // used to be missing, silently literalizing \"S\"/\"SS\".\n { from: 'SSS', to: 'SSS' },\n { from: 'SS', to: 'SS' },\n { from: 'S', to: 'S' },\n { from: 'a', to: 'a' },\n { from: 'aaa', to: 'a' },\n { from: 'XXX', to: 'XXX' },\n { from: 'XX', to: 'XX' },\n { from: 'X', to: 'X', notes: 'Opt-in via useAdditionalDayOfYearTokens-adjacent rules in date-fns v3+; matches temporal-fmt\\'s own \"X\" already.' },\n { from: 'xxx', to: 'xxx' },\n { from: 'xx', to: 'xx' },\n { from: 'x', to: 'x' },\n { from: 'zzzz', to: 'zzzz' },\n { from: 'zzz', to: 'zzz' },\n { from: 'z', to: 'z' },\n { from: 'QQQ', to: 'QQQ' },\n { from: 'Q', to: 'Q' },\n { from: 'QQQQ', to: null, notes: 'Long quarter name — temporal-fmt has Q (numeric) and QQQ (\"Q1\"-style) only.' },\n { from: 'Qo', to: null, notes: 'Ordinal quarter — no temporal-fmt equivalent.' },\n { from: 'GGGG', to: 'GGGG' },\n { from: 'GGG', to: null, notes: 'Abbreviated era — temporal-fmt only has \"G\" (short) and \"GGGG\" (long).' },\n { from: 'GG', to: null, notes: 'Abbreviated era — temporal-fmt only has \"G\" (short) and \"GGGG\" (long).' },\n { from: 'G', to: 'G' },\n // date-fns w/ww are LOCAL week rules (en-US: week starts Sunday, week\n // 1 contains Jan 1) — temporal-fmt's ww is strict ISO. Silently\n // mapping prints different numbers than the source library (2016-01-01:\n // date-fns \"01\" vs temporal-fmt \"53\"), so refuse with a note.\n { from: 'ww', to: null, notes: 'Local week of year — temporal-fmt\\'s \"ww\" is a strict ISO week number and disagrees with date-fns\\'s locale week for the same date. Compute locale weeks separately if needed.' },\n { from: 'w', to: null, notes: 'Unpadded local week number — temporal-fmt\\'s \"ww\" is ISO-week and always 2-digit.' },\n { from: 'RRRR', to: 'RRRR' },\n { from: 'R', to: null, notes: 'Unpadded ISO week-numbering year — temporal-fmt\\'s \"RRRR\" is always 4-digit.' },\n { from: 'Y', to: null, notes: 'Week-numbering year (locale week rules), opt-in — no temporal-fmt equivalent; \"RRRR\" is ISO week-numbering, a different rule set.' },\n { from: 'PPPP', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'PPP', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'PP', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'P', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'pppp', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'ppp', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'pp', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n { from: 'p', to: null, notes: 'Localized composite format — write the format string out explicitly.' },\n];\n\n// Format preview — for a given format string and a sample Temporal\n// value, returns the formatted string. Editor plugins use this for\n// live preview as the user types.\nexport function previewFormat(formatStr: string, sample?: unknown): string {\n // Use a fixed sample date if none provided — 2026-08-04T15:45:30,\n // built as a REAL Temporal.PlainDateTime. Picked because it exercises\n // every common token: weekday is Tuesday, month name has 5 chars, day\n // is single-digit, hour is 12-hour-style, minute/second both pad.\n // (A plain field bag used to be passed instead, which can't render\n // locale-aware tokens at all — previewFormat('MMMM d') threw \"needs a\n // value that implements toLocaleString\".)\n let value = sample;\n if (value === undefined) {\n const temporal = getTemporal();\n value = temporal.PlainDateTime.from({\n year: 2026, month: 8, day: 4, hour: 15, minute: 45, second: 30, millisecond: 123,\n });\n }\n return builtinFormat(value as Parameters<typeof builtinFormat>[0], formatStr, { locale: 'en-US' });\n}\n\n// Documentation links. Docs used to live under docs/ as one file per\n// token family; they're now consolidated into the root README's \"Token\n// reference\" section, which has no per-token anchors — so this points\n// at the section instead of a token-specific fragment.\nexport function getDocUrl(tokenName: string): string {\n void tokenName;\n return 'README.md#token-reference';\n}\n\n// Re-exports for callers that want everything IDE-related from one module.\nexport { listTokens, TOKEN_METADATA, ALL_TOKEN_NAMES };","/*\n * Copyright 2026 DirazCoder\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// translates Day.js / date-fns format strings — this is what backs the\n// CLI's `translate` subcommand. the mapping tables were already sitting\n// in ideData.ts (built for the IDE tooling), so this just builds the\n// actual string translator on top instead of pulling in anything else.\n//\n// heads up: this only handles format *strings* (\"YYYY-MM-DD\" -> \"yyyy-MM-dd\"),\n// not an actual AST codemod that goes and rewrites call sites in your code.\n// that's a bigger separate thing — check temporal-fmt-codemod if that's\n// what you actually need\n\nimport { DAYJS_TO_TEMPORAL_FMT, DATE_FNS_TO_TEMPORAL_FMT, type TokenConversionHint } from './ideData.js';\n\ninterface SourcePiece {\n kind: 'token' | 'literal';\n value: string;\n}\n\n// Day.js and date-fns escape literal text with square brackets — [MM]\n// stays as literal \"MM\" — not single quotes like temporal-fmt does.\n// splitting on brackets first keeps the token scan below from accidentally\n// matching stuff inside an escaped span\nfunction splitOnBrackets(source: string): SourcePiece[] {\n const pieces: SourcePiece[] = [];\n let i = 0;\n while (i < source.length) {\n if (source[i] === '[') {\n const end = source.indexOf(']', i + 1);\n if (end === -1) {\n pieces.push({ kind: 'token', value: source.slice(i) });\n break;\n }\n pieces.push({ kind: 'literal', value: source.slice(i + 1, end) });\n i = end + 1;\n } else {\n let j = i;\n while (j < source.length && source[j] !== '[') j += 1;\n pieces.push({ kind: 'token', value: source.slice(i, j) });\n i = j;\n }\n }\n return pieces;\n}\n\n// splits a non-bracketed span into runs, matching greedy-longest against\n// the known token table — basically the same idea as tokenize.ts, just\n// scanning the SOURCE library's tokens here instead of temporal-fmt's own\nfunction splitIntoRuns(span: string, sortedFrom: string[]): SourcePiece[] {\n const pieces: SourcePiece[] = [];\n let i = 0;\n while (i < span.length) {\n const match = sortedFrom.find((tok) => span.startsWith(tok, i));\n if (match) {\n pieces.push({ kind: 'token', value: match });\n i += match.length;\n continue;\n }\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += span[i];\n } else {\n pieces.push({ kind: 'literal', value: span[i] });\n }\n i += 1;\n }\n return pieces;\n}\n\nfunction translate(source: string, table: TokenConversionHint[], sourceLibLabel: string): string {\n const byFrom = new Map(table.map((hint) => [hint.from, hint.to]));\n const sortedFrom = [...byFrom.keys()].sort((a, b) => b.length - a.length);\n\n const bracketPieces = splitOnBrackets(source);\n let out = '';\n for (const piece of bracketPieces) {\n if (piece.kind === 'literal') {\n // re-escape for temporal-fmt's quote syntax — any literal quote\n // char inside the escaped bit needs doubling up\n out += `'${piece.value.replace(/'/g, \"''\")}'`;\n continue;\n }\n for (const run of splitIntoRuns(piece.value, sortedFrom)) {\n if (run.kind === 'token') {\n const mapped = byFrom.get(run.value);\n if (mapped === undefined || mapped === null) {\n throw new Error(\n `temporal-fmt: \"${run.value}\" has no ${sourceLibLabel} -> temporal-fmt mapping ` +\n `(in format string \"${source}\"). Write the equivalent temporal-fmt token in by hand, ` +\n `or wrap it in brackets if it was meant as literal text.`\n );\n }\n out += mapped;\n } else if (/[a-zA-Z]/.test(run.value)) {\n // can't just let unrecognized letters through as-is — temporal-fmt\n // would read them as its own tokens by accident. gotta quote the run\n out += `'${run.value.replace(/'/g, \"''\")}'`;\n } else {\n out += run.value;\n }\n }\n }\n return out;\n}\n\n/**\n * Translates a Day.js format string to the equivalent temporal-fmt\n * token string.\n *\n * ```js\n * translateDayjsFormatString('YYYY-MM-DD HH:mm:ss'); // \"yyyy-MM-dd HH:mm:ss\"\n * translateDayjsFormatString('[Q]Q YYYY'); // \"'Q'Q yyyy\" (bracketed text stays literal)\n * ```\n *\n * Throws if the format string uses a Day.js token with no temporal-fmt\n * equivalent (`Do`, `Mo`, `Qo`, `k`, `kk`, `X`, `x`, the localized\n * `L`-family tokens) — these need to be rewritten by hand, since\n * there's no single temporal-fmt token that means the same thing.\n *\n * Note: `Do`/`Mo`/`Qo`/`k`/`kk`/`X`/`x` only have meaning in Day.js\n * once the `AdvancedFormat` (and, for `X`/`x`, base) plugins are\n * loaded — without them Day.js silently glues the parts together or\n * passes the letters through unrendered instead of erroring. This\n * function assumes the plugin is loaded, since that's the common case\n * for anyone who put these tokens in a format string on purpose.\n */\nexport function translateDayjsFormatString(formatStr: string): string {\n return translate(formatStr, DAYJS_TO_TEMPORAL_FMT, 'Day.js');\n}\n\n/**\n * Translates a date-fns format string to the equivalent temporal-fmt\n * token string. date-fns already uses Unicode-style tokens close to\n * temporal-fmt's own, so most strings pass through with only a case\n * change on the weekday tokens; the notable divergences are date-fns's\n * `D`/`DD` (day-of-year, matches temporal-fmt already) versus its `d`/\n * `dd` (day-of-month, also matches already) and the locale-dependent\n * `P`/`p` composite tokens, which have no single temporal-fmt token\n * and throw.\n */\nexport function translateDateFnsFormatString(formatStr: string): string {\n return translate(formatStr, DATE_FNS_TO_TEMPORAL_FMT, 'date-fns');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,SAAS,WAAW,OAAgB,OAA8B;AAChE,MAAI,UAAU,QAAQ,OAAO,UAAU,UAAU;AAC/C,UAAM,IAAI;AAAA,MACR,6DAA6D,KAAK,MAAM,OAAO,KAAK,CAAC;AAAA,IACvF;AAAA,EACF;AACA,QAAM,MAAM;AAGZ,QAAM,UAAU,OAAO,IAAI,SAAS;AACpC,QAAM,WAAW,OAAO,IAAI,UAAU;AACtC,QAAM,SAAS,OAAO,IAAI,QAAQ;AAClC,MAAI,YAAY,YAAY,aAAa,QAAQ;AAC/C,UAAM,IAAI;AAAA,MACR,sCAAsC,KAAK;AAAA,IAE7C;AAAA,EACF;AAUA,MAAI,SAAS;AACX,UAAM,IAAI,IAAI;AACd,UAAM,IAAI,IAAI;AACd,UAAM,IAAI,IAAI;AACd,QAAI,CAAC,OAAO,SAAS,CAAC,KAAK,CAAC,OAAO,UAAU,CAAC,KAAK,IA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