temporal-fmt 0.9.1 → 0.9.3
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.
- package/README.md +166 -1
- package/dist/chunk-2JHEV7ZF.js +7 -0
- package/dist/chunk-2JHEV7ZF.js.map +1 -0
- package/dist/chunk-4JDAJSEM.js +35 -0
- package/dist/chunk-4JDAJSEM.js.map +1 -0
- package/dist/chunk-4XRE37WT.js +2 -0
- package/dist/chunk-4XRE37WT.js.map +1 -0
- package/dist/{chunk-H52AMABK.js → chunk-5U5WJ465.js} +6 -6
- package/dist/chunk-5U5WJ465.js.map +1 -0
- package/dist/chunk-GMGZZG6I.js +2 -0
- package/dist/chunk-GMGZZG6I.js.map +1 -0
- package/dist/{chunk-M5WL5VGW.js → chunk-NPKJ7QFK.js} +2 -2
- package/dist/chunk-R4YEFOVE.js +2 -0
- package/dist/chunk-R4YEFOVE.js.map +1 -0
- package/dist/{chunk-DXLBLPLQ.js → chunk-SSPABEUR.js} +2 -2
- package/dist/chunk-UJR6DHXY.js +2 -0
- package/dist/chunk-UJR6DHXY.js.map +1 -0
- package/dist/{chunk-6UNSCZPL.js → chunk-XH46JNPK.js} +2 -2
- package/dist/chunk-XH46JNPK.js.map +1 -0
- package/dist/chunk-ZGMTY52O.js +2 -0
- package/dist/chunk-ZGMTY52O.js.map +1 -0
- package/dist/duration.cjs +4 -10
- package/dist/duration.cjs.map +1 -1
- package/dist/duration.js +1 -1
- package/dist/format.cjs +6 -6
- package/dist/format.cjs.map +1 -1
- package/dist/format.js +1 -1
- package/dist/formatDuration.d.cts +6 -0
- package/dist/formatDuration.d.ts +6 -0
- package/dist/index.cjs +37 -43
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +15 -15
- package/dist/index.js.map +1 -1
- package/dist/interval.cjs +6 -6
- package/dist/interval.cjs.map +1 -1
- package/dist/interval.js +1 -1
- package/dist/localeRegistry.cjs +4 -4
- package/dist/localeRegistry.cjs.map +1 -1
- package/dist/localeRegistry.js +1 -1
- package/dist/localeVocab.d.cts +3 -0
- package/dist/localeVocab.d.ts +3 -0
- package/dist/parse.cjs +9 -9
- package/dist/parse.cjs.map +1 -1
- package/dist/parse.js +1 -1
- package/dist/parsePattern.d.cts +1 -0
- package/dist/parsePattern.d.ts +1 -0
- package/dist/pattern.d.cts +2 -0
- package/dist/pattern.d.ts +2 -0
- package/dist/recurrence.cjs +4 -4
- package/dist/recurrence.cjs.map +1 -1
- package/dist/recurrence.js +1 -1
- package/dist/relativeTime.cjs +24 -1
- package/dist/relativeTime.cjs.map +1 -1
- package/dist/relativeTime.js +1 -1
- package/dist/rounding.d.cts +1 -0
- package/dist/rounding.d.ts +1 -0
- package/dist/serialization.d.cts +1 -1
- package/dist/serialization.d.ts +1 -1
- package/dist/typeGuards.d.cts +9 -9
- package/dist/typeGuards.d.ts +9 -9
- package/package.json +1 -1
- package/dist/chunk-6JAWE65A.js +0 -2
- package/dist/chunk-6JAWE65A.js.map +0 -1
- package/dist/chunk-6UNSCZPL.js.map +0 -1
- package/dist/chunk-CUTVOO4Y.js +0 -35
- package/dist/chunk-CUTVOO4Y.js.map +0 -1
- package/dist/chunk-H52AMABK.js.map +0 -1
- package/dist/chunk-ILXRFTAE.js +0 -13
- package/dist/chunk-ILXRFTAE.js.map +0 -1
- package/dist/chunk-LYWOLBMV.js +0 -2
- package/dist/chunk-LYWOLBMV.js.map +0 -1
- package/dist/chunk-QASXSTBN.js +0 -2
- package/dist/chunk-QASXSTBN.js.map +0 -1
- package/dist/chunk-YAVXHM4W.js +0 -2
- package/dist/chunk-YAVXHM4W.js.map +0 -1
- package/dist/chunk-ZYVMZRMR.js +0 -2
- package/dist/chunk-ZYVMZRMR.js.map +0 -1
- /package/dist/{chunk-M5WL5VGW.js.map → chunk-NPKJ7QFK.js.map} +0 -0
- /package/dist/{chunk-DXLBLPLQ.js.map → chunk-SSPABEUR.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/pattern.ts","../src/parsePattern.ts","../src/parse.ts"],"sourcesContent":["import { getLocaleVocab } from './localeVocab.js';\nimport { UnknownTokenError } from './errors.js';\nimport { getTemporal } from './temporalProvider.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction alternation(values: string[], caseInsensitive = false): string {\n const escaped = values.map(escapeRegExp);\n if (!caseInsensitive) return `(?:${escaped.join('|')})`;\n // JS regex has no per-group inline case-insensitive flag, and this\n // fragment gets embedded in one larger pattern built with a single flag\n // set — so case-folding here means listing both cases explicitly rather\n // than relying on a flag.\n return `(?:${escaped.map(foldCase).join('|')})`;\n}\n\n// Expands \"PM\" into a character-class-per-letter pattern matching any\n// casing of it (\"[Pp][Mm]\"), so \"pm\", \"Pm\", \"PM\" all match the same\n// alternative. Only used for the day-period token (see the 'a' case\n// below) — not applied to month/weekday names, where case-folding across\n// scripts is a different and riskier problem this doesn't need to solve.\nfunction foldCase(value: string): string {\n return value.replace(/[a-zA-Z]/g, (ch) => `[${ch.toLowerCase()}${ch.toUpperCase()}]`);\n}\n\n// Every real IANA zone id is letters/digits/'_'/'+'/'-' segments joined by\n// '/' (e.g. \"America/Argentina/Buenos_Aires\", \"Etc/GMT+12\"); UTC and\n// fixed-offset strings are the only other shapes zzz accepts. Matching that\n// *shape* here — instead of alternating all ~400 zone names inline — keeps\n// the compiled regex small regardless of how many zzz tokens appear in a\n// format string. The captured text still gets checked against the real\n// zone set in isValidTimeZone() after the overall pattern matches, so this\n// is strictly a matching-cost change, not a validation-strictness change:\n// a bogus zone id fails \"no valid pattern matches\" exactly like it did when\n// the zone list was inlined (see isValidTimeZone's caller in parse.ts).\nconst TIME_ZONE_SHAPE = '(?:UTC|[+-]\\\\d{2}:\\\\d{2}(?::\\\\d{2}(?:\\\\.\\\\d{1,9})?)?|[A-Za-z_]+(?:[+-]\\\\d{1,2})?(?:\\\\/[A-Za-z0-9_+-]+)*)';\n\n// Per-variant regex shapes for the six offset tokens. Each matches the\n// shape its own format counterpart produces, so a round-trip\n// format->parse succeeds for any input the library itself emitted.\n//\n// Kept loose (no hour/minute range bounds inline) on purpose, mirroring\n// how TIME_ZONE_SHAPE is loose: a permissive shape here lets parse()\n// surface a descriptive out-of-range error post-match (see\n// parseOffsetString in parse.ts) instead of the generic \"no valid pattern\n// matches\" the regex throws when the shape itself fails. \"+99:99\" should\n// tell the user it's out of range, not look like the input never matched\n// the format at all.\n//\n// X / x accept an optional minutes group so whole-hour offsets can be\n// written short (\"+05\") while non-whole-hour offsets still parse\n// (\"+0530\"). The optional group is greedy, so for input \"+0530\" the\n// engine prefers the 4-digit match; only falls back to 2-digit when\n// there's nothing else to consume — same longer-first preference the\n// unpadded numeric tokens use elsewhere in this file (see the comment on\n// NUMERIC_FRAGMENTS).\nconst OFFSET_SHAPES: Record<string, string> = {\n X: '(?:Z|[+-]\\\\d{2}(?:\\\\d{2})?)',\n XX: '(?:Z|[+-]\\\\d{4})',\n XXX: '(?:Z|[+-]\\\\d{2}:\\\\d{2})',\n x: '[+-]\\\\d{2}(?:\\\\d{2})?',\n xx: '[+-]\\\\d{4}',\n xxx: '[+-]\\\\d{2}:\\\\d{2}',\n};\n\nfunction getTimeZoneFragment(): string {\n return TIME_ZONE_SHAPE;\n}\n\nlet validZoneSet: Set<string> | undefined;\n\n// Real zone ids plus the couple of aliases zzz has always accepted even\n// though Intl.supportedValuesOf('timeZone') doesn't list them (UTC isn't\n// itself an IANA zone name, it's the identity offset).\nfunction getValidZoneSet(): Set<string> {\n if (!validZoneSet) {\n validZoneSet = new Set(Intl.supportedValuesOf('timeZone'));\n validZoneSet.add('UTC');\n }\n return validZoneSet;\n}\n\nconst FIXED_OFFSET_RE = /^[+-]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?$/;\n\n// Called post-match on whatever the bounded TIME_ZONE_SHAPE captured, since\n// that shape is deliberately looser than \"a real zone id\" (it has to be, to\n// stay a fixed-size regex fragment — see the comment above). A fixed offset\n// is valid by construction; anything else has to be a real IANA name.\n//\n// Intl.supportedValuesOf('timeZone') is checked first as a fast path — it's\n// a plain Set lookup and covers the overwhelming majority of real input.\n// But it lists only canonical zone ids, not every IANA link/alias name:\n// \"Asia/Kolkata\" is a legitimate, commonly-used alias for \"Asia/Calcutta\"\n// that Temporal.ZonedDateTime.from() itself resolves correctly, yet some\n// ICU builds' supportedValuesOf() omits it. Rejecting it here — even\n// though the exact same string would construct a real ZonedDateTime one\n// call later — was a real bug: parse() refused input its own downstream\n// construction step would have accepted. Anything Intl doesn't recognize\n// gets a second check against Temporal itself before being refused.\nexport function isValidTimeZone(raw: string): boolean {\n if (FIXED_OFFSET_RE.test(raw) || getValidZoneSet().has(raw)) return true;\n try {\n getTemporal().ZonedDateTime.from({\n year: 2026, month: 1, day: 1, hour: 0, minute: 0, second: 0,\n timeZone: raw,\n });\n return true;\n } catch {\n return false;\n }\n}\n\n// mirrors the ranges pad() in tokens.ts actually produces — keep in sync\n// if those ever change\n//\n// Unpadded alternatives (M, H, h, m, s) list the longer branch first\n// (e.g. '1[0-2]|[1-9]', not '[1-9]|1[0-2]'). This matters only when two\n// unpadded tokens are glued with no separator: with short-first ordering,\n// a regex engine takes the first successful overall match, and won't\n// backtrack into a token's second alternative unless its first choice\n// makes the *rest* of the pattern fail outright. If the short reading also\n// happens to leave a valid match for the next token, the engine stops\n// there — silently, deterministically, and with no relation to which\n// reading a human intended. E.g. \"Md\" against \"121\": short-first order\n// resolves it as month=1/day=21 (M grabs '1', d gets '21', which is a\n// valid day) instead of month=12/day=1. Longer-first ordering fixes this\n// by making the greedy match try to consume as many digits as possible\n// before ever handing digits to the next token, which is the reading\n// that matches how format() itself produces glued output in the first\n// place (format() always emits the token's natural width, so decoding\n// should prefer the same). Found via the token×token combinatorial glue\n// matrix in combinatorial.test.js — see that file for the full case list.\nconst NUMERIC_FRAGMENTS: Record<string, string> = {\n yy: '\\\\d{2}',\n MM: '(?:0[1-9]|1[0-2])',\n M: '(?:1[0-2]|[1-9])',\n dd: '(?:0[1-9]|[12]\\\\d|3[01])',\n d: '(?:[12]\\\\d|3[01]|[1-9])',\n HH: '(?:[01]\\\\d|2[0-3])',\n H: '(?:1\\\\d|2[0-3]|[0-9])',\n hh: '(?:0[1-9]|1[0-2])',\n h: '(?:1[0-2]|[1-9])',\n mm: '(?:[0-5]\\\\d)',\n m: '(?:[1-5]\\\\d|[0-9])',\n ss: '(?:[0-5]\\\\d)',\n s: '(?:[1-5]\\\\d|[0-9])',\n SSSSSSSSS: '\\\\d{9}',\n SSSSSSSS: '\\\\d{8}',\n SSSSSSS: '\\\\d{7}',\n SSSSSS: '\\\\d{6}',\n SSSSS: '\\\\d{5}',\n SSSS: '\\\\d{4}',\n SSS: '\\\\d{3}',\n SS: '\\\\d{2}',\n S: '\\\\d',\n // Q is always a single digit 1-4 (no padding variant, so no width ambiguity\n // with adjacent digit tokens the way M/d/H/m/s have).\n Q: '[1-4]',\n};\n\n// QQQ matches its own formatted output: the literal \"Q\" prefix plus a single\n// digit 1-4. Kept as a static fragment rather than routed through vocab,\n// since the \"Q\" prefix is part of the token's own contract, not locale-vocab\n// data that could ever differ.\nconst QQQ_FRAGMENT = 'Q[1-4]';\n\n// Format-only tokens — they have no parse counterpart. The tokenizer still\n// recognizes them (so format() can use them), but parse()'s regex builder\n// rejects them with a clear error rather than silently dropping the token\n// or falling through to the generic \"unknown token\" message.\n// Exported so analyze.ts can include them in the public analyzer surface.\nexport const FORMAT_ONLY_TOKENS = new Set(['do', 'ww', 'RRRR', 'D', 'DD', 'DDD', 'LLLL', 'LLL', 'cccc', 'ccc', 'GGGG', 'G', 'zzzz', 'z']);\n\n// pad()'s year formatter (tokens.ts) never truncates: it preserves the sign\n// for BCE years and doesn't cap width past 9999, so a formatted \"yyyy\" can\n// be longer than 4 digits or start with '-'. YYYY_EXTENDED accepts that;\n// YYYY_EXACT is the plain 4-unsigned-digit case. Which one a given \"yyyy\"\n// occurrence gets depends on what follows it — see buildCapturingPattern in\n// parsePattern.ts. Two separate fragments instead of one `-?\\d{4,}` because\n// an open-ended-width year directly followed by another digit token (e.g.\n// \"yyyyMM\") lets the year's own greediness silently eat digits meant for\n// the next token — same class of bug as UNPADDED_NUMERIC_TOKENS below, but\n// unbounded-width, so it can't reuse enumerateValidSplits' fixed-range\n// splitting. Restricting to exactly 4 digits whenever something could\n// follow closes that off entirely, at the cost of \"yyyyMM\" not being able\n// to represent a 5-digit year — an already-rare case doubly rare in\n// combination with a glued adjacent token.\nconst YYYY_EXACT = '-?\\\\d{4}';\nconst YYYY_EXTENDED = '-?\\\\d{4,}';\n\n// \"y\" is yyyy's unpadded sibling: any width, 1 digit up through Temporal's\n// max supported year (275760), with the same optional leading \"-\" for\n// years before ISO year 0. Unlike yyyy, there's no bounded fallback to\n// reach for when something digit-consuming follows — yyyy can fall back\n// to an exact 4 digits because it's always exactly 4 digits in that case,\n// but \"y\" being unpadded is the entire point of the token, so there's no\n// narrower shape that still means the same thing. buildCapturingPattern\n// (parsePattern.ts) refuses to build a pattern where \"y\" is immediately\n// followed by another digit-consuming element, rather than trying to\n// bound this fragment the way YYYY_EXACT does.\nconst Y_FRAGMENT = '-?\\\\d+';\n\n// True for any token whose matched text can start with a digit — i.e.\n// every token here except the locale-named ones (MMMM/MMM/EEEE/EEE/a) and\n// zzz (which can start with a digit only via a fixed offset like \"+09:00\",\n// already handled by requiring a leading sign there). Used to decide\n// whether a \"yyyy\" immediately before this token needs the exact-4-digit\n// fragment instead of the open-ended one.\n// Exported for parsePattern.ts's ReDoS guard: a token whose regex\n// fragment can begin with a bare digit (see the guard comments there).\nexport const DIGIT_LEADING_TOKENS = new Set([\n 'yyyy', 'yy', 'y', 'MM', 'M', 'dd', 'd', 'HH', 'H', 'hh', 'h', 'mm', 'm', 'ss', 's',\n 'SSSSSSSSS', 'SSSSSSSS', 'SSSSSSS', 'SSSSSS', 'SSSSS', 'SSSS', 'SSS', 'SS', 'S',\n]);\n\n// Tokens whose regex fragment has no upper bound on width — nothing\n// caps how many digits they might consume. yyyy's YYYY_EXTENDED form is\n// also unbounded, but it's only ever selected when the *next* piece\n// already isn't digit-consuming (see tokenFragment below), so by\n// construction it never reaches a position where the ambiguity guard in\n// parsePattern.ts would need to weigh in. \"y\" has no such self-limiting\n// selection rule — it's unbounded unconditionally — so it needs an\n// explicit guard there instead of a bit-cost estimate: there's no\n// meaningful number of \"width choices\" to assign to \"any number of\n// digits,\" so parsePattern.ts refuses outright rather than pretending a\n// finite ambiguity score covers it.\nexport const UNBOUNDED_WIDTH_TOKENS = new Set(['y']);\n\nexport function tokenFragment(token: string, locale: string, nextToken?: string): string {\n if (token === 'yyyy') {\n return nextToken !== undefined && DIGIT_LEADING_TOKENS.has(nextToken) ? YYYY_EXACT : YYYY_EXTENDED;\n }\n if (token === 'y') {\n return Y_FRAGMENT;\n }\n\n const numeric = NUMERIC_FRAGMENTS[token];\n if (numeric) {\n return numeric;\n }\n\n if (token === 'QQQ') {\n return QQQ_FRAGMENT;\n }\n\n if (FORMAT_ONLY_TOKENS.has(token)) {\n throw new UnknownTokenError({\n token,\n message:\n `temporal-fmt: token \"${token}\" is format-only — it can't be parsed back into a value. ` +\n `Use a different token in the parse format string (e.g. \"d\" for \"do\", \"MM\" for \"ww\").`,\n });\n }\n\n const vocab = getLocaleVocab(locale);\n switch (token) {\n case 'MMMM': return alternation(vocab.monthLong);\n case 'MMM': return alternation(vocab.monthShort);\n case 'EEEE': return alternation(vocab.weekdayLong);\n case 'EEE': return alternation(vocab.weekdayShort);\n // Case-insensitive on purpose: \"pm\"/\"Pm\"/\"PM\" all mean the same thing,\n // and unlike the Md-glue ambiguity elsewhere in this file, there's no\n // second valid reading to guess wrong — so rejecting on case buys no\n // correctness, only friction against real-world data (mixed-case CSV\n // exports, lowercase log timestamps).\n case 'a': return alternation(vocab.dayPeriod, true);\n case 'zzz': return getTimeZoneFragment();\n case 'X': case 'XX': case 'XXX':\n case 'x': case 'xx': case 'xxx':\n return OFFSET_SHAPES[token]!;\n /* c8 ignore start @preserve -- defensive guard, not reachable through\n the public API. tokenFragment's only caller (buildCapturingPattern\n in parsePattern.ts) always passes piece.value straight from\n tokenize.ts, which only ever emits strings from tokens.ts's TOKENS\n table. Every token in that table is handled above: the numeric\n ones via NUMERIC_FRAGMENTS, QQQ via QQQ_FRAGMENT, the format-only\n ones via the FORMAT_ONLY_TOKENS check earlier in this function, and\n everything else via one of the switch cases. There's no token\n string that can reach this default without either tokens.ts\n registering something new or tokenize.ts being bypassed, neither of\n which happens on the parse() path. */\n default:\n throw new UnknownTokenError({ token, message: `temporal-fmt: unknown token \"${token}\"` });\n /* c8 ignore stop @preserve */\n }\n}\n\n// Tokens whose fragment is variable-width (1-2 digits, no leading zero).\n// Two or more of these glued with no literal separator between them can\n// have more than one digit-split that's independently valid against every\n// fragment in the run — see the big comment on NUMERIC_FRAGMENTS above.\n// Reordering alternation branches picks a winner for *some* of these\n// cases, but can't make both directions of a pair (e.g. \"Md\" and \"dM\")\n// agree, because the ambiguity is in the input string itself, not in how\n// any one fragment is written. exported so parsePattern.ts can find runs\n// of these that need split-counting at match time instead of a single\n// fixed regex.\nexport const UNPADDED_NUMERIC_TOKENS = new Set(['M', 'd', 'H', 'h', 'm', 's']);\n\n// Every accept width for a given unpadded numeric token, as plain min/max\n// value + digit-length pairs — used to enumerate candidate splits of a\n// digit run at match time. Mirrors NUMERIC_FRAGMENTS's semantics exactly\n// (same accepted values), just as data instead of regex source, since\n// enumerating splits against a compiled regex per-candidate would be\n// slower and harder to reason about than checking numeric ranges directly.\nexport const UNPADDED_NUMERIC_RANGES: Record<string, Array<{ digits: 1 | 2; min: number; max: number }>> = {\n M: [{ digits: 1, min: 1, max: 9 }, { digits: 2, min: 10, max: 12 }],\n d: [{ digits: 1, min: 1, max: 9 }, { digits: 2, min: 10, max: 31 }],\n H: [{ digits: 1, min: 0, max: 9 }, { digits: 2, min: 10, max: 23 }],\n h: [{ digits: 1, min: 1, max: 9 }, { digits: 2, min: 10, max: 12 }],\n m: [{ digits: 1, min: 0, max: 9 }, { digits: 2, min: 10, max: 59 }],\n s: [{ digits: 1, min: 0, max: 9 }, { digits: 2, min: 10, max: 59 }],\n};\n\n/**\n * Given the literal digit string a run of N adjacent unpadded-numeric\n * tokens matched as a whole (e.g. \"112\" for a 2-token run), enumerates\n * every way to split it into N pieces (one per token, each piece 1-2\n * digits per that token's own width rule) and returns every split where\n * every piece is independently valid for its token. Length 0 means the\n * run's regex match shouldn't have been possible in the first place\n * (shouldn't happen — the caller only invokes this after the whole\n * pattern already matched, meaning at least one split exists: the one the\n * regex actually took). Length 1 means the reading is unambiguous.\n * Length 2+ means true ambiguity — the caller should throw rather than\n * pick one.\n *\n * Recursive over token count rather than hardcoded to 2, so a 3+ token\n * unseparated run (e.g. \"Hms\") is covered by the same logic without a\n * special case — those are rarer in practice but not impossible, and a\n * partial fix that only covered pairs would leave the identical bug for\n * anyone writing a 3-token glued run.\n */\nexport function enumerateValidSplits(digits: string, tokens: string[]): number[][] {\n const memo = new Map<string, number[][]>();\n\n function solve(tokenIndex: number, offset: number): number[][] {\n const key = `${tokenIndex}:${offset}`;\n const cached = memo.get(key);\n if (cached) {\n return cached;\n }\n\n if (tokenIndex === tokens.length) {\n const result = offset === digits.length ? [[]] : [];\n memo.set(key, result);\n return result;\n }\n\n const token = tokens[tokenIndex];\n const ranges = UNPADDED_NUMERIC_RANGES[token!];\n /* c8 ignore start @preserve -- defensive guard, not reachable through\n the public API. enumerateValidSplits's only caller (parse.ts, both\n call sites) passes run.tokens straight from\n pattern.ambiguousRuns, which parsePattern.ts only ever populates\n with tokens already checked against UNPADDED_NUMERIC_TOKENS — the\n exact same key set as UNPADDED_NUMERIC_RANGES. There's no path\n where a token reaches here without having already passed that\n check. */\n if (!ranges) {\n throw new Error(`temporal-fmt: internal error — \"${token}\" is not an unpadded numeric token`);\n }\n /* c8 ignore stop @preserve */\n\n const results: number[][] = [];\n for (const { digits: width, min, max } of ranges) {\n if (offset + width > digits.length) continue;\n const piece = digits.slice(offset, offset + width);\n if (width === 2 && piece[0] === '0') continue;\n const value = Number(piece);\n if (value < min || value > max) continue;\n\n for (const restSplit of solve(tokenIndex + 1, offset + width)) {\n results.push([value, ...restSplit]);\n if (results.length === 2) break;\n }\n if (results.length === 2) break;\n }\n\n memo.set(key, results);\n return results;\n }\n\n return solve(0, 0);\n}","import type { Piece } from './tokenize.js';\nimport { tokenFragment, UNPADDED_NUMERIC_TOKENS, DIGIT_LEADING_TOKENS, UNBOUNDED_WIDTH_TOKENS } from './pattern.js';\nimport { FormatSyntaxError } from './errors.js';\n\nfunction escapeRegExp(literal: string): string {\n return literal.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\n// Guards against catastrophic-backtracking (ReDoS) patterns.\n//\n// Every confirmed ReDoS in this library shares one shape: two or more\n// variable-width digit-consuming regex fragments placed so the engine\n// can't tell where one ends and the next begins — either glued with no\n// separator (\"MdMdMd…\", \"HmsHms…\") or separated only by a literal that\n// itself starts with a digit (\"M1M1M1…\", \"yyyy1yyyy1…\"). Each fragment\n// then has multiple ways to divide the digit run, and a failing match\n// makes the engine explore every combination — exponential in the number\n// of fragments. Measured against the pre-fix code: \"Md\"×13 (26-char\n// format, 40-char input) ≈ 2.7 s; \"yyyy1\"×8 (48-char format) ≈ 26 s;\n// both grow roughly ×3–14 per additional fragment.\n//\n// Three structural defenses, applied at pattern-build time:\n//\n// 1. A run of 2+ glued unpadded-numeric tokens is emitted as ONE\n// bounded digit group `(?<rN>\\d{R,2R})` instead of R separate\n// variable-width fragments. The per-token split is resolved after\n// the match by enumerateValidSplits() (pattern.ts) — the exact\n// machinery parse() already used to detect ambiguous glued runs —\n// so the documented behavior (unique split resolves; 2+ valid\n// splits throws in strict mode / heuristic-picks in lenient; 0\n// splits is a mismatch) is preserved. A lone `\\d{R,2R}` group\n// backtracks at most R+1 times, which is linear.\n//\n// 2. yyyy uses the exact `-?\\d{4}` fragment not only when the next\n// *token* is digit-leading (existing rule) but also when the next\n// *literal* starts with a digit. An open-ended `-?\\d{4,}` year\n// glued to a digit literal is the cheapest exponential engine\n// there is (unbounded width choices per year), and the exact form\n// matches everything the open-ended form matched in that position\n// except years with 5+ digits glued directly to an unquoted digit\n// literal — a pathological corner deliberately traded away.\n//\n// 3. An ambiguity budget for what's left: every adjacency between a\n// variable-width digit consumer (a lone unpadded token, or a glued\n// run group) and a digit-consuming successor (a digit-leading token\n// or a literal starting with a digit) costs log2 of the consumer's\n// width choices. A pattern whose total exceeds MAX_AMBIGUITY_BITS\n// (12 — a hard ceiling of 4096 backtrack paths) is rejected at\n// build time with a FormatSyntaxError. Realistic format strings\n// score 0–3; the \"M1M1M1…\" attack scores one bit per glued pair.\nconst MAX_AMBIGUITY_BITS = 12;\n\nfunction widthChoicesBits(choices: number): number {\n return Math.ceil(Math.log2(Math.max(choices, 1)));\n}\n\n// Does this piece's regex fragment START by consuming a bare digit?\n// (Tokens whose match can begin with 0-9, and literals whose first\n// character is a digit.) Used to find the boundaries where a preceding\n// variable-width digit consumer could trade digits with a successor.\nfunction isDigitConsumingStart(piece: Piece | undefined): boolean {\n if (piece === undefined) return false;\n if (piece.kind === 'literal') return /^[0-9]/.test(piece.value);\n return DIGIT_LEADING_TOKENS.has(piece.value);\n}\n\nexport interface CapturingPattern {\n regex: RegExp;\n groups: Array<{ name: string; token: string }>; // token pieces, in order\n // Runs of 2+ adjacent unpadded-numeric tokens with no literal separator\n // between them (e.g. \"Md\", \"Hms\"). Each run is captured by ONE regex\n // group named `groupName` spanning the run's whole digit run\n // (R..2·R digits); per-token values come from enumerateValidSplits()\n // at match time. `groupNames` lists the per-token group names — they\n // appear in `groups` for structure/positions but have no counterpart\n // in the regex itself, so consumers must read their values from the\n // split enumeration, not from match.groups.\n ambiguousRuns: Array<{ groupName: string; groupNames: string[]; tokens: string[] }>;\n}\n\n/**\n * Same walk as buildPatternSource() in pattern.ts, but each token piece\n * gets its own named capture group (positionally named so the same token,\n * e.g. \"yyyy\", could in theory appear twice) so a caller can pull the\n * matched substring for each token back out after a successful match.\n */\nexport function buildCapturingPattern(pieces: Piece[], locale: string): CapturingPattern {\n const groups: Array<{ name: string; token: string }> = [];\n const ambiguousRuns: Array<{ groupName: string; groupNames: string[]; tokens: string[] }> = [];\n let source = '';\n let i = 0;\n let ambiguityBits = 0;\n\n // Tracks the current run of adjacent unpadded-numeric token pieces (no\n // literal or non-unpadded token has broken it yet). Names are recorded\n // in declaration order so a run of 2+ can emit one group while its\n // member tokens still get individual entries in `groups`.\n let currentRun: { names: string[]; tokens: string[] } = { names: [], tokens: [] };\n\n const flushRun = (nextPiece: Piece | undefined) => {\n if (currentRun.tokens.length === 1) {\n // A lone unpadded token: emit its normal (two-way) fragment. Two\n // width choices are harmless on their own; if the next element\n // can consume a digit, charge one ambiguity bit for the boundary.\n const name = currentRun.names[0]!;\n const token = currentRun.tokens[0]!;\n source += `(?<${name}>${tokenFragment(token, locale)})`;\n if (isDigitConsumingStart(nextPiece)) ambiguityBits += 1;\n } else if (currentRun.tokens.length >= 2) {\n // Emit the accumulated run as ONE bounded digit group. R unpadded\n // tokens accept between R and 2R digits in total; anything outside\n // that span can't match regardless of how the digits split, so the\n // single group's acceptance region is exactly the union of the old\n // per-token fragments' regions. Backtracking into this group is\n // bounded at R+1 width choices — linear, not exponential.\n const runName = `r${i++}`;\n const tokenCount = currentRun.tokens.length;\n source += `(?<${runName}>\\\\d{${tokenCount},${tokenCount * 2}})`;\n // Note: no `groups` entry for the run group itself — `groups` lists\n // per-token pieces only (its members were already pushed when\n // visited), so consumers like parseToParts see exactly one entry\n // per token, same as before this run-group change. The regex group\n // is reached through ambiguousRuns[].groupName.\n ambiguousRuns.push({\n groupName: runName,\n groupNames: currentRun.names,\n tokens: currentRun.tokens,\n });\n // A run group adjacent to a digit-consuming successor keeps its\n // (R+1) width choices at that boundary — charge the budget.\n if (isDigitConsumingStart(nextPiece)) {\n ambiguityBits += widthChoicesBits(tokenCount + 1);\n }\n }\n currentRun = { names: [], tokens: [] };\n };\n\n for (const [idx, piece] of pieces.entries()) {\n if (piece.kind === 'literal') {\n flushRun(piece);\n source += escapeRegExp(piece.value);\n continue;\n }\n\n if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {\n // Part of a (potential) glued run — defer fragment emission to\n // flushRun so a run of 2+ collapses into one bounded group.\n const name = `g${i++}`;\n groups.push({ name, token: piece.value });\n currentRun.names.push(name);\n currentRun.tokens.push(piece.value);\n continue;\n }\n\n flushRun(piece);\n const name = `g${i++}`;\n groups.push({ name, token: piece.value });\n const nextPiece = pieces[idx + 1];\n const nextToken = nextPiece?.kind === 'token' ? nextPiece.value : undefined;\n\n // \"y\" has no bounded fallback the way yyyy does (see tokenFragment in\n // pattern.ts) — it's unpadded by definition, so there's no narrower\n // fixed-width shape to fall back to. A run of \"any number of digits\"\n // immediately next to another digit consumer has no finite ambiguity\n // score to charge against MAX_AMBIGUITY_BITS below, so this is\n // refused outright at build time instead of estimated.\n if (UNBOUNDED_WIDTH_TOKENS.has(piece.value) && isDigitConsumingStart(nextPiece)) {\n throw new FormatSyntaxError({\n reason:\n `token \"${piece.value}\" has no fixed width — it can't be placed directly next to another ` +\n `digit-reading token or a literal that starts with a digit, since there's no way to tell ` +\n `where \"${piece.value}\" ends and the next field begins. Add a non-digit separator (e.g. \"-\" or \" \") after it.`,\n });\n }\n\n // yyyy picks its fragment based on what follows: the exact 4-digit\n // form whenever a digit-consuming element comes next (digit-leading\n // token — the pre-existing rule — OR a literal starting with a\n // digit, added by the ReDoS fix; see the guard block above). The\n // open-ended form is only safe when nothing digit-consuming can\n // follow it.\n if (piece.value === 'yyyy' && nextToken === undefined && isDigitConsumingStart(nextPiece)) {\n source += `(?<${name}>${tokenFragment(piece.value, locale, 'M')})`;\n } else {\n source += `(?<${name}>${tokenFragment(piece.value, locale, nextToken)})`;\n }\n }\n flushRun(undefined);\n\n if (ambiguityBits > MAX_AMBIGUITY_BITS) {\n throw new FormatSyntaxError({\n reason:\n `format string has too many variable-width numeric tokens glued to digit-consuming neighbors ` +\n `(ambiguity score ${ambiguityBits} > ${MAX_AMBIGUITY_BITS}). ` +\n `This shape makes the regex engine backtrack exponentially on near-miss input. ` +\n `Add a non-digit separator between these tokens (e.g. \"-\" or \" \") or use their padded forms (MM/dd/HH/mm/ss).`,\n });\n }\n\n // 'd' flag enables match.indices.groups — used by parseToParts to\n // report each token's actual position in the input. Without it,\n // computing per-group positions would require a separate walk of the\n // piece list against the input, duplicating logic the regex already\n // has. Backward-compatible: 'd' only adds an `indices` property to\n // the match result, no behavioral change to the match itself.\n return { regex: new RegExp(`^(?:${source})$`, 'ud'), groups, ambiguousRuns };\n}","import { DEFAULT_LOCALE, type FormatOptions } from './tokens.js';\nimport { tokenize } from './tokenize.js';\nimport { buildCapturingPattern, type CapturingPattern } from './parsePattern.js';\nimport { enumerateValidSplits, isValidTimeZone } from './pattern.js';\nimport { getLocaleVocab, canonicalCacheKey, assertValidLocaleTag, subscribeToVocabChanges } from './localeVocab.js';\nimport { getTemporal } from './temporalProvider.js';\nimport { MAX_FORMAT_LENGTH, MAX_INPUT_LENGTH } from './constants.js';\nimport { TemporalFmtError, InvalidTimeZoneError, InvalidOffsetError, FormatSyntaxError, ParseMismatchError, AmbiguousInputError, InvalidDateError, wrapUntypedError } from './errors.js';\nimport { applyParseNumbering, type NumberingParseOptions } from './numbering.js';\n\n// format strings are short hand-written literals reused across many calls —\n// cache the compiled capturing pattern per (formatStr, locale) pair instead\n// of rebuilding it every call.\nconst patternCache = new Map<string, CapturingPattern>();\nconst MAX_CACHE_SIZE = 500;\n\n// A compiled pattern embeds locale-vocabulary alternations (MMMM/MMM/\n// EEEE/EEE/a fragments) at build time. When registerLocaleVocab()\n// swaps a locale's vocabulary, every cached pattern for any locale\n// becomes potentially stale — the cached regex would keep matching the\n// OLD vocabulary while format() renders the new one, breaking the\n// format→parse round-trip for the library's own output. Clear the whole\n// cache on any vocab change: rebuilds are cheap and self-limiting via\n// the cache size cap.\nsubscribeToVocabChanges(() => { patternCache.clear(); });\n\nfunction getPattern(formatStr: string, locale: string): CapturingPattern {\n const key = JSON.stringify([canonicalCacheKey(locale), formatStr]);\n let pattern = patternCache.get(key);\n if (pattern) {\n return pattern;\n }\n if (patternCache.size >= MAX_CACHE_SIZE) {\n const oldestKey = patternCache.keys().next().value;\n if (oldestKey !== undefined) patternCache.delete(oldestKey);\n }\n pattern = buildCapturingPattern(tokenize(formatStr), locale);\n patternCache.set(key, pattern);\n return pattern;\n}\n\n// Requires an explicit `-u-ca-` extension (e.g. 'en-u-ca-hebrew') to apply\n// a non-Gregorian calendar, per parse()'s own docstring. 'gregory' counts\n// as \"no calendar\" so the default locale keeps constructing plain ISO 8601.\n//\n// Used to key off resolvedOptions().calendar instead — a locale's\n// *default* calendar, whether the caller asked for one or not. That broke\n// th-TH silently: its default is 'buddhist', so plain Gregorian-looking\n// digits parsed 543 years off, while format() has no matching calendar\n// step and just prints the object's own ISO fields either way.\nconst calendarCache = new Map<string, string | undefined>();\nconst MAX_CALENDAR_CACHE_SIZE = 500;\n\nfunction resolveCalendar(locale: string): string | undefined {\n // Typed validation first: a genuinely malformed tag (bare private-use\n // singleton, control characters, garbage) surfaces as the library's\n // InvalidLocaleError instead of a raw engine RangeError — same code as\n // before, different (documented, structured) error class.\n assertValidLocaleTag(locale);\n // canonicalCacheKey is memoized (localeVocab.ts), so the common path —\n // repeated parse() calls with the same locale — no longer constructs a\n // fresh Intl.Locale per call just to compute the calendar-cache key.\n const canonicalLocale = canonicalCacheKey(locale);\n if (calendarCache.has(canonicalLocale)) {\n return calendarCache.get(canonicalLocale);\n }\n if (calendarCache.size >= MAX_CALENDAR_CACHE_SIZE) {\n const oldestKey = calendarCache.keys().next().value;\n if (oldestKey !== undefined) calendarCache.delete(oldestKey);\n }\n let calendar: string | undefined;\n const parts = canonicalLocale.split('-');\n const extensionIndex = parts.indexOf('u');\n const calendarKeyIndex = extensionIndex === -1 ? -1 : parts.indexOf('ca', extensionIndex + 1);\n if (calendarKeyIndex !== -1 && calendarKeyIndex + 1 < parts.length) {\n const resolved = new Intl.DateTimeFormat(canonicalLocale).resolvedOptions().calendar;\n calendar = resolved === 'gregory' ? undefined : resolved;\n }\n calendarCache.set(canonicalLocale, calendar);\n return calendar;\n}\n\ninterface Fields {\n year?: number;\n twoDigitYear?: number;\n month?: number;\n day?: number;\n hour?: number;\n hour12?: number;\n dayPeriodRaw?: string;\n isPM?: boolean;\n minute?: number;\n second?: number;\n millisecond?: number;\n microsecond?: number;\n nanosecond?: number;\n timeZoneId?: string;\n // Canonical `+HH:MM` form of any offset token (X/XX/XXX/x/xx/xxx)\n // captured in this pattern. Distinct from timeZoneId because the two\n // can coexist in the same pattern (e.g. \"yyyy-MM-dd HH:mm zzz XXX\") —\n // see the cross-check after construction for how a mismatch between\n // them is resolved.\n offsetString?: string;\n weekdayExpected?: number;\n weekdayRaw?: string;\n quarter?: number;\n}\n\n// Normalizes a captured offset-token string into the canonical `+HH:MM`\n// shape Temporal.ZonedDateTime.from accepts as a `timeZone` value. Throws\n// descriptive errors for out-of-range hours/minutes, since the regex\n// shape (OFFSET_SHAPES in pattern.ts) is deliberately permissive — a\n// post-match range check here gives the user a specific error (\"offset\n// hours 99 out of range, max 14\") instead of \"no valid pattern matches\".\n//\n// Range bounds: -12:00 to +14:00, the standard IANA offset range\n// (Baker/Howland at -12, Kiritimati at +14). +14:01 / -12:01 etc. are\n// rejected explicitly even though the per-piece bounds (hours ≤ 14,\n// minutes ≤ 59) alone wouldn't catch them.\nfunction parseOffsetString(raw: string, token: string): string {\n if (raw === 'Z') {\n /* c8 ignore start @preserve -- unreachable: lowercase tokens' regex\n (OFFSET_SHAPES in pattern.ts) has no \"Z\" alternative at all, so\n raw === 'Z' can only ever be reached when token is one of the\n uppercase variants (X/XX/XXX). A lowercase token can't even\n capture \"Z\" as `raw` in the first place. */\n if (token === 'x' || token === 'xx' || token === 'xxx') {\n throw new Error(\n `temporal-fmt: offset token \"${token}\" doesn't accept \"Z\" — only the uppercase variants (X/XX/XXX) emit \"Z\" for UTC. ` +\n `Use \"+00:00\", \"+0000\", or \"+00\" depending on the variant's width.`\n );\n }\n /* c8 ignore stop @preserve */\n return '+00:00';\n }\n\n const sign = raw[0];\n /* c8 ignore start @preserve -- unreachable: raw is a regex-captured\n group from an offset token, and every OFFSET_SHAPES pattern\n (pattern.ts) is anchored to either \"Z\" or a leading [+-]. raw's\n first character can never be anything else by the time it reaches\n this function. */\n if (sign !== '+' && sign !== '-') {\n throw new Error(`temporal-fmt: offset \"${raw}\" for token \"${token}\" doesn't start with \"+\", \"-\", or \"Z\".`);\n }\n /* c8 ignore stop @preserve */\n const body = raw.slice(1);\n let hoursStr: string;\n let minutesStr: string;\n if (body.length === 2) {\n /* c8 ignore start @preserve -- unreachable: each offset token's own\n regex shape in OFFSET_SHAPES (pattern.ts) already gates which\n body shapes it can capture. Only X and x ever match a 2-digit\n body — XX/xx/XXX/xxx's regexes can't produce one — so this\n mismatch can never actually fire through parse(). */\n // +HH — only X/x emit this shape; XX/xx/XXX/xxx always carry minutes.\n if (token !== 'X' && token !== 'x') {\n throw new Error(\n `temporal-fmt: offset token \"${token}\" can't match \"${raw}\" — it requires minutes, but \"${raw}\" has none.`\n );\n }\n /* c8 ignore stop @preserve */\n hoursStr = body;\n minutesStr = '00';\n } else if (body.length === 4) {\n /* c8 ignore start @preserve -- unreachable, same reason as the\n 2-digit case above: XXX/xxx's regex requires a colon, so it can\n never capture a 4-digit no-colon body in the first place. */\n // +HHMM — X/x (when minutes are non-zero) or XX/xx.\n if (token === 'XXX' || token === 'xxx') {\n throw new Error(\n `temporal-fmt: offset token \"${token}\" can't match \"${raw}\" — it requires a colon between hours and minutes (e.g. \"${sign}${body.slice(0, 2)}:${body.slice(2)}\").`\n );\n }\n /* c8 ignore stop @preserve */\n hoursStr = body.slice(0, 2);\n minutesStr = body.slice(2, 4);\n } else if (body.length === 5 && body[2] === ':') {\n /* c8 ignore start @preserve -- unreachable, same reason again: only\n XXX/xxx's regex can produce a colon-shaped body; X/x/XX/xx never\n capture one. */\n // +HH:MM — XXX/xxx only.\n if (token !== 'XXX' && token !== 'xxx') {\n throw new Error(\n `temporal-fmt: offset token \"${token}\" can't match \"${raw}\" — it doesn't use a colon (use \"${sign}${body.slice(0, 2)}${body.slice(3)}\" instead).`\n );\n }\n /* c8 ignore stop @preserve */\n hoursStr = body.slice(0, 2);\n minutesStr = body.slice(3, 5);\n /* c8 ignore start @preserve -- unreachable: every offset token's\n regex only ever produces a body of length 2, length 4, or length 5\n with a colon at index 2 (see OFFSET_SHAPES in pattern.ts) — no\n shape falls outside those three cases, so this else arm can't be\n taken through parse(). Kept as an exhaustiveness fallback so\n hoursStr/minutesStr are assigned on every path TypeScript can see. */\n } else {\n throw new Error(`temporal-fmt: offset \"${raw}\" doesn't match the shape token \"${token}\" accepts.`);\n }\n /* c8 ignore stop @preserve */\n\n const hours = Number(hoursStr);\n const minutes = Number(minutesStr);\n // Per-piece range checks catch most malformed input.\n if (hours > 14) {\n throw new InvalidOffsetError({\n actual: raw,\n message: `temporal-fmt: offset hours ${hours} in \"${raw}\" out of range (max 14 — Kiritimati, Line Islands is +14:00).`,\n });\n }\n if (minutes > 59) {\n throw new InvalidOffsetError({\n actual: raw,\n message: `temporal-fmt: offset minutes ${minutes} in \"${raw}\" out of range (max 59).`,\n });\n }\n // Boundary: +14:01..+14:59 and -12:01..-12:59 are out of range even\n // though each piece alone is in bounds — the overall offset exceeds\n // the IANA-supported range.\n if (sign === '+' && hours === 14 && minutes !== 0) {\n throw new InvalidOffsetError({\n actual: raw,\n message: `temporal-fmt: offset \"${raw}\" exceeds the maximum supported UTC offset of +14:00.`,\n });\n }\n if (sign === '-' && hours === 12 && minutes !== 0) {\n throw new InvalidOffsetError({\n actual: raw,\n message: `temporal-fmt: offset \"${raw}\" exceeds the maximum supported negative UTC offset of -12:00.`,\n });\n }\n return `${sign}${hoursStr}:${minutesStr}`;\n}\n\nfunction assignField<T>(fields: Fields, key: keyof Fields, value: T): void {\n (fields as Record<string, T | undefined>)[key] = value;\n}\n\nfunction applyGroup(fields: Fields, token: string, raw: string, locale: string, formatStr: string): void {\n const vocab = getLocaleVocab(locale);\n switch (token) {\n case 'yyyy': case 'y':\n assignField(fields, 'year', Number(raw));\n break;\n case 'yy':\n assignField(fields, 'twoDigitYear', Number(raw));\n break;\n case 'MM': case 'M':\n assignField(fields, 'month', Number(raw));\n break;\n case 'MMMM':\n assignField(fields, 'month', vocab.monthLong.indexOf(raw) + 1);\n break;\n case 'MMM':\n assignField(fields, 'month', vocab.monthShort.indexOf(raw) + 1);\n break;\n case 'dd': case 'd':\n assignField(fields, 'day', Number(raw));\n break;\n case 'EEEE':\n assignField(fields, 'weekdayRaw', raw);\n assignField(fields, 'weekdayExpected', vocab.weekdayLong.indexOf(raw) + 1);\n break;\n case 'EEE':\n assignField(fields, 'weekdayRaw', raw);\n assignField(fields, 'weekdayExpected', vocab.weekdayShort.indexOf(raw) + 1);\n break;\n case 'HH': case 'H':\n assignField(fields, 'hour', Number(raw));\n break;\n case 'hh': case 'h':\n assignField(fields, 'hour12', Number(raw));\n break;\n case 'mm': case 'm':\n assignField(fields, 'minute', Number(raw));\n break;\n case 'ss': case 's':\n assignField(fields, 'second', Number(raw));\n break;\n case 'S': case 'SS': case 'SSS': case 'SSSS': case 'SSSSS':\n case 'SSSSSS': case 'SSSSSSS': case 'SSSSSSSS': case 'SSSSSSSSS': {\n // The captured digits are the leading N digits of a nanosecond-of-second\n // value, not the whole thing — \"5\" under SSSSSSSSS means 500000000ns\n // (half a second), not 5ns. Right-padding to 9 digits before splitting\n // is what makes that work; left-padding (or just Number(raw)) would\n // read \"5\" as 5ns instead.\n const nanoOfSecond = Number(raw.padEnd(9, '0'));\n assignField(fields, 'millisecond', Math.floor(nanoOfSecond / 1_000_000));\n assignField(fields, 'microsecond', Math.floor(nanoOfSecond / 1_000) % 1_000);\n assignField(fields, 'nanosecond', nanoOfSecond % 1_000);\n break;\n }\n case 'a': {\n // Matches case-insensitively (see pattern.ts's foldCase), so the\n // lookup here has to fold too, or \"pm\" would pass the regex and\n // then fail this indexOf against the exact-case vocab.\n const periodIndex = vocab.dayPeriod.findIndex((p) => p.toLowerCase() === raw.toLowerCase());\n /* c8 ignore start @preserve -- unreachable: the 'a' token's regex\n fragment (pattern.ts's alternation() over vocab.dayPeriod) can\n only ever capture a case-insensitive match of one of\n vocab.dayPeriod's own entries. Both the regex and this lookup\n derive their vocab from the same `locale` via getLocaleVocab(),\n so periodIndex can't come back negative through parse(). */\n if (periodIndex < 0) throw new Error(`temporal-fmt: unknown day period \"${raw}\" for locale \"${locale}\".`);\n /* c8 ignore stop @preserve */\n assignField(fields, 'dayPeriodRaw', raw);\n assignField(fields, 'isPM', periodIndex === 1);\n break;\n }\n case 'zzz':\n assignField(fields, 'timeZoneId', raw);\n break;\n case 'X': case 'XX': case 'XXX':\n case 'x': case 'xx': case 'xxx':\n assignField(fields, 'offsetString', parseOffsetString(raw, token));\n break;\n case 'Q':\n assignField(fields, 'quarter', Number(raw));\n break;\n case 'QQQ':\n // strips the literal \"Q\" prefix the token itself formats; the suffix\n // digit is the quarter value 1-4\n assignField(fields, 'quarter', Number(raw.slice(1)));\n break;\n }\n}\n\n// The lenient split-selection heuristic for ambiguous glued numeric runs.\n// See README \"Lenient parse mode\" — the strict default throws on these,\n// lenient mode opts into picking one split instead.\nfunction pickLenientSplit(splits: number[][], tokens: string[]): number[] {\n // Prefer the split where a \"d\" (day) token, if any, has a value of 12 or\n // less. Rationale: when a person writes a glued run like \"121\" for an\n // Md format string, the reading \"Dec 1\" (M=12, d=1) is what they\n // typically meant — if they meant \"Jan 21\" they would more often have\n // written it as \"1/21\" or \"01/21\" with a separator or padding, since the\n // 2-digit day is the more naturally-cohesive unit to keep glued. This\n // isn't a guarantee, which is exactly why lenient mode is opt-in — but\n // it's a reasonable default when the caller has asked us to guess.\n const dayIndex = tokens.indexOf('d');\n if (dayIndex !== -1) {\n const smallDaySplits = splits.filter((s) => s[dayIndex]! <= 12);\n if (smallDaySplits.length > 0) {\n return smallDaySplits[0]!;\n }\n }\n // Fallback to the first valid split when the day heuristic doesn't\n // narrow it down — deterministic, and \"first\" here means \"whichever\n // enumerateValidSplits returned first\", which is a depth-first\n // leftmost-shortest walk over the candidate splits.\n return splits[0]!;\n}\n\n// emulates strptime (POSIX) for 2-digit years so the result doesn't depend\n// on the current clock: 00-68 -> 2000-2068, 69-99 -> 1900-1999\n// https://www.man7.org/linux//man-pages/man3/strptime.3p.html\nfunction resolveYear(fields: Fields): number | undefined {\n if (fields.year !== undefined && fields.twoDigitYear !== undefined) {\n // FormatSyntaxError, not ParseMismatchError: this is a contradiction\n // in the format string itself (both a full-year token and \"yy\" are\n // present), not a mismatch between the format and a specific input.\n // \"y\" and \"yyyy\" both land in fields.year, so this also covers a\n // \"y\"+\"yy\" mix, not just \"yyyy\"+\"yy\" — kept generic rather than\n // naming a specific pair.\n throw new FormatSyntaxError({\n message: 'temporal-fmt: format string mixes a full-year token (\"yyyy\"/\"y\") with the two-digit \"yy\" token.',\n });\n }\n if (fields.year !== undefined) return fields.year;\n if (fields.twoDigitYear !== undefined) {\n return fields.twoDigitYear <= 68 ? 2000 + fields.twoDigitYear : 1900 + fields.twoDigitYear;\n }\n return undefined;\n}\n\nfunction resolveHour(fields: Fields, formatStr: string, locale: string): number | undefined {\n if (fields.hour !== undefined && fields.hour12 !== undefined) {\n throw new FormatSyntaxError({\n format: formatStr,\n message:\n `temporal-fmt: format string \"${formatStr}\" mixes a 24-hour token (\"HH\"/\"H\") with a ` +\n `12-hour token (\"hh\"/\"h\").`,\n });\n }\n if (fields.hour !== undefined) {\n if (fields.dayPeriodRaw !== undefined) {\n throw new FormatSyntaxError({\n format: formatStr,\n message:\n `temporal-fmt: format string \"${formatStr}\" mixes a 24-hour token (\"HH\"/\"H\") with a ` +\n `day-period token (\"a\"). Both describe the same field; use one or the other, not both.`,\n });\n }\n return fields.hour;\n }\n if (fields.hour12 !== undefined) {\n if (fields.isPM === undefined) {\n throw new FormatSyntaxError({\n format: formatStr,\n message:\n `temporal-fmt: format string \"${formatStr}\" uses a 12-hour token (\"hh\"/\"h\") without an \"a\" token, ` +\n `so parse() can't tell AM from PM.`,\n });\n }\n return (fields.hour12 % 12) + (fields.isPM ? 12 : 0);\n }\n return undefined;\n}\n\n/**\n * Parses `input` against `formatStr` and builds the real Temporal value it\n * describes: a `Temporal.PlainDate`, `PlainTime`, `PlainDateTime`, or\n * `ZonedDateTime` depending on which tokens are present.\n *\n * Returns `unknown` — this package has no ambient `Temporal` types to return\n * a real one against.\n *\n * `options.locale` picks the calendar the result is built in. Pass a locale\n * tag with a `-u-ca-` extension (e.g. `'en-u-ca-hebrew'`) to parse into a\n * non-Gregorian calendar.\n *\n * @throws if `input` doesn't match `formatStr`'s shape at all\n * @throws if it matches the shape but describes an impossible date (e.g. Feb\n * 30) or self-contradictory data (e.g. a weekday name that doesn't match the\n * actual date)\n *\n * @example\n * parse('yyyy-MM-dd HH:mm', '2026-08-04 15:45') // Temporal.PlainDateTime\n * parse('yyyy-MM', '2026-08-04T15:45:30') // throws — shape doesn't match\n * parse('yyyy-MM-dd', '2026-02-30') // throws — not a real date\n */\nexport function parse(formatStr: string, input: string, options: NumberingParseOptions = {}): unknown | undefined {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new FormatSyntaxError({\n format: formatStr,\n message:\n `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`,\n });\n }\n\n if (input.length > MAX_INPUT_LENGTH) {\n throw new FormatSyntaxError({\n input,\n message: `temporal-fmt: input exceeds maximum length of ${MAX_INPUT_LENGTH} characters (got ${input.length}).`,\n });\n }\n\n // Transliterate non-ASCII numerals to ASCII before any matching happens,\n // when the caller opts in via parseNumberingSystem. Every regex this\n // module builds expects 0-9; this is the one place that assumption\n // could otherwise be violated by locale-native input digits.\n if (options.parseNumberingSystem) {\n input = applyParseNumbering(input, options);\n }\n\n const locale = options.locale ?? DEFAULT_LOCALE;\n const calendar = resolveCalendar(locale);\n const pattern = getPattern(formatStr, locale);\n const match = pattern.regex.exec(input);\n if (!match) {\n throw new ParseMismatchError({\n input, format: formatStr,\n // reason set explicitly (not just message): parse.test.js's\n // \"safeParse: failure returns { ok: false, error } with a\n // TemporalFmtError\" asserts result.error.reason carries the\n // underlying detail text, matching what wrapUntypedError used to\n // populate when this message reached it as a caught plain Error.\n reason: 'no valid pattern matches the format string and input shape',\n message: `temporal-fmt: no valid pattern matches the format string and input shape`,\n });\n }\n\n if (pattern.groups.length === 0) {\n // ParseMismatchError, not FormatSyntaxError: pinned by\n // errors.test.js's \"format string with no tokens at all falls\n // through to ParseMismatchError\" — wrapUntypedError's classifier\n // has no branch for this message, so it lands on the\n // PARSE_MISMATCH fallback, and a direct throw here needs to\n // agree with that.\n throw new ParseMismatchError({\n format: formatStr,\n // reason set explicitly: errors.test.js's \"format string with no\n // tokens at all falls through to ParseMismatchError\" asserts\n // error.reason matches /has no tokens/.\n reason: `format string \"${formatStr}\" has no tokens — nothing to parse into a value.`,\n message: `temporal-fmt: format string \"${formatStr}\" has no tokens — nothing to parse into a value.`,\n });\n }\n\n // The regex's zzz fragment only matches a bounded zone-id *shape* (see\n // TIME_ZONE_SHAPE in pattern.ts) rather than alternating every real IANA\n // name inline, so a shape match isn't proof of a real zone yet — check\n // Zone ids can't be enumerated in the regex itself (there are ~400 of\n // them and they change over time as IANA updates the tz database), so\n // the regex only captures the zzz group's shape and this loop checks\n // each captured zzz group against the actual zone list here. Unlike a\n // regex-shape mismatch, this failure has a specific cause worth\n // naming: the shape matched but the zone id itself isn't recognized.\n for (const { name, token } of pattern.groups) {\n if (token === 'zzz' && !isValidTimeZone(match.groups![name]!)) {\n throw new InvalidTimeZoneError({\n input, format: formatStr, actual: match.groups![name],\n reason: 'not a recognized IANA time zone identifier',\n });\n }\n }\n\n // A run of 2+ adjacent unpadded-numeric tokens with no literal separator\n // (e.g. \"Md\", \"dM\", \"Hms\") is captured by a single bounded digit group in\n // the regex (see buildCapturingPattern — per-token variable-width\n // fragments made near-miss matching exponential in the number of glued\n // tokens). Resolve each run's per-token split here instead: unique valid\n // split resolves (identical to what the old regex's own greedy match\n // produced, since the old match was always one of the valid splits);\n // 2+ valid splits is genuinely ambiguous input — strict mode throws,\n // lenient opts into the documented heuristic. A span with 0 valid\n // splits matched the run's width window but names no valid per-token\n // assignment, which the old per-token fragments rejected at match\n // time — surface the same \"no valid pattern matches\" error.\n const runValues = new Map<string, string>();\n for (const run of pattern.ambiguousRuns) {\n const runDigits = match.groups![run.groupName]!;\n const splits = enumerateValidSplits(runDigits, run.tokens);\n if (splits.length === 0) {\n throw new ParseMismatchError({\n input, format: formatStr,\n reason: 'no valid pattern matches the format string and input shape',\n message: `temporal-fmt: no valid pattern matches the format string and input shape`,\n });\n }\n if (splits.length > 1) {\n // Strict default — throw on ambiguity. The whole point of the\n // library's parse() is to refuse to guess when the same input has\n // more than one valid reading. Lenient mode (opt-in via\n // options.lenient) instead picks one split via a documented\n // heuristic — see pickLenientSplit() above and the README section\n // \"Lenient parse mode\" for why this is strictly additive and never\n // the default.\n if (!options.lenient) {\n throw new AmbiguousInputError({\n input, format: formatStr,\n message:\n `temporal-fmt: \"${runDigits}\" in format string \"${formatStr}\" is ambiguous — ` +\n `${splits.length} different ways to read tokens \"${run.tokens.join('')}\" (with no separator ` +\n `between them) are all individually valid (e.g. ${JSON.stringify(splits[0])} vs ${JSON.stringify(splits[1])}). ` +\n `parse() won't guess; add a separator between these tokens, or use their padded form ` +\n `(e.g. \"MM\" instead of \"M\") so each one has a fixed width. ` +\n `Pass { lenient: true } to opt into a documented heuristic that picks one.`,\n });\n }\n const picked = pickLenientSplit(splits, run.tokens);\n run.groupNames.forEach((name, idx) => runValues.set(name, String(picked[idx])));\n } else {\n run.groupNames.forEach((name, idx) => runValues.set(name, String(splits[0]![idx])));\n }\n }\n const fields: Fields = {};\n // Per-token values for glued-run members come from the split\n // enumeration above (runValues); every other token reads its own\n // regex group directly.\n for (const { name, token } of pattern.groups) {\n const raw = runValues.get(name) ?? match.groups![name]!;\n applyGroup(fields, token, raw, locale, formatStr);\n }\n\n const year = resolveYear(fields);\n const hour = resolveHour(fields, formatStr, locale);\n const { month, day, minute, second, millisecond, microsecond, nanosecond, timeZoneId, offsetString, weekdayExpected, weekdayRaw, quarter } = fields;\n\n const hasAnyDatePart = year !== undefined || month !== undefined || day !== undefined;\n const hasFullDate = year !== undefined && month !== undefined && day !== undefined;\n if (hasAnyDatePart && !hasFullDate) {\n throw new InvalidDateError({\n format: formatStr,\n message:\n `temporal-fmt: format string \"${formatStr}\" has an incomplete date — ` +\n `year, month, and day tokens must all be present together.`,\n });\n }\n\n const hasTime = hour !== undefined || minute !== undefined || second !== undefined || millisecond !== undefined;\n\n if (timeZoneId !== undefined && !(hasFullDate && hasTime)) {\n throw new FormatSyntaxError({\n format: formatStr,\n message:\n `temporal-fmt: format string \"${formatStr}\" has a \"zzz\" token but needs a full date and time ` +\n `to build a ZonedDateTime.`,\n });\n }\n\n // Mirror zzz's full-date-and-time requirement: an offset alone is\n // meaningless without a wall-clock instant to anchor it to. Throws the\n // same kind of \"needs full date and time\" error zzz throws — separate\n // message so a caller reading it can tell which token type they\n // forgot to pair with a full date+time.\n if (offsetString !== undefined && !(hasFullDate && hasTime)) {\n throw new FormatSyntaxError({\n format: formatStr,\n message:\n `temporal-fmt: format string \"${formatStr}\" has an offset token (X/XX/XXX/x/xx/xxx) but needs a full date and time ` +\n `to build a ZonedDateTime.`,\n });\n }\n\n if (weekdayExpected !== undefined && !hasFullDate) {\n throw new FormatSyntaxError({\n format: formatStr,\n message:\n `temporal-fmt: format string \"${formatStr}\" has a weekday token (\"EEEE\"/\"EEE\") but needs ` +\n `a full date to validate it against.`,\n });\n }\n\n if (!hasFullDate && !hasTime) {\n // shouldn't happen — every token maps to a date, time, zone, or\n // weekday field, and weekday-without-date already threw above\n throw new FormatSyntaxError({\n format: formatStr,\n message: `temporal-fmt: format string \"${formatStr}\" has no date or time tokens to parse.`,\n });\n }\n\n const temporal = getTemporal();\n const timeFields = {\n hour: hour ?? 0,\n minute: minute ?? 0,\n second: second ?? 0,\n millisecond: millisecond ?? 0,\n microsecond: microsecond ?? 0,\n nanosecond: nanosecond ?? 0,\n };\n // omitted entirely for the default calendar (see resolveCalendar) so\n // construction stays plain ISO 8601 unless a caller's locale asks for\n // something else — Temporal calendars don't apply to time-only values.\n const calendarField = calendar ? { calendar } : {};\n\n // overflow: 'reject' — without it Temporal *clamps* out-of-range fields\n // (Feb 30 silently becomes Feb 28) instead of throwing, which would\n // contradict the \"throws on genuinely invalid data\" behavior parse() promises.\n const reject = { overflow: 'reject' as const };\n\n let result: unknown;\n try {\n if (timeZoneId !== undefined) {\n // offset: 'prefer' never throws on a mismatch — it just falls back to\n // the zone's real offset at this instant, silently overriding\n // whatever the offset token said. That's also what resolves a\n // repeated wall-clock time (DST fall-back): without an explicit\n // offset, Temporal defaults to the first occurrence, so passing the\n // token's offset here is what lets a second-occurrence input resolve\n // to the second occurrence instead of always falling back to the\n // first. Either way, \"prefer\" can't be used to detect disagreement —\n // that's checked explicitly below, once we have a real ZonedDateTime\n // to compare against, instead of relying on the wording of whatever\n // error Temporal's active implementation happens to throw (that\n // wording isn't part of the spec and differs between the native\n // Temporal global and userland polyfills).\n const zoneOptions: Temporal.ZonedDateTimeFromOptions = { overflow: 'reject', offset: 'prefer' };\n result = temporal.ZonedDateTime.from(\n {\n year: year!, month: month!, day: day!, ...timeFields, ...calendarField,\n timeZone: timeZoneId,\n ...(offsetString !== undefined ? { offset: offsetString } : {}),\n },\n zoneOptions\n );\n if (offsetString !== undefined) {\n // 'prefer' silently rewrites the wall-clock time itself when the\n // input falls in a DST gap (the time never occurred, so there's\n // no instant to prefer toward) — it doesn't just pick a\n // different offset for the same clock time, the way it does for\n // an overlap. Checking offsetString alone can't tell \"gap,\n // silently moved\" apart from \"overlap, correctly resolved,\"\n // since both can produce an actualOffset that differs from what\n // was parsed. Comparing the wall-clock fields catches the gap\n // case: they can only drift from the parsed input if Temporal\n // moved the clock time to escape the gap.\n //\n // Only checked when an offset token was given: with no offset\n // token to disagree with, a gap shifting forward is the\n // documented, wanted behavior (there's nothing to reject against).\n const zdt = result as Temporal.ZonedDateTime;\n const wallClockShifted =\n zdt.hour !== timeFields.hour ||\n zdt.minute !== timeFields.minute ||\n zdt.second !== timeFields.second;\n if (wallClockShifted) {\n // InvalidDateError, not AmbiguousInputError: the message\n // *mentions* \"not an ambiguous... instant\" as a negation, which\n // is a false-positive match against wrapUntypedError's\n // /ambiguous/i classifier regex — the actual failure here is a\n // wall-clock time that doesn't exist (DST gap), which is an\n // invalid-value problem, not an ambiguous-reading-of-input\n // problem the way the numeric-token-glue ambiguity above is.\n throw new InvalidDateError({\n input, format: formatStr,\n message:\n `\"${timeZoneId}\" has no such wall-clock time on this date — it falls in a DST gap, ` +\n `not an ambiguous or valid instant.`,\n });\n }\n const actualOffset = zdt.offset;\n if (actualOffset !== offsetString) {\n throw new ParseMismatchError({\n input, format: formatStr,\n message:\n `has both a \"zzz\" zone (${timeZoneId}) and an offset token (${offsetString}), ` +\n `but the zone's actual offset at this date/time is ${actualOffset}, not ${offsetString}.`,\n });\n }\n }\n } else if (offsetString !== undefined) {\n // An offset token with no \"zzz\" zone token present. Previously this\n // built a fixed-offset ZonedDateTime directly from the offset\n // string; now it's refused outright — an offset identifies a\n // moment's distance from UTC, not a zone, and building a\n // ZonedDateTime without a real zone identity papers over that\n // difference instead of surfacing it.\n throw new ParseMismatchError({\n input, format: formatStr,\n message:\n `format string \"${formatStr}\" has an offset token but no \"zzz\" zone token. ` +\n `An offset does not identify a time zone by itself — add \"zzz\" to the pattern, ` +\n `or parse into a PlainDateTime/PlainDate/PlainTime if a zone isn't needed.`,\n });\n } else if (hasFullDate && hasTime) {\n result = temporal.PlainDateTime.from({ year: year!, month: month!, day: day!, ...timeFields, ...calendarField }, reject);\n } else if (hasFullDate) {\n result = temporal.PlainDate.from({ year: year!, month: month!, day: day!, ...calendarField }, reject);\n } else {\n result = temporal.PlainTime.from(timeFields, reject);\n }\n } catch (err) {\n throw new InvalidDateError({\n input, format: formatStr,\n message:\n `temporal-fmt: \"${input}\" doesn't describe a valid date/time for format \"${formatStr}\": ` +\n `${(err as Error).message}`,\n });\n }\n\n if (weekdayExpected !== undefined) {\n const actual = (result as { dayOfWeek: number }).dayOfWeek;\n if (actual !== weekdayExpected) {\n const vocab = getLocaleVocab(locale);\n throw new InvalidDateError({\n input, format: formatStr,\n message:\n `temporal-fmt: \"${weekdayRaw}\" doesn't match the actual weekday (${vocab.weekdayLong[actual - 1]}) ` +\n `for the parsed date.`,\n });\n }\n }\n\n // Q/QQQ is a derived field of the month: 1-3 -> Q1, 4-6 -> Q2, 7-9 -> Q3,\n // 10-12 -> Q4. If a format string carries a quarter token alongside\n // month/date tokens, parse() cross-checks the parsed quarter against the\n // month the same way EEEE cross-checks weekday against date — silently\n // accepting a mismatch would defeat the point of having a quarter token\n // at all, since you'd be telling parse() one thing and the date another.\n if (quarter !== undefined && month !== undefined) {\n const expectedQuarter = Math.ceil(month / 3);\n if (quarter !== expectedQuarter) {\n throw new InvalidDateError({\n format: formatStr,\n message:\n `temporal-fmt: format string \"${formatStr}\" contains a quarter token (Q/QQQ) whose value ` +\n `(Q${quarter}) disagrees with the parsed month's actual quarter — month ${month} is in ` +\n `Q${expectedQuarter}.`,\n });\n }\n }\n\n return result;\n}\n\n// safeParse: returns a discriminated union instead of throwing. The\n// happy path returns `{ ok: true, value }` with the Temporal instance\n// (typed as `unknown` since this package has no ambient Temporal types).\n// The error path returns `{ ok: false, error }` where `error` is a\n// `TemporalFmtError` subclass when the failure is one the typed-error\n// surface in errors.ts knows how to classify (most of them), or a\n// wrapped plain `Error` (still inside a TemporalFmtError shell) when\n// the throw site hasn't been migrated yet. Callers needing the original\n// thrown object for backward compatibility should use parse() directly.\nexport type SafeParseResult =\n | { ok: true; value: unknown }\n | { ok: false; error: TemporalFmtError };\n\nexport function safeParse(formatStr: string, input: string, options: NumberingParseOptions = {}): SafeParseResult {\n try {\n return { ok: true, value: parse(formatStr, input, options) };\n } catch (err) {\n // Pass through typed errors unchanged — preserves the structured\n // fields (code/token/position/etc.) the existing typed-error\n // surface already populated.\n //\n // Every reachable throw site in parse()'s call graph now throws a\n // TemporalFmtError directly, so this condition is always true in the\n // current test suite; the false path (falling through to\n // wrapUntypedError below) is kept as a safety net for any throw site\n // added later without being migrated to a typed class immediately —\n // removing it would silently break the \"safeParse always returns a\n // TemporalFmtError\" contract documented above. Ignoring the whole\n // if/else as one unit is harmless for the true branch (real tests\n // still execute and count it — c8 just excludes it from the\n // denominator), and it's the only shape that actually suppresses the\n // false-branch marker, since c8 has no standalone \"ignore else\".\n /* c8 ignore start @preserve */\n if (err instanceof TemporalFmtError) {\n return { ok: false, error: err };\n }\n return { ok: false, error: wrapUntypedError(err as Error, { input, format: formatStr }) };\n }\n /* c8 ignore stop @preserve */\n}\n\n// tryParse: best-effort variant. Returns the parsed value or undefined.\n// Suppresses diagnostics entirely — when callers need the reason for\n// a failure, they should use safeParse(). Intentionally loose on the\n// return type (unknown) since this package has no ambient Temporal\n// types to return a real one against.\nexport function tryParse(formatStr: string, input: string, options: NumberingParseOptions = {}): unknown | undefined {\n try {\n return parse(formatStr, input, options);\n } catch {\n return undefined;\n }\n}\n\n// parseToParts: returns the matched groups with token labels, before\n// any Temporal construction. Useful for callers that want to inspect\n// what each token captured (e.g. to build a non-Temporal result, or to\n// cross-check fields themselves) without committing to the inferred\n// Temporal type parse() would build.\n//\n// Throws the same errors parse() throws for early validation (unknown\n// token, unterminated quote, no-match, ambiguity in strict mode) since\n// those failures happen before any group assignment. Construction-time\n// errors (Feb 30, weekday mismatch, etc.) do not happen here —\n// parseToParts doesn't construct anything, so it can't fail at that step.\nexport interface ParsedPart {\n token: string;\n raw: string;\n // Field name (year/month/day/...) this token would assign if handed\n // to parse()'s applyGroup loop. undefined for tokens that don't map\n // to a single field (none today, but kept here so future additions\n // don't have to widen the type).\n field?: string;\n // Position of `raw` in `input`, 0-indexed. Lets a caller highlight\n // the matched span in an editor/CLI.\n position: number;\n}\n\nexport function parseToParts(formatStr: string, input: string, options: NumberingParseOptions = {}): ParsedPart[] {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new FormatSyntaxError({\n format: formatStr,\n message:\n `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`,\n });\n }\n if (input.length > MAX_INPUT_LENGTH) {\n throw new FormatSyntaxError({\n input,\n message: `temporal-fmt: input exceeds maximum length of ${MAX_INPUT_LENGTH} characters (got ${input.length}).`,\n });\n }\n\n // Same numeral transliteration parse() does — see the comment there.\n if (options.parseNumberingSystem) {\n input = applyParseNumbering(input, options);\n }\n\n const locale = options.locale ?? DEFAULT_LOCALE;\n const pattern = getPattern(formatStr, locale);\n const match = pattern.regex.exec(input);\n if (!match) {\n throw new ParseMismatchError({\n input, format: formatStr,\n // reason set explicitly (not just message): parse.test.js's\n // \"safeParse: failure returns { ok: false, error } with a\n // TemporalFmtError\" asserts result.error.reason carries the\n // underlying detail text, matching what wrapUntypedError used to\n // populate when this message reached it as a caught plain Error.\n reason: 'no valid pattern matches the format string and input shape',\n message: `temporal-fmt: no valid pattern matches the format string and input shape`,\n });\n }\n if (pattern.groups.length === 0) {\n // ParseMismatchError, not FormatSyntaxError: pinned by\n // errors.test.js's \"format string with no tokens at all falls\n // through to ParseMismatchError\" — wrapUntypedError's classifier\n // has no branch for this message, so it lands on the\n // PARSE_MISMATCH fallback, and a direct throw here needs to\n // agree with that.\n throw new ParseMismatchError({\n format: formatStr,\n // reason set explicitly: errors.test.js's \"format string with no\n // tokens at all falls through to ParseMismatchError\" asserts\n // error.reason matches /has no tokens/.\n reason: `format string \"${formatStr}\" has no tokens — nothing to parse into a value.`,\n message: `temporal-fmt: format string \"${formatStr}\" has no tokens — nothing to parse into a value.`,\n });\n }\n // Same zzz shape-validation parse() does — kept here for parity, so\n // a caller using parseToParts sees the same InvalidTimeZoneError for\n // a bogus zone id, not a silently-accepted bogus zone.\n for (const { name, token } of pattern.groups) {\n if (token === 'zzz' && !isValidTimeZone(match.groups![name]!)) {\n throw new InvalidTimeZoneError({\n input, format: formatStr, actual: match.groups![name],\n reason: 'not a recognized IANA time zone identifier',\n });\n }\n }\n\n // Glued-run split handling: same as parse() — each run's single regex\n // group is split into per-token values by enumerateValidSplits();\n // unique split resolves, 2+ splits throws in strict mode / heuristic-\n // picks in lenient, 0 splits is a shape mismatch. parseToParts mirrors\n // parse() so callers switching between the two on the same input get\n // consistent results.\n const runValues = new Map<string, string>();\n for (const run of pattern.ambiguousRuns) {\n const runDigits = match.groups![run.groupName]!;\n const splits = enumerateValidSplits(runDigits, run.tokens);\n if (splits.length === 0) {\n throw new ParseMismatchError({\n input, format: formatStr,\n reason: 'no valid pattern matches the format string and input shape',\n message: `temporal-fmt: no valid pattern matches the format string and input shape`,\n });\n }\n if (splits.length > 1) {\n if (!options.lenient) {\n throw new AmbiguousInputError({\n input, format: formatStr,\n message:\n `temporal-fmt: \"${runDigits}\" in format string \"${formatStr}\" is ambiguous — ` +\n `${splits.length} different ways to read tokens \"${run.tokens.join('')}\" (with no separator ` +\n `between them) are all individually valid (e.g. ${JSON.stringify(splits[0])} vs ${JSON.stringify(splits[1])}). ` +\n `parse() won't guess; add a separator between these tokens, or use their padded form ` +\n `(e.g. \"MM\" instead of \"M\") so each one has a fixed width. ` +\n `Pass { lenient: true } to opt into a documented heuristic that picks one.`,\n });\n }\n const picked = pickLenientSplit(splits, run.tokens);\n run.groupNames.forEach((name, idx) => runValues.set(name, String(picked[idx])));\n } else {\n run.groupNames.forEach((name, idx) => runValues.set(name, String(splits[0]![idx])));\n }\n }\n\n const parts: ParsedPart[] = [];\n // match.indices.groups (provided by the regex 'd' flag) gives the\n // [start, end] of each named group in the input. Used here so positions\n // are accurate even when literals separate tokens — summing raw\n // lengths alone wouldn't account for the literal characters between\n // groups. Falls back to the cumulative-raw-length heuristic on engines\n // without 'd' support (none we target, but the fallback keeps the\n // code robust if the flag is ever removed).\n const indices = (match as RegExpMatchArray & { indices?: { groups?: Record<string, [number, number]> } }).indices;\n const groupIndices = indices?.groups;\n let consumed = 0;\n for (const { name, token } of pattern.groups) {\n const raw = runValues.get(name) ?? match.groups![name]!;\n // Glued-run members have no regex group of their own — the regex's\n // recorded indices point at the run's overall span, not the\n // individual token's slice within it — so fall back to cumulative-\n // raw-length for them. Positions stay monotonic but may not be\n // exact for tokens inside a resolved run. Documented as a known\n // limitation; the alternative (re-running the regex with the chosen\n // split baked in) would mean a second match pass for a corner case\n // the caller opted into by gluing unpadded tokens.\n const fromIndices = !runValues.has(name) && groupIndices?.[name];\n /* c8 ignore next */\n const position = fromIndices ? fromIndices[0] : (match.index ?? 0) + consumed;\n parts.push({ token, raw, position });\n consumed += raw.length;\n }\n return parts;\n}\n\n// compileParser: pre-compiles a format string into an object whose\n// parse()/safeParse()/parseToParts() methods skip the per-call\n// pattern-cache lookup. The patternCache in this module means a plain\n// parse(fmt, input) call already pays only a Map lookup after the first\n// call, so compileParser is mostly an ergonomics affordance — useful\n// for callers who want to hold the compiled parser explicitly (e.g. to\n// inspect the pattern via the .pattern property).\nexport interface CompiledParser {\n parse(input: string, options?: NumberingParseOptions): unknown;\n safeParse(input: string, options?: NumberingParseOptions): SafeParseResult;\n tryParse(input: string, options?: NumberingParseOptions): unknown | undefined;\n parseToParts(input: string, options?: NumberingParseOptions): ParsedPart[];\n readonly formatStr: string;\n readonly pattern: CapturingPattern;\n}\n\nexport function compileParser(formatStr: string, options: NumberingParseOptions = {}): CompiledParser {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new FormatSyntaxError({\n format: formatStr,\n message:\n `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`,\n });\n }\n // Pre-compile against the default locale; per-call locales will\n // re-resolve via getPattern() if they differ. Most callers use one\n // locale consistently, so pre-compiling against the default keeps\n // the fast path fast.\n const locale = options.locale ?? DEFAULT_LOCALE;\n const pattern = getPattern(formatStr, locale);\n return {\n formatStr,\n pattern,\n parse(input: string, opts: NumberingParseOptions = {}) {\n return parse(formatStr, input, { locale, ...opts });\n },\n safeParse(input: string, opts: NumberingParseOptions = {}) {\n return safeParse(formatStr, input, { locale, ...opts });\n },\n tryParse(input: string, opts: NumberingParseOptions = {}) {\n return tryParse(formatStr, input, { locale, ...opts });\n },\n parseToParts(input: string, opts: NumberingParseOptions = {}) {\n return parseToParts(formatStr, input, { locale, ...opts });\n },\n };\n}"],"mappings":"gQAIA,SAASA,GAAaC,EAAyB,CAC7C,OAAOA,EAAQ,QAAQ,sBAAuB,MAAM,CACtD,CAEA,SAASC,EAAYC,EAAkBC,EAAkB,GAAe,CACtE,IAAMC,EAAUF,EAAO,IAAIH,EAAY,EACvC,OAAKI,EAKE,MAAMC,EAAQ,IAAIC,EAAQ,EAAE,KAAK,GAAG,CAAC,IALf,MAAMD,EAAQ,KAAK,GAAG,CAAC,GAMtD,CAOA,SAASC,GAASC,EAAuB,CACvC,OAAOA,EAAM,QAAQ,YAAcC,GAAO,IAAIA,EAAG,YAAY,CAAC,GAAGA,EAAG,YAAY,CAAC,GAAG,CACtF,CAYA,IAAMC,GAAkB,2GAqBlBC,GAAwC,CAC5C,EAAK,8BACL,GAAK,mBACL,IAAK,0BACL,EAAK,wBACL,GAAK,aACL,IAAK,mBACP,EAEA,SAASC,IAA8B,CACrC,OAAOF,EACT,CAEA,IAAIG,EAKJ,SAASC,IAA+B,CACtC,OAAKD,IACHA,EAAe,IAAI,IAAI,KAAK,kBAAkB,UAAU,CAAC,EACzDA,EAAa,IAAI,KAAK,GAEjBA,CACT,CAEA,IAAME,GAAkB,6CAiBjB,SAASC,EAAgBC,EAAsB,CACpD,GAAIF,GAAgB,KAAKE,CAAG,GAAKH,GAAgB,EAAE,IAAIG,CAAG,EAAG,MAAO,GACpE,GAAI,CACF,O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AW8C,EAAO,CAAE,OAAA7C,EAAQ,GAAGqG,CAAK,CAAC,CACpD,EACA,UAAUxD,EAAewD,EAA8B,CAAC,EAAG,CACzD,OAAOV,GAAU5F,EAAW8C,EAAO,CAAE,OAAA7C,EAAQ,GAAGqG,CAAK,CAAC,CACxD,EACA,SAASxD,EAAewD,EAA8B,CAAC,EAAG,CACxD,OAAOP,GAAS/F,EAAW8C,EAAO,CAAE,OAAA7C,EAAQ,GAAGqG,CAAK,CAAC,CACvD,EACA,aAAaxD,EAAewD,EAA8B,CAAC,EAAG,CAC5D,OAAON,GAAahG,EAAW8C,EAAO,CAAE,OAAA7C,EAAQ,GAAGqG,CAAK,CAAC,CAC3D,CACF,CACF","names":["escapeRegExp","literal","alternation","values","caseInsensitive","escaped","foldCase","value","ch","TIME_ZONE_SHAPE","OFFSET_SHAPES","getTimeZoneFragment","validZoneSet","getValidZoneSet","FIXED_OFFSET_RE","isValidTimeZone","raw","getTemporal","NUMERIC_FRAGMENTS","QQQ_FRAGMENT","FORMAT_ONLY_TOKENS","YYYY_EXACT","YYYY_EXTENDED","Y_FRAGMENT","DIGIT_LEADING_TOKENS","UNBOUNDED_WIDTH_TOKENS","tokenFragment","token","locale","nextToken","numeric","UnknownTokenError","vocab","getLocaleVocab","UNPADDED_NUMERIC_TOKENS","UNPADDED_NUMERIC_RANGES","enumerateValidSplits","digits","tokens","memo","solve","tokenIndex","offset","key","cached","result","ranges","results","width","min","max","piece","restSplit","escapeRegExp","literal","MAX_AMBIGUITY_BITS","widthChoicesBits","choices","isDigitConsumingStart","piece","DIGIT_LEADING_TOKENS","buildCapturingPattern","pieces","locale","groups","ambiguousRuns","source","i","ambiguityBits","currentRun","flushRun","nextPiece","name","token","tokenFragment","runName","tokenCount","idx","UNPADDED_NUMERIC_TOKENS","nextToken","UNBOUNDED_WIDTH_TOKENS","FormatSyntaxError","patternCache","MAX_CACHE_SIZE","subscribeToVocabChanges","getPattern","formatStr","locale","key","canonicalCacheKey","pattern","oldestKey","buildCapturingPattern","tokenize","calendarCache","MAX_CALENDAR_CACHE_SIZE","resolveCalendar","assertValidLocaleTag","canonicalLocale","calendar","parts","extensionIndex","calendarKeyIndex","resolved","parseOffsetString","raw","token","sign","body","hoursStr","minutesStr","hours","minutes","InvalidOffsetError","assignField","fields","value","applyGroup","vocab","getLocaleVocab","nanoOfSecond","periodIndex","p","pickLenientSplit","splits","tokens","dayIndex","smallDaySplits","resolveYear","FormatSyntaxError","resolveHour","parse","input","options","applyParseNumbering","DEFAULT_LOCALE","match","ParseMismatchError","name","isValidTimeZone","InvalidTimeZoneError","runValues","run","runDigits","enumerateValidSplits","AmbiguousInputError","picked","idx","year","hour","month","day","minute","second","millisecond","microsecond","nanosecond","timeZoneId","offsetString","weekdayExpected","weekdayRaw","quarter","hasAnyDatePart","hasFullDate","InvalidDateError","hasTime","temporal","getTemporal","timeFields","calendarField","reject","result","zoneOptions","zdt","actualOffset","err","actual","expectedQuarter","safeParse","TemporalFmtError","wrapUntypedError","tryParse","parseToParts","groupIndices","consumed","fromIndices","position","compileParser","opts"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as p,b as h}from"./chunk-SSPABEUR.js";import{p as b}from"./chunk-5U5WJ465.js";import{a}from"./chunk-UJR6DHXY.js";import{n as f}from"./chunk-EHLRZULM.js";function x(t,n,o="closed"){if(a(t,n)>0)throw new Error("temporal-fmt: interval start must be \u2264 end (got start > end). Pass them in chronological order.");return{start:t,end:n,bounds:o}}function F(t,n){let o=a(n,t.start),r=a(n,t.end),e=t.bounds==="open"||t.bounds==="half-open-end"?o>0:o>=0,s=t.bounds==="open"||t.bounds==="half-open-start"?r<0:r<=0;return e&&s}function E(t,n){return m(t,n)}function m(t,n){return!(a(t.end,n.start)<0||a(t.start,n.end)>0)}function S(t,n){return a(t.end,n.start)<0}function T(t,n){return a(t.start,n.end)>0}function B(t,n){if(!m(t,n))return null;let o=a(t.start,n.start)>=0?t.start:n.start,r=a(t.end,n.end)<=0?t.end:n.end,e=t.bounds==="open"||t.bounds==="half-open-end"||n.bounds==="open"||n.bounds==="half-open-end",s=t.bounds==="open"||t.bounds==="half-open-start"||n.bounds==="open"||n.bounds==="half-open-start";return{start:o,end:r,bounds:e&&s?"open":e?"half-open-end":s?"half-open-start":"closed"}}function R(t,n){if(!m(t,n))return null;let o=a(t.start,n.start)<=0?t.start:n.start,r=a(t.end,n.end)>=0?t.end:n.end,e=(t.bounds==="open"||t.bounds==="half-open-end")&&(n.bounds==="open"||n.bounds==="half-open-end"),s=(t.bounds==="open"||t.bounds==="half-open-start")&&(n.bounds==="open"||n.bounds==="half-open-start");return{start:o,end:r,bounds:e&&s?"open":e?"half-open-end":s?"half-open-start":"closed"}}function v(t,n){if(!m(t,n))return[t];let o=[],r=t.bounds==="closed"||t.bounds==="half-open-end",e=t.bounds==="closed"||t.bounds==="half-open-start";return a(t.start,n.start)<0&&o.push({start:t.start,end:n.start,bounds:r?"half-open-end":"open"}),a(t.end,n.end)>0&&o.push({start:n.end,end:t.end,bounds:e?"half-open-start":"open"}),o}var A=v;function O(t){if(t.length===0)return[];let n=[...t].sort((r,e)=>a(r.start,e.start)),o=[{...n[0]}];for(let r=1;r<n.length;r++){let e=n[r],s=o[o.length-1];m(s,e)||a(s.end,e.start)===0?a(e.end,s.end)>0&&(s.end=e.end):o.push(e)}return o}var I=864e13;function k(t,n){if(n<=0)throw new Error(`temporal-fmt: splitInterval requires n > 0 (got ${n}).`);if(n===1)return[t];let o=f(t.start),r=f(t.end),e=y(o),s=y(r);if(Math.abs(e)>I||Math.abs(s)>I)throw new RangeError("temporal-fmt: splitInterval() endpoints are outside the representable Date range (approximately \xB1275,760 years). Split the interval into smaller ranges first.");let l=(s-e)/n,d=[];for(let u=0;u<n;u++){let c=e+u*l,i=u===n-1?s:c+l;d.push({start:w(c,o),end:w(i,r),bounds:u===0?t.bounds:"half-open-start"})}return d}function y(t){let n=t.year,o=t.month,r=t.day,e=o<=2?n-1:n,s=Math.floor((e>=0?e:e-399)/400),l=e-s*400,d=o>2?o-3:o+9,u=Math.floor((153*d+2)/5)+r-1,c=l*365+Math.floor(l/4)-Math.floor(l/100)+u;return(s*146097+c-719468)*864e5+(t.hour??0)*36e5+(t.minute??0)*6e4+(t.second??0)*1e3+(t.millisecond??0)}function w(t,n){let r=Math.floor(t/864e5),e=t%864e5;e<0&&(e+=864e5);let s=Math.floor(e/36e5),l=Math.floor(e%36e5/6e4),d=Math.floor(e%6e4/1e3),u=e%1e3,c=r*864e5,i=new Date(c);return{...n,year:i.getUTCFullYear(),month:i.getUTCMonth()+1,day:i.getUTCDate(),hour:s,minute:l,second:d,millisecond:u}}function V(t,n,o={}){try{let r=p(t.start,n,o),e=p(t.end,n,o);return`${r} \u2013 ${e}`}catch(r){try{let e=new Intl.DateTimeFormat(b(o.locale??"en-US"),{}),s=_(t.start),l=_(t.end);return e.formatRange(s,l)}catch{throw r}}}function C(t,n,o={}){let r=h(t.start,n,o),e=h(t.end,n,o),s=[...r];return s.push({type:"literal",value:" \u2013 "}),s.push(...e),s}function _(t){let n=t;if(typeof n?.toInstant=="function")return new Date(n.toInstant().epochMilliseconds);if(typeof n?.year=="number"&&typeof n?.month=="number"&&typeof n?.day=="number")return new Date(Date.UTC(n.year,n.month-1,n.day,n.hour??0,n.minute??0,n.second??0,n.millisecond??0));throw new Error(`temporal-fmt: formatRange() expected Temporal values with year/month/day, got ${typeof t}.`)}export{x as a,F as b,E as c,m as d,S as e,T as f,B as g,R as h,v as i,A as j,O as k,k as l,V as m,C as n};
|
|
2
|
+
//# sourceMappingURL=chunk-4XRE37WT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/interval.ts"],"sourcesContent":["// Intervals / ranges. An interval is a pair of\n// (start, end) Temporal values with bounds semantics: open, closed,\n// or half-open. Operations: contains, overlaps, intersects, isBefore,\n// isAfter, intersection, union, difference, subtract, mergeIntervals,\n// splitInterval. Plus formatRange / formatRangeToParts with intelligent\n// collapsing.\n//\n// All operations are field-based (no instanceof), matching the rest of\n// the library. Internally uses the comparison helpers from comparison.ts\n// to order endpoints.\n\nimport { compare } from './comparison.js';\nimport { format, formatToParts, type FormattedPart } from './format.js';\nimport { asDateFieldView, type DateFieldView } from './calendarUtils.js';\nimport { normalizeLocaleTag } from './localeVocab.js';\nimport type { FormatOptions } from './tokens.js';\n\nexport type IntervalBounds = 'open' | 'closed' | 'half-open-start' | 'half-open-end';\n\nexport interface Interval {\n start: unknown;\n end: unknown;\n bounds: IntervalBounds;\n}\n\nexport function interval(start: unknown, end: unknown, bounds: IntervalBounds = 'closed'): Interval {\n // Validate that start ≤ end, otherwise the interval is malformed.\n const cmp = compare(start, end);\n if (cmp > 0) {\n throw new Error(\n `temporal-fmt: interval start must be ≤ end (got start > end). Pass them in chronological order.`\n );\n }\n return { start, end, bounds };\n}\n\n// Inclusive containment check accounting for bounds semantics.\n// - 'closed': [start, end] — both endpoints included\n// - 'open': (start, end) — neither endpoint included\n// - 'half-open-start': (start, end] — start excluded, end included\n// - 'half-open-end': [start, end) — start included, end excluded\nexport function contains(iv: Interval, value: unknown): boolean {\n const startCmp = compare(value, iv.start);\n const endCmp = compare(value, iv.end);\n const afterStart = iv.bounds === 'open' || iv.bounds === 'half-open-end'\n ? startCmp > 0\n : startCmp >= 0;\n const beforeEnd = iv.bounds === 'open' || iv.bounds === 'half-open-start'\n ? endCmp < 0\n : endCmp <= 0;\n return afterStart && beforeEnd;\n}\n\n// Two intervals overlap iff their ranges intersect, regardless of bounds.\n// intersects() is the boolean form; intersection() returns the actual\n// overlap interval.\nexport function overlaps(a: Interval, b: Interval): boolean {\n return intersects(a, b);\n}\n\nexport function intersects(a: Interval, b: Interval): boolean {\n // a is entirely before b: a.end < b.start\n if (compare(a.end, b.start) < 0) return false;\n // a is entirely after b: a.start > b.end\n if (compare(a.start, b.end) > 0) return false;\n // Touching endpoints with both-closed bounds counts as overlap;\n // open bounds would not. To keep it simple, touching counts.\n return true;\n}\n\nexport function isBefore(a: Interval, b: Interval): boolean {\n return compare(a.end, b.start) < 0;\n}\n\nexport function isAfter(a: Interval, b: Interval): boolean {\n return compare(a.start, b.end) > 0;\n}\n\n// Returns the intersection of two intervals, or null if they don't\n// overlap. The result's bounds are the more restrictive of the two\n// inputs (closed ∩ open = open, etc.).\nexport function intersection(a: Interval, b: Interval): Interval | null {\n if (!intersects(a, b)) return null;\n const start = compare(a.start, b.start) >= 0 ? a.start : b.start;\n const end = compare(a.end, b.end) <= 0 ? a.end : b.end;\n // Compute resulting bounds: take the more restrictive at each endpoint.\n // If a.start === b.start, the more restrictive of (a.bounds, b.bounds)\n // at that endpoint wins.\n const startBoundsOpen = (a.bounds === 'open' || a.bounds === 'half-open-end')\n || (b.bounds === 'open' || b.bounds === 'half-open-end');\n const endBoundsOpen = (a.bounds === 'open' || a.bounds === 'half-open-start')\n || (b.bounds === 'open' || b.bounds === 'half-open-start');\n const bounds: IntervalBounds = startBoundsOpen && endBoundsOpen ? 'open'\n : startBoundsOpen ? 'half-open-end'\n : endBoundsOpen ? 'half-open-start'\n : 'closed';\n return { start, end, bounds };\n}\n\n// Returns the union of two intervals (the smallest interval containing\n// both), or null if they don't overlap (caller should use mergeIntervals\n// for that case).\nexport function union(a: Interval, b: Interval): Interval | null {\n if (!intersects(a, b)) return null;\n const start = compare(a.start, b.start) <= 0 ? a.start : b.start;\n const end = compare(a.end, b.end) >= 0 ? a.end : b.end;\n // Union's bounds are the less restrictive at each endpoint.\n const startBoundsOpen = (a.bounds === 'open' || a.bounds === 'half-open-end')\n && (b.bounds === 'open' || b.bounds === 'half-open-end');\n const endBoundsOpen = (a.bounds === 'open' || a.bounds === 'half-open-start')\n && (b.bounds === 'open' || b.bounds === 'half-open-start');\n const bounds: IntervalBounds = startBoundsOpen && endBoundsOpen ? 'open'\n : startBoundsOpen ? 'half-open-end'\n : endBoundsOpen ? 'half-open-start'\n : 'closed';\n return { start, end, bounds };\n}\n\n// Returns the part of `a` that is not in `b`. May produce 0, 1, or 2\n// intervals depending on the overlap shape.\n//\n// Bounds semantics: each surviving piece keeps the inclusivity of the\n// original endpoint it inherits from `a`, and the endpoint created by the\n// cut is always exclusive (it is `b`'s edge, which belongs to the removed\n// overlap). The old implementation derived both bounds from a lossy\n// helper that collapsed several of these combinations — the pieces'\n// endpoints were right, but the bounds metadata was stricter than the\n// actual remainder for open/half-open inputs.\nexport function difference(a: Interval, b: Interval): Interval[] {\n if (!intersects(a, b)) return [a];\n const result: Interval[] = [];\n // Does `a` include its own start / end?\n const aStartIncluded = a.bounds === 'closed' || a.bounds === 'half-open-end';\n const aEndIncluded = a.bounds === 'closed' || a.bounds === 'half-open-start';\n // Part of `a` before `b` starts: [a.start, b.start) — start inclusivity\n // inherited from a, cut end always exclusive.\n if (compare(a.start, b.start) < 0) {\n result.push({ start: a.start, end: b.start, bounds: aStartIncluded ? 'half-open-end' : 'open' });\n }\n // Part of `a` after `b` ends: (b.end, a.end] — cut start always\n // exclusive, end inclusivity inherited from a.\n if (compare(a.end, b.end) > 0) {\n result.push({ start: b.end, end: a.end, bounds: aEndIncluded ? 'half-open-start' : 'open' });\n }\n return result;\n}\n\n// Alias for difference() — \"subtract\" reads more naturally at some\n// call sites than \"difference\" does.\nexport const subtract = difference;\n\n// Merges a list of intervals, combining overlapping ones. Returns a\n// sorted list of disjoint intervals. The inputs are treated as\n// immutable — the merged result carries shallow copies of any interval\n// object it extends, so a caller's own `end` reference is never\n// reassigned under them (mergeIntervals used to write `last.end =\n// current.end` straight into the caller's object).\nexport function mergeIntervals(intervals: Interval[]): Interval[] {\n if (intervals.length === 0) return [];\n const sorted = [...intervals].sort((a, b) => compare(a.start, b.start));\n const result: Interval[] = [{ ...sorted[0]! }];\n for (let i = 1; i < sorted.length; i++) {\n const current = sorted[i]!;\n const last = result[result.length - 1]!;\n if (intersects(last, current) || compare(last.end, current.start) === 0) {\n // Merge into last.\n if (compare(current.end, last.end) > 0) {\n last.end = current.end;\n }\n } else {\n result.push(current);\n }\n }\n return result;\n}\n\n// Widest instant JS Date can represent (±8.64e15 ms, i.e. ±100,000,000\n// days from the Unix epoch). splitInterval rebuilds endpoints via Date,\n// so anything outside this window would silently produce Invalid Date\n// objects with NaN year/month/day fields — reject it descriptively\n// instead.\nconst MAX_DATE_MS = 8.64e15;\n\n// Splits an interval into N equal sub-intervals. Throws if N ≤ 0.\n// Equality is by ms-distance between start and end — for date ranges\n// this approximates \"equal time slices\", which is the most useful\n// interpretation. For calendar-bound splits (e.g. \"split this month\n// into weeks\"), callers should use recurrence() instead.\nexport function splitInterval(iv: Interval, n: number): Interval[] {\n if (n <= 0) throw new Error(`temporal-fmt: splitInterval requires n > 0 (got ${n}).`);\n if (n === 1) return [iv];\n const startFields = asDateFieldView(iv.start) as DateFieldView & { hour?: number; minute?: number; second?: number; millisecond?: number };\n const endFields = asDateFieldView(iv.end) as DateFieldView & { hour?: number; minute?: number; second?: number; millisecond?: number };\n const startMs = toMs(startFields);\n const endMs = toMs(endFields);\n if (Math.abs(startMs) > MAX_DATE_MS || Math.abs(endMs) > MAX_DATE_MS) {\n throw new RangeError(\n `temporal-fmt: splitInterval() endpoints are outside the representable Date range ` +\n `(approximately ±275,760 years). Split the interval into smaller ranges first.`\n );\n }\n const step = (endMs - startMs) / n;\n const result: Interval[] = [];\n for (let i = 0; i < n; i++) {\n const sliceStart = startMs + i * step;\n const sliceEnd = i === n - 1 ? endMs : sliceStart + step;\n result.push({\n start: fromMs(sliceStart, startFields),\n end: fromMs(sliceEnd, endFields),\n bounds: i === 0 ? iv.bounds : 'half-open-start',\n });\n }\n return result;\n}\n\nfunction toMs(v: DateFieldView & { hour?: number; minute?: number; second?: number; millisecond?: number }): number {\n // Reuse the same day-count math arithmetic.ts uses, inlined.\n const y = v.year!, m = v.month!, d = v.day!;\n const y2 = m <= 2 ? y - 1 : y;\n const era = Math.floor((y2 >= 0 ? y2 : y2 - 399) / 400);\n const yoe = y2 - era * 400;\n const m2 = m > 2 ? m - 3 : m + 9;\n const doy = Math.floor((153 * m2 + 2) / 5) + d - 1;\n const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;\n const days = era * 146097 + doe - 719468;\n return days * 86_400_000\n + (v.hour ?? 0) * 3_600_000\n + (v.minute ?? 0) * 60_000\n + (v.second ?? 0) * 1_000\n + (v.millisecond ?? 0);\n}\n\nfunction fromMs(ms: number, base: DateFieldView & { hour?: number; minute?: number; second?: number; millisecond?: number }): DateFieldView {\n const MS_PER_DAY = 86_400_000;\n const dayOverflow = Math.floor(ms / MS_PER_DAY);\n let withinDay = ms % MS_PER_DAY;\n if (withinDay < 0) withinDay += MS_PER_DAY;\n const hour = Math.floor(withinDay / 3_600_000);\n const minute = Math.floor((withinDay % 3_600_000) / 60_000);\n const second = Math.floor((withinDay % 60_000) / 1_000);\n const millisecond = withinDay % 1_000;\n // `ms` (and therefore `dayOverflow`) is already an absolute epoch-ms /\n // epoch-day value — toMs() computed it via Howard Hinnant's algorithm\n // from scratch, not as an offset from `base`. So the date only needs\n // reconstructing from the Unix epoch itself; `base` is just a template\n // for whatever extra (non-date) fields get spread into the result.\n // (Previously this added dayOverflow on top of base's own epoch-ms,\n // double-counting base's offset and landing tens of thousands of days\n // away from the intended date for any non-epoch base.)\n const newMs = dayOverflow * MS_PER_DAY;\n const d = new Date(newMs);\n return {\n ...base,\n year: d.getUTCFullYear(),\n month: d.getUTCMonth() + 1,\n day: d.getUTCDate(),\n hour,\n minute,\n second,\n millisecond,\n };\n}\n\n// Formats an interval as a single string, collapsing shared fields.\n// E.g. \"August 4 – August 6, 2026\" rather than \"August 4, 2026 – August 6, 2026\".\n// Uses Intl.DateTimeFormat's formatRange when available (most engines),\n// falling back to format(start, fmt) + '–' + format(end, fmt) when not.\n\nexport function formatRange(\n iv: Interval,\n formatStr: string,\n options: FormatOptions = {},\n): string {\n // The formatStr parameter is this function's contract — the caller\n // asked for their token format on both endpoints. Honor it first:\n // format each side with the caller's format string and join with an\n // en dash. (This used to try Intl.DateTimeFormat.formatRange() first,\n // which ignores formatStr entirely — formatRange(iv, 'yyyy-MM-dd')\n // silently returned locale-default output like \"8/4/2026 – 8/6/2026\"\n // instead of \"2026-08-04 – 2026-08-06\".) Intl's range collapsing is\n // kept as a fallback for inputs the token path can't render.\n try {\n const startStr = format(iv.start as Parameters<typeof format>[0], formatStr, options);\n const endStr = format(iv.end as Parameters<typeof format>[0], formatStr, options);\n return `${startStr} – ${endStr}`;\n } catch (err) {\n // Fallback: Intl.DateTimeFormat.formatRange is the standard\n // mechanism with native field-collapse behavior, but it has no\n // knowledge of the caller's token format string.\n try {\n const fmt = new Intl.DateTimeFormat(normalizeLocaleTag(options.locale ?? 'en-US'), {});\n // Cast the interval endpoints to Date for the Intl call. Both\n // endpoints must be Temporal values that can convert to a Date;\n // for non-ZonedDateTime values we synthesize a Date via the field\n // shape (year/month/day/hour/...).\n const startDate = toJSDate(iv.start);\n const endDate = toJSDate(iv.end);\n return fmt.formatRange(startDate, endDate);\n } catch {\n // Neither path could render — surface the token-path error, since\n // the formatStr contract is the primary one.\n throw err;\n }\n }\n}\n\nexport function formatRangeToParts(\n iv: Interval,\n formatStr: string,\n options: FormatOptions = {},\n): FormattedPart[] {\n // Best-effort: returns formatToParts for the start, then a literal\n // \" – \" part, then formatToParts for the end. Doesn't currently\n // expose Intl.DateTimeFormat.formatRangeToParts's collapsed shape —\n // that would require mapping Intl's part types back to temporal-fmt's\n // token strings, which is locale-dependent and not stable across\n // engines.\n const startParts = formatToParts(iv.start as Parameters<typeof formatToParts>[0], formatStr, options);\n const endParts = formatToParts(iv.end as Parameters<typeof formatToParts>[0], formatStr, options);\n const result: FormattedPart[] = [...startParts];\n result.push({ type: 'literal', value: ' – ' });\n result.push(...endParts);\n return result;\n}\n\nfunction toJSDate(value: unknown): Date {\n const v = value as { year?: number; month?: number; day?: number; hour?: number; minute?: number; second?: number; millisecond?: number; toInstant?: () => { epochMilliseconds: number } };\n if (typeof v?.toInstant === 'function') {\n return new Date(v.toInstant().epochMilliseconds);\n }\n if (typeof v?.year === 'number' && typeof v?.month === 'number' && typeof v?.day === 'number') {\n return new Date(Date.UTC(v.year, v.month - 1, v.day, v.hour ?? 0, v.minute ?? 0, v.second ?? 0, v.millisecond ?? 0));\n }\n throw new Error(`temporal-fmt: formatRange() expected Temporal values with year/month/day, got ${typeof value}.`);\n}"],"mappings":"kKAyBO,SAASA,EAASC,EAAgBC,EAAcC,EAAyB,SAAoB,CAGlG,GADYC,EAAQH,EAAOC,CAAG,EACpB,EACR,MAAM,IAAI,MACR,sGACF,EAEF,MAAO,CAAE,MAAAD,EAAO,IAAAC,EAAK,OAAAC,CAAO,CAC9B,CAOO,SAASE,EAASC,EAAcC,EAAyB,CAC9D,IAAMC,EAAWJ,EAAQG,EAAOD,EAAG,KAAK,EAClCG,EAASL,EAAQG,EAAOD,EAAG,GAAG,EAC9BI,EAAaJ,EAAG,SAAW,QAAUA,EAAG,SAAW,gBACrDE,EAAW,EACXA,GAAY,EACVG,EAAYL,EAAG,SAAW,QAAUA,EAAG,SAAW,kBACpDG,EAAS,EACTA,GAAU,EACd,OAAOC,GAAcC,CACvB,CAKO,SAASC,EAASC,EAAaC,EAAsB,CAC1D,OAAOC,EAAWF,EAAGC,CAAC,CACxB,CAEO,SAASC,EAAWF,EAAaC,EAAsB,CAI5D,MAFI,EAAAV,EAAQS,EAAE,IAAKC,EAAE,KAAK,EAAI,GAE1BV,EAAQS,EAAE,MAAOC,EAAE,GAAG,EAAI,EAIhC,CAEO,SAASE,EAASH,EAAaC,EAAsB,CAC1D,OAAOV,EAAQS,EAAE,IAAKC,EAAE,KAAK,EAAI,CACnC,CAEO,SAASG,EAAQJ,EAAaC,EAAsB,CACzD,OAAOV,EAAQS,EAAE,MAAOC,EAAE,GAAG,EAAI,CACnC,CAKO,SAASI,EAAaL,EAAaC,EAA8B,CACtE,GAAI,CAACC,EAAWF,EAAGC,CAAC,EAAG,OAAO,KAC9B,IAAMb,EAAQG,EAAQS,EAAE,MAAOC,EAAE,KAAK,GAAK,E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AAK,KAAK,IAAIA,EAAE,KAAMA,EAAE,MAAQ,EAAGA,EAAE,IAAKA,EAAE,MAAQ,EAAGA,EAAE,QAAU,EAAGA,EAAE,QAAU,EAAGA,EAAE,aAAe,CAAC,CAAC,EAErH,MAAM,IAAI,MAAM,iFAAiF,OAAOtC,CAAK,GAAG,CAClH","names":["interval","start","end","bounds","compare","contains","iv","value","startCmp","endCmp","afterStart","beforeEnd","overlaps","a","b","intersects","isBefore","isAfter","intersection","startBoundsOpen","endBoundsOpen","union","difference","result","aStartIncluded","aEndIncluded","subtract","mergeIntervals","intervals","sorted","i","current","last","MAX_DATE_MS","splitInterval","startFields","asDateFieldView","endFields","startMs","toMs","endMs","step","sliceStart","sliceEnd","fromMs","v","y","m","d","y2","era","yoe","m2","doy","doe","ms","base","dayOverflow","withinDay","hour","minute","second","millisecond","newMs","formatRange","formatStr","options","startStr","format","endStr","err","fmt","normalizeLocaleTag","startDate","toJSDate","endDate","formatRangeToParts","startParts","formatToParts","endParts"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
1
|
+
var s=class extends Error{code;input;format;token;position;expected;actual;reason;constructor(e,t){super(e),this.name="TemporalFmtError",this.code=t.code,this.input=t.input,this.format=t.format,this.token=t.token,this.position=t.position,this.expected=t.expected,this.actual=t.actual,this.reason=t.reason;let o=Error.captureStackTrace;typeof o=="function"&&o(this,this.constructor)}toJSON(){return{name:this.name,message:this.message,code:this.code,input:this.input,format:this.format,token:this.token,position:this.position,expected:this.expected,actual:this.actual,reason:this.reason}}},T=class extends s{constructor(e){let{message:t,...o}=e;super(t??`format string "${e.format??""}" has a syntax error${e.reason?`: ${e.reason}`:""}.`,{code:"FORMAT_SYNTAX_ERROR",...o}),this.name="FormatSyntaxError"}},$=class extends s{constructor(e){let{message:t,...o}=e;super(t??`token "${e.token??""}" is not a recognized temporal-fmt token${e.format?` in format string "${e.format}"`:""}.`,{code:"UNKNOWN_TOKEN",...o}),this.name="UnknownTokenError"}},w=class extends s{constructor(e){let{message:t,...o}=e;super(t??`input "${e.input??""}" does not match format "${e.format??""}"${e.reason?`: ${e.reason}`:""}.`,{code:"PARSE_MISMATCH",...o}),this.name="ParseMismatchError"}},k=class extends s{constructor(e){let{message:t,...o}=e;super(t??`input "${e.input??""}" does not describe a valid date${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_DATE",...o}),this.name="InvalidDateError"}};/* c8 ignore start @preserve -- InvalidTimeError is part of the public
|
|
2
2
|
error-class surface (exported from index.ts, code 'INVALID_TIME')
|
|
3
3
|
but nothing in this package constructs one. Investigated wiring it
|
|
4
4
|
in the same way InvalidTimeZoneError was just wired (see parse.ts's
|
|
@@ -10,7 +10,7 @@ var i=class extends Error{code;input;format;token;position;expected;actual;reaso
|
|
|
10
10
|
is rejected as a plain shape mismatch before any semantic check
|
|
11
11
|
could run. There's no live gap to hook this into without inventing a
|
|
12
12
|
redundant check purely to give this class a body. Left unconstructed
|
|
13
|
-
until the library actually has a real invalid-time case to report. */var
|
|
13
|
+
until the library actually has a real invalid-time case to report. */var _=class extends s{constructor(e){let{message:t,...o}=e;super(t??`input "${e.input??""}" does not describe a valid time${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_TIME",...o}),this.name="InvalidTimeError"}};/* c8 ignore stop @preserve */var A=class extends s{constructor(e){let{message:t,...o}=e;super(t??`offset "${e.actual??""}" is invalid${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_OFFSET",...o}),this.name="InvalidOffsetError"}},b=class extends s{constructor(e){let{message:t,...o}=e;super(t??`time zone "${e.actual??""}" is not a recognized IANA time zone or fixed offset${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_TIME_ZONE",...o}),this.name="InvalidTimeZoneError"}};/* c8 ignore start @preserve -- InvalidCalendarError is part of the
|
|
14
14
|
public error-class surface (exported from index.ts, code
|
|
15
15
|
'INVALID_CALENDAR') but nothing in this package constructs one.
|
|
16
16
|
Checked for a wiring opportunity the same way InvalidTimeZoneError
|
|
@@ -20,8 +20,8 @@ var i=class extends Error{code;input;format;token;position;expected;actual;reaso
|
|
|
20
20
|
of the locale string — it's never handed an arbitrary "calendar"
|
|
21
21
|
value a caller could get wrong. There's no live input to reject.
|
|
22
22
|
Left unconstructed until the library actually accepts a calendar
|
|
23
|
-
parameter that could be invalid. */var
|
|
24
|
-
see rationale above */function
|
|
23
|
+
parameter that could be invalid. */var M=class extends s{constructor(e){let{message:t,...o}=e;super(t??`calendar "${e.actual??""}" is not supported${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_CALENDAR",...o}),this.name="InvalidCalendarError"}};/* c8 ignore stop @preserve */var I=class extends s{constructor(e){let{message:t,...o}=e;super(t??`input "${e.input??""}" is ambiguous${e.reason?`: ${e.reason}`:""}.`,{code:"AMBIGUOUS_INPUT",...o}),this.name="AmbiguousInputError"}},u=class extends s{constructor(e){let{message:t,...o}=e;super(t??`locale "${e.actual??""}" is not a valid BCP-47 tag${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_LOCALE",...o}),this.name="InvalidLocaleError"}},C=class extends s{constructor(e){let{message:t,...o}=e;super(t??`duration is invalid${e.reason?`: ${e.reason}`:""}.`,{code:"INVALID_DURATION",...o}),this.name="InvalidDurationError"}};/* c8 ignore start @preserve -- unreachable from the current test suite,
|
|
24
|
+
see rationale above */function H(r,e){let t=r.message;if(/unknown token|isn't a recognized token/.test(t))return new $({input:e.input,format:e.format,reason:t});if(/ambiguous/i.test(t))return new I({input:e.input,format:e.format,reason:t});if(/offset/.test(t)&&/out of range|exceeds|doesn't match the shape/i.test(t))return new A({input:e.input,format:e.format,reason:t});if(/no valid pattern matches/i.test(t))return new w({input:e.input,format:e.format,reason:t});if(/doesn't describe a valid date\/time|incomplete date|weekday token|quarter token/.test(t))return new k({input:e.input,format:e.format,reason:t});let o=t.toLowerCase();return o.includes("locale")&&(o.includes("produced no")||o.includes("not a valid"))||o.includes("cutoffs must be")?new u({input:e.input,format:e.format,reason:t}):/format string exceeds maximum length|input exceeds maximum length|unterminated quote|isn't a recognized token/i.test(t)?new T({input:e.input,format:e.format,reason:t}):new w({input:e.input,format:e.format,reason:t})}/* c8 ignore stop @preserve */var y=new Map,N=500,D=256,O=256;function Z(r,e){let t=[{key:"monthLong",length:12,label:"long month names"},{key:"monthShort",length:12,label:"short month names"},{key:"weekdayLong",length:7,label:"long weekday names"},{key:"weekdayShort",length:7,label:"short weekday names"},{key:"dayPeriod",length:2,label:"day period markers (AM/PM-equivalent)"}];for(let{key:o,length:n,label:a}of t){let i=r[o];if(i===void 0)throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}" is missing required field "${o}" (${a}).`);if(!Array.isArray(i))throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}": "${o}" must be an array, got ${typeof i}.`);if(i.length!==n)throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}": "${o}" must have exactly ${n} entries (got ${i.length}) \u2014 ${a}.`);i.forEach((m,g)=>{if(typeof m!="string"||m.length===0)throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}": "${o}[${g}]" must be a non-empty string, got ${String(m)}.`);if(m.length>O)throw new RangeError(`temporal-fmt: registerLocaleVocab for locale "${e}": "${o}[${g}]" is too long (maximum ${O} characters).`)})}if(d(r.monthLong,"MMMM month",e),d(r.monthShort,"MMM month",e),d(r.weekdayLong,"EEEE weekday",e),d(r.weekdayShort,"EEE weekday",e),r.dayPeriod[0]===r.dayPeriod[1])throw new Error(`temporal-fmt: registerLocaleVocab for locale "${e}": dayPeriod entries must differ (both are "${r.dayPeriod[0]}"); otherwise parse() can't tell AM from PM.`)}var S=[];function W(r){S.push(r)}function J(r,e){if(typeof r!="string"||r.length===0)throw new Error(`temporal-fmt: registerLocaleVocab requires a non-empty locale string, got ${String(r)}.`);if(r.length>D)throw new RangeError(`temporal-fmt: registerLocaleVocab locale is too long (maximum ${D} characters).`);Z(e,r);let t=F(r);if(!y.has(t)&&y.size>=N)throw new RangeError(`temporal-fmt: registerLocaleVocab reached the ${N}-locale limit.`);y.set(t,{monthLong:[...e.monthLong],monthShort:[...e.monthShort],weekdayLong:[...e.weekdayLong],weekdayShort:[...e.weekdayShort],dayPeriod:[...e.dayPeriod]}),p.delete(t);for(let o of S)o()}function P(r){return r.replace(/_/g,"-")}var f=new Map,B=500;function F(r){let e=f.get(r);if(e!==void 0)return e;let t;try{t=new Intl.Locale(r.replace(/_/g,"-")).toString().toLowerCase()}catch{t=r}if(f.size>=B){let o=f.keys().next().value;o!==void 0&&f.delete(o)}return f.set(r,t),t}function X(r){try{new Intl.Locale(P(r))}catch{throw new u({actual:r,reason:"not a valid BCP-47 locale tag"})}}var p=new Map,q=500;function l(r,e,t){let o=r.formatToParts(e),n=o.findIndex(g=>g.type===t);/* c8 ignore start @preserve -- defensive guard against a real but
|
|
25
25
|
unreproducible failure mode: an Intl implementation that omits the
|
|
26
26
|
requested part type entirely for some locale. Checked every locale
|
|
27
27
|
with unusual dayPeriod/weekday/month rendering available in this
|
|
@@ -32,5 +32,5 @@ var i=class extends Error{code;input;format;token;position;expected;actual;reaso
|
|
|
32
32
|
produced a false "gap" during investigation). None omit their part
|
|
33
33
|
on this runtime. A different ICU version or a non-Node Intl
|
|
34
34
|
implementation could plausibly behave differently, so this stays a
|
|
35
|
-
real check rather than an assertion. *//* c8 ignore start @preserve */if(n===-1)throw new
|
|
36
|
-
//# sourceMappingURL=chunk-
|
|
35
|
+
real check rather than an assertion. *//* c8 ignore start @preserve */if(n===-1)throw new u({message:`temporal-fmt: locale produced no "${t}" part while building match vocabulary.`});/* c8 ignore stop @preserve */let a=o[n].value,i=o[n-1],m=o[n+1];return i?.type==="literal"&&!/\s/.test(i.value)&&(a=i.value+a),m?.type==="literal"&&!/\s/.test(m.value)&&(a=a+m.value),a}function d(r,e,t){let o=new Map;for(let n=0;n<r.length;n++){let a=o.get(r[n]);if(a!==void 0)throw new Error(`temporal-fmt: locale "${t}" renders ${e} index ${a} and ${n} identically ("${r[n]}"). parse() can't reliably tell these apart for this locale/token, so this combination isn't supported.`);o.set(r[n],n)}}function j(r){let e=F(r);return y.get(e)}function Q(r){X(r);let e=F(r),t=y.get(e);if(t)return t;let o=p.get(e);if(o)return o;let n=P(r),a=new Intl.DateTimeFormat(n,{month:"long",timeZone:"UTC"}),i=new Intl.DateTimeFormat(n,{month:"short",timeZone:"UTC"}),m=[],g=[];for(let c=0;c<12;c++){let h=new Date(Date.UTC(2020,c,1));m.push(l(a,h,"month")),g.push(l(i,h,"month"))}d(m,"MMMM month",r),d(g,"MMM month",r);let v=new Intl.DateTimeFormat(n,{weekday:"long",timeZone:"UTC"}),U=new Intl.DateTimeFormat(n,{weekday:"short",timeZone:"UTC"}),E=[],L=[];for(let c=0;c<7;c++){let h=new Date(Date.UTC(2024,0,1+c));E.push(l(v,h,"weekday")),L.push(l(U,h,"weekday"))}d(E,"EEEE weekday",r),d(L,"EEE weekday",r);let V=new Intl.DateTimeFormat(n,{hour:"numeric",hour12:!0,timeZone:"UTC"}),R=l(V,new Date(Date.UTC(2020,0,1,1)),"dayPeriod"),K=l(V,new Date(Date.UTC(2020,0,1,13)),"dayPeriod"),z=[...new Set([R,K])],x={monthLong:m,monthShort:g,weekdayLong:E,weekdayShort:L,dayPeriod:z};if(p.size>=q){let c=p.keys().next().value;c!==void 0&&p.delete(c)}return p.set(e,x),x}export{s as a,T as b,$ as c,w as d,k as e,_ as f,A as g,b as h,M as i,I as j,u as k,C as l,H as m,W as n,J as o,P as p,F as q,X as r,j as s,Q as t};
|
|
36
|
+
//# sourceMappingURL=chunk-5U5WJ465.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/localeVocab.ts"],"sourcesContent":["// Structured error classes for parse()/format() failures.\n//\n// As of 0.9.0, every throw site on the parse/format data path —\n// tokenize.ts, pattern.ts, format.ts, parse.ts (parse/safeParse/tryParse/\n// parseToParts/compileParser), and the two data-path throws in\n// localeVocab.ts (partValue/assertNoCollision on the getLocaleVocab side)\n// — throws these typed classes directly instead of plain\n// `new Error(message)`. Every migrated site kept its exact pre-0.9.0\n// message text — subclasses of TemporalFmtError still satisfy\n// `instanceof Error` and message-matching regexes (e.g.\n// `/token \"HH\" requires/`), so this was safe to do without a semver-major\n// bump for either check. What *is* a breaking change for 0.9.0: code that\n// specifically checked `err.constructor === Error` or `err.name ===\n// 'Error'` will see a different name now (e.g. 'FormatSyntaxError'). See\n// the 0.9.0 changelog entry.\n//\n// Not migrated, on purpose:\n// - localeVocab.ts's registration-time throws (assertValidVocab,\n// registerLocaleVocab itself) — these are config-time API-misuse\n// errors on data the developer supplies once at startup, not runtime\n// parse/format failures, so they don't fit this module's\n// TemporalFmtErrorCode taxonomy as-is. assertNoCollision is shared\n// between the registration path and the data path (getLocaleVocab), so\n// its throw stays plain `Error` for both until that split is done —\n// see the tracking note at its call site.\n//\n// wrapUntypedError() below still exists for localeVocab.ts's registration\n// throws and for anything a caller passes into safeParse()/tryParse() from\n// outside this package. On the data path, safeParse's `if (err instanceof\n// TemporalFmtError) return { ok: false, error: err }` now catches every\n// throw before it would reach the classifier, so the regex branches here\n// are effectively dead for parse/format/tokenize/pattern — left in place\n// as the fallback for anything not yet on a typed throw site.\n\nexport type TemporalFmtErrorCode =\n | 'FORMAT_SYNTAX_ERROR'\n | 'UNKNOWN_TOKEN'\n | 'PARSE_MISMATCH'\n | 'INVALID_DATE'\n | 'INVALID_TIME'\n | 'INVALID_OFFSET'\n | 'INVALID_TIME_ZONE'\n | 'INVALID_CALENDAR'\n | 'AMBIGUOUS_INPUT'\n | 'INVALID_LOCALE'\n | 'INVALID_DURATION';\n\nexport interface TemporalFmtErrorFields {\n code: TemporalFmtErrorCode;\n input?: string;\n format?: string;\n token?: string;\n position?: number;\n expected?: string;\n actual?: string;\n reason?: string;\n}\n\n// Base class. `message` is the human-readable summary; the structured\n// fields are the machine-readable parts a linter or codemod reports on.\n// `Error.captureStackTrace` is called manually (where available) so\n// the stack points at the call site, not at this constructor — same\n// pattern Node uses for its own error classes.\nexport class TemporalFmtError extends Error {\n readonly code: TemporalFmtErrorCode;\n readonly input?: string;\n readonly format?: string;\n readonly token?: string;\n readonly position?: number;\n readonly expected?: string;\n readonly actual?: string;\n readonly reason?: string;\n\n constructor(message: string, fields: TemporalFmtErrorFields) {\n super(message);\n this.name = 'TemporalFmtError';\n this.code = fields.code;\n this.input = fields.input;\n this.format = fields.format;\n this.token = fields.token;\n this.position = fields.position;\n this.expected = fields.expected;\n this.actual = fields.actual;\n this.reason = fields.reason;\n // Avoid setting the stack to point at this constructor — keeps it\n // useful. captureStackTrace is V8-only; on other engines the\n // default stack (this constructor line) is what callers get.\n const capture = (Error as unknown as { captureStackTrace?: (target: Error, ctor?: Function) => void }).captureStackTrace;\n if (typeof capture === 'function') {\n capture(this, this.constructor);\n }\n }\n\n // Lets callers do `err.toJSON()` for logging. Plain `Error` doesn't\n // serialize its non-enumerable fields; this picks them up explicitly.\n toJSON(): TemporalFmtErrorFields & { name: string; message: string } {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n input: this.input,\n format: this.format,\n token: this.token,\n position: this.position,\n expected: this.expected,\n actual: this.actual,\n reason: this.reason,\n };\n }\n}\n\n// Each subclass fixes `code` so callers can switch on it without\n// re-checking message text. The constructor takes only the fields\n// that vary per call; `code` and a default `message` template are\n// provided by the subclass.\n\nexport class FormatSyntaxError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `format string \"${fields.format ?? ''}\" has a syntax error${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'FORMAT_SYNTAX_ERROR', ...rest },\n );\n this.name = 'FormatSyntaxError';\n }\n}\n\nexport class UnknownTokenError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `token \"${fields.token ?? ''}\" is not a recognized temporal-fmt token${fields.format ? ` in format string \"${fields.format}\"` : ''}.`,\n { code: 'UNKNOWN_TOKEN', ...rest },\n );\n this.name = 'UnknownTokenError';\n }\n}\n\nexport class ParseMismatchError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `input \"${fields.input ?? ''}\" does not match format \"${fields.format ?? ''}\"${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'PARSE_MISMATCH', ...rest },\n );\n this.name = 'ParseMismatchError';\n }\n}\n\nexport class InvalidDateError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `input \"${fields.input ?? ''}\" does not describe a valid date${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_DATE', ...rest },\n );\n this.name = 'InvalidDateError';\n }\n}\n\n/* c8 ignore start @preserve -- InvalidTimeError is part of the public\n error-class surface (exported from index.ts, code 'INVALID_TIME')\n but nothing in this package constructs one. Investigated wiring it\n in the same way InvalidTimeZoneError was just wired (see parse.ts's\n zzz-validation loop): checked whether hour/minute/second have a\n post-match semantic range check the way zone ids do. They don't —\n pattern.ts's regex fragments for HH/H/hh/h/mm/m/ss/s already enforce\n their valid ranges at the regex level (e.g. HH is '(?:[01]\\d|2[0-3])',\n which can't match \"99\" in the first place), so an out-of-range time\n is rejected as a plain shape mismatch before any semantic check\n could run. There's no live gap to hook this into without inventing a\n redundant check purely to give this class a body. Left unconstructed\n until the library actually has a real invalid-time case to report. */\nexport class InvalidTimeError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `input \"${fields.input ?? ''}\" does not describe a valid time${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_TIME', ...rest },\n );\n this.name = 'InvalidTimeError';\n }\n}\n/* c8 ignore stop @preserve */\n\nexport class InvalidOffsetError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `offset \"${fields.actual ?? ''}\" is invalid${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_OFFSET', ...rest },\n );\n this.name = 'InvalidOffsetError';\n }\n}\n\nexport class InvalidTimeZoneError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `time zone \"${fields.actual ?? ''}\" is not a recognized IANA time zone or fixed offset${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_TIME_ZONE', ...rest },\n );\n this.name = 'InvalidTimeZoneError';\n }\n}\n\n/* c8 ignore start @preserve -- InvalidCalendarError is part of the\n public error-class surface (exported from index.ts, code\n 'INVALID_CALENDAR') but nothing in this package constructs one.\n Checked for a wiring opportunity the same way InvalidTimeZoneError\n got one: there's no user-supplied calendar identifier anywhere in\n the library to validate against a supported list. resolveCalendar()\n in parse.ts derives the calendar entirely from Intl's own resolution\n of the locale string — it's never handed an arbitrary \"calendar\"\n value a caller could get wrong. There's no live input to reject.\n Left unconstructed until the library actually accepts a calendar\n parameter that could be invalid. */\nexport class InvalidCalendarError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `calendar \"${fields.actual ?? ''}\" is not supported${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_CALENDAR', ...rest },\n );\n this.name = 'InvalidCalendarError';\n }\n}\n/* c8 ignore stop @preserve */\n\nexport class AmbiguousInputError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `input \"${fields.input ?? ''}\" is ambiguous${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'AMBIGUOUS_INPUT', ...rest },\n );\n this.name = 'AmbiguousInputError';\n }\n}\n\nexport class InvalidLocaleError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `locale \"${fields.actual ?? ''}\" is not a valid BCP-47 tag${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_LOCALE', ...rest },\n );\n this.name = 'InvalidLocaleError';\n }\n}\n\nexport class InvalidDurationError extends TemporalFmtError {\n constructor(fields: Omit<TemporalFmtErrorFields, 'code'> & { message?: string }) {\n const { message, ...rest } = fields;\n super(\n message ?? `duration is invalid${fields.reason ? `: ${fields.reason}` : ''}.`,\n { code: 'INVALID_DURATION', ...rest },\n );\n this.name = 'InvalidDurationError';\n }\n}\n\n// Wraps a plain Error thrown from a code path that hasn't been\n// migrated to typed errors yet. Carries the original message in\n// `reason` so callers reading the typed surface still see what\n// failed. Used by safeParse() in parse.ts.\n//\n// As of the 0.9.0 migration, every throw site on the parse/format data\n// path throws a TemporalFmtError directly, so safeParse's `instanceof\n// TemporalFmtError` check always passes before this function would be\n// called — nothing in the current test suite reaches any branch below.\n// Kept as the safety net for wrapping a future unmigrated throw site\n// (see the c8-ignored call in parse.ts's safeParse), same reasoning as\n// that call site: removing this would silently drop the \"safeParse\n// always returns a TemporalFmtError\" contract the moment anyone adds a\n// throw new Error(...) without wiring a typed class for it.\n/* c8 ignore start @preserve -- unreachable from the current test suite,\n see rationale above */\nexport function wrapUntypedError(err: Error, context: { input?: string; format?: string }): TemporalFmtError {\n // Try to classify by inspecting the message — covers the existing\n // parse()/format() throw sites without modifying them. Anything\n // that doesn't match a known pattern falls through to a generic\n // ParseMismatchError, which still has the structured fields.\n const msg = err.message;\n if (/unknown token|isn't a recognized token/.test(msg)) {\n return new UnknownTokenError({ input: context.input, format: context.format, reason: msg });\n }\n if (/ambiguous/i.test(msg)) {\n return new AmbiguousInputError({ input: context.input, format: context.format, reason: msg });\n }\n if (/offset/.test(msg) && /out of range|exceeds|doesn't match the shape/i.test(msg)) {\n return new InvalidOffsetError({ input: context.input, format: context.format, reason: msg });\n }\n if (/no valid pattern matches/i.test(msg)) {\n return new ParseMismatchError({ input: context.input, format: context.format, reason: msg });\n }\n if (/doesn't describe a valid date\\/time|incomplete date|weekday token|quarter token/.test(msg)) {\n return new InvalidDateError({ input: context.input, format: context.format, reason: msg });\n }\n const lowerMsg = msg.toLowerCase();\n const mentionsLocale = lowerMsg.includes('locale');\n if (\n (mentionsLocale && (lowerMsg.includes('produced no') || lowerMsg.includes('not a valid'))) ||\n lowerMsg.includes('cutoffs must be')\n ) {\n return new InvalidLocaleError({ input: context.input, format: context.format, reason: msg });\n }\n if (/format string exceeds maximum length|input exceeds maximum length|unterminated quote|isn't a recognized token/i.test(msg)) {\n return new FormatSyntaxError({ input: context.input, format: context.format, reason: msg });\n }\n return new ParseMismatchError({ input: context.input, format: context.format, reason: msg });\n}\n/* c8 ignore stop @preserve */","// Name lists for the locale-aware tokens (MMMM, MMM, EEEE, EEE, a). Each\n// list is small and fixed (12 months, 7 weekdays, 2 day periods), so we\n// generate the real Intl strings for a locale once and cache them.\n\nimport { InvalidLocaleError } from './errors.js';\n\nexport interface LocaleVocab {\n monthLong: string[]; // index 0 = January\n monthShort: string[];\n weekdayLong: string[]; // index 0 = Monday, per Temporal's dayOfWeek numbering\n weekdayShort: string[];\n dayPeriod: string[]; // typically [AM-ish, PM-ish], deduped\n}\n\n// Custom vocabs registered by callers for locales Intl doesn't cover well\n// (e.g. a 13-month Hebrew leap year, where Intl's 12-month vocabulary\n// silently loses a whole month). Keyed by canonical cache key so the\n// same locale string spelling variants fold together — same convention\n// as the Intl-derived vocab cache above.\nconst customVocabs = new Map<string, LocaleVocab>();\nconst MAX_CUSTOM_VOCABS = 500;\nconst MAX_LOCALE_TAG_LENGTH = 256;\nconst MAX_VOCAB_ENTRY_LENGTH = 256;\n\nfunction assertValidVocab(vocab: Partial<LocaleVocab>, locale: string): void {\n // Strict shape validation at registration time, not lazily on first\n // use — the README's promise is that a malformed registration throws\n // descriptively here, rather than failing later inside format()/parse()\n // with a confusing \"no month part\" or wrong-month error the caller\n // can't trace back to the bad registration.\n const required: Array<{ key: keyof LocaleVocab; length: number; label: string }> = [\n { key: 'monthLong', length: 12, label: 'long month names' },\n { key: 'monthShort', length: 12, label: 'short month names' },\n { key: 'weekdayLong', length: 7, label: 'long weekday names' },\n { key: 'weekdayShort', length: 7, label: 'short weekday names' },\n { key: 'dayPeriod', length: 2, label: 'day period markers (AM/PM-equivalent)' },\n ];\n\n for (const { key, length, label } of required) {\n const value = vocab[key];\n if (value === undefined) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\" is missing required field \"${key}\" (${label}).`\n );\n }\n if (!Array.isArray(value)) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}\" must be an array, got ${typeof value}.`\n );\n }\n if (value.length !== length) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}\" must have exactly ${length} entries (got ${value.length}) — ${label}.`\n );\n }\n value.forEach((entry, i) => {\n if (typeof entry !== 'string' || entry.length === 0) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}[${i}]\" must be a non-empty string, got ${String(entry)}.`\n );\n }\n if (entry.length > MAX_VOCAB_ENTRY_LENGTH) {\n throw new RangeError(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}[${i}]\" is too long (maximum ${MAX_VOCAB_ENTRY_LENGTH} characters).`\n );\n }\n });\n }\n\n // Reuse the same collision check the Intl-derived path uses — a\n // duplicate month name is just as ambiguous when supplied by a caller\n // as when produced by Intl.\n assertNoCollision(vocab.monthLong!, 'MMMM month', locale);\n assertNoCollision(vocab.monthShort!, 'MMM month', locale);\n assertNoCollision(vocab.weekdayLong!, 'EEEE weekday', locale);\n assertNoCollision(vocab.weekdayShort!, 'EEE weekday', locale);\n\n // dayPeriod entries must differ from each other, or parse()'s\n // isPM check (raw === vocab.dayPeriod[1]) can never return true and\n // every 12-hour parse silently resolves to AM. The Intl-derived path\n // dedupes a same-AM/PM collision to length 1, but a caller passing\n // both entries identical is a real bug to surface — not something to\n // dedupe around.\n if (vocab.dayPeriod![0] === vocab.dayPeriod![1]) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": dayPeriod entries must differ ` +\n `(both are \"${vocab.dayPeriod![0]}\"); otherwise parse() can't tell AM from PM.`\n );\n }\n}\n\n// Anything that caches a result derived from *which* vocabulary is\n// active for a locale (right now: parse.ts's compiled pattern cache,\n// whose MMMM/MMM/EEEE/EEE/a fragments embed the vocab's alternations)\n// subscribes here so it gets invalidated when a registration swaps the\n// vocab — mirrors temporalProvider.ts's subscribeToTemporalChanges.\nconst onVocabChanged: Array<() => void> = [];\n\nexport function subscribeToVocabChanges(listener: () => void): void {\n onVocabChanged.push(listener);\n}\n\n/**\n * Supply a custom month/weekday/day-period vocabulary for a locale key,\n * overriding the Intl-derived vocab this library would otherwise build\n * for that key. Useful for locales Intl doesn't cover well — the README's\n * known-limitations section calls out the Hebrew leap-month gap as a\n * specific case this addresses.\n *\n * Throws descriptively on malformed input (wrong array lengths, empty\n * strings, duplicate entries, missing fields) rather than failing later\n * during format/parse.\n *\n * Registered vocab takes precedence over the Intl-derived vocab for that\n * locale key, including for already-cached entries — registering\n * invalidates the prior cache entry for that locale so the next call\n * picks up the new vocab.\n *\n * @example\n * registerLocaleVocab('en-u-ca-hebrew-leap', {\n * monthLong: ['Nisan','Iyar','Sivan','Tammuz','Av','Elul','Tishrei','Marcheshvan','Kislev','Tevet','Shevat','Adar I','Adar II'],\n * monthShort: ['Nis','Iyy','Siv','Tam','Av','Elu','Tish','Chesh','Kis','Tev','Shv','Ad1','Ad2'],\n * weekdayLong: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],\n * weekdayShort: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],\n * dayPeriod: ['AM','PM'],\n * });\n */\nexport function registerLocaleVocab(locale: string, vocab: Partial<LocaleVocab>): void {\n if (typeof locale !== 'string' || locale.length === 0) {\n throw new Error(`temporal-fmt: registerLocaleVocab requires a non-empty locale string, got ${String(locale)}.`);\n }\n if (locale.length > MAX_LOCALE_TAG_LENGTH) {\n throw new RangeError(`temporal-fmt: registerLocaleVocab locale is too long (maximum ${MAX_LOCALE_TAG_LENGTH} characters).`);\n }\n assertValidVocab(vocab, locale);\n\n const cacheKey = canonicalCacheKey(locale);\n if (!customVocabs.has(cacheKey) && customVocabs.size >= MAX_CUSTOM_VOCABS) {\n throw new RangeError(`temporal-fmt: registerLocaleVocab reached the ${MAX_CUSTOM_VOCABS}-locale limit.`);\n }\n customVocabs.set(cacheKey, {\n monthLong: [...vocab.monthLong!],\n monthShort: [...vocab.monthShort!],\n weekdayLong: [...vocab.weekdayLong!],\n weekdayShort: [...vocab.weekdayShort!],\n dayPeriod: [...vocab.dayPeriod!],\n });\n // Invalidate the Intl-derived cache entry so any prior format/parse\n // result cached for this locale is rebuilt against the new vocab. Not\n // strictly necessary (getLocaleVocab checks customVocabs first), but\n // cheap and keeps the two caches from drifting out of sync.\n vocabCache.delete(cacheKey);\n // Also invalidate downstream caches that baked the previous vocab in\n // at build time (parse.ts's pattern cache is the one that matters:\n // without this, a cached pattern would keep matching the OLD month /\n // weekday names while format() renders the new ones, so the library's\n // own format() output would fail to parse back).\n for (const listener of onVocabChanged) listener();\n}\n\n// Every locale-keyed cache in this library (this one, formatterCache in\n// tokens.ts, patternCache/calendarCache in parse.ts) used to key on the\n// exact locale string a caller passed in. Intl treats spelling variants of\n// the same locale as equivalent ('en-US' / 'en-us' / 'en_US' all resolve\n// the same way), but a plain string-keyed Map doesn't — so callers mixing\n// spellings for what's really one locale would silently fragment across\n// separate cache entries instead of sharing one, making the bounded\n// eviction limits (MAX_*_CACHE_SIZE) less effective than they look. This\n// doesn't change any cache's *correctness* (each entry is still built from\n// -- and valid for -- whatever locale string produced it), only how many\n// distinct entries equivalent spellings end up costing. Falls back to the\n// original string on a malformed/unrecognized tag rather than throwing —\n// cache-key normalization shouldn't be where a bad locale first surfaces\n// as an error; whatever actually calls `new Intl.DateTimeFormat(locale)`\n// downstream is the right place for that.\n// Intl constructors (DateTimeFormat/NumberFormat/RelativeTimeFormat)\n// reject underscore-separated tags like 'en_US' outright, while\n// canonicalCacheKey and every locale-parsing path in this library\n// tolerates them by normalizing to BCP-47 hyphens. Centralize that\n// normalization so every `new Intl.*(locale)` construction site\n// accepts the same spellings the cache keys do. Genuinely malformed\n// tags still throw downstream, unchanged.\nexport function normalizeLocaleTag(locale: string): string {\n return locale.replace(/_/g, '-');\n}\n\n// Memoized so hot paths (parse()'s resolveCalendar keys off this on\n// every call, and every locale-keyed cache re-derives it) don't build a\n// fresh Intl.Locale per invocation — construction is comparatively\n// expensive. Bounded like every other cache in this library.\nconst canonicalKeyCache = new Map<string, string>();\nconst MAX_CANONICAL_KEY_CACHE = 500;\n\nexport function canonicalCacheKey(locale: string): string {\n const hit = canonicalKeyCache.get(locale);\n if (hit !== undefined) return hit;\n let key: string;\n try {\n // Intl.Locale requires BCP-47 hyphens and rejects underscore-separated\n // tags like 'en_US' outright (RangeError), rather than normalizing\n // them — so without this replace, that spelling would just fall\n // through to the catch below and never fold with 'en-US'.\n key = new Intl.Locale(locale.replace(/_/g, '-')).toString().toLowerCase();\n } catch {\n // Malformed tag: key on the raw string. Callers that must reject\n // malformed tags do it via assertValidLocaleTag() before/instead of\n // relying on this function — cache-key normalization isn't where a\n // bad locale should surface as an error (unchanged behavior).\n key = locale;\n }\n if (canonicalKeyCache.size >= MAX_CANONICAL_KEY_CACHE) {\n const oldestKey = canonicalKeyCache.keys().next().value;\n if (oldestKey !== undefined) canonicalKeyCache.delete(oldestKey);\n }\n canonicalKeyCache.set(locale, key);\n return key;\n}\n\n// Single validation choke point for locale tags at public boundaries.\n// Intl constructors reject malformed tags with a bare engine RangeError\n// (\"Incorrect locale information provided\") that carries none of the\n// library's structured error context; this rethrows as the typed\n// InvalidLocaleError with the offending tag in its fields. Accepts the\n// same spellings as canonicalCacheKey (underscore tags normalized).\nexport function assertValidLocaleTag(locale: string): void {\n try {\n new Intl.Locale(normalizeLocaleTag(locale));\n } catch {\n throw new InvalidLocaleError({\n actual: locale,\n reason: 'not a valid BCP-47 locale tag',\n });\n }\n}\n\nconst vocabCache = new Map<string, LocaleVocab>();\nconst MAX_VOCAB_CACHE_SIZE = 500;\n\n// Some locales (ja-JP) split a field across two parts — month \"8\" plus a\n// counter suffix \"月\" as a separate sibling \"literal\" — while format()'s\n// tokens go through toLocaleString(), which concatenates everything into\n// \"8月\". Reading only the type-tagged part used to drop that suffix, so\n// this locale's vocab never matched what format() actually produced.\n// Only merges *adjacent* literals, not the whole string, since the\n// dayPeriod/weekday formatters below carry an extra hour part that a\n// join-everything approach would wrongly absorb.\nfunction partValue(formatter: Intl.DateTimeFormat, date: Date, type: Intl.DateTimeFormatPartTypes): string {\n const parts = formatter.formatToParts(date);\n const index = parts.findIndex((p) => p.type === type);\n /* c8 ignore start @preserve -- defensive guard against a real but\n unreproducible failure mode: an Intl implementation that omits the\n requested part type entirely for some locale. Checked every locale\n with unusual dayPeriod/weekday/month rendering available in this\n runtime's ICU data (ja-JP, zh-CN, th-TH, he-IL, ar-SA, ko-KR, fa-IR)\n against the exact formatter options getLocaleVocab uses (notably\n hour12: true for the dayPeriod formatter, which is what makes every\n locale here actually emit a dayPeriod part — omitting it is what\n produced a false \"gap\" during investigation). None omit their part\n on this runtime. A different ICU version or a non-Node Intl\n implementation could plausibly behave differently, so this stays a\n real check rather than an assertion. */\n /* c8 ignore start @preserve */\n if (index === -1) {\n throw new InvalidLocaleError({\n message: `temporal-fmt: locale produced no \"${type}\" part while building match vocabulary.`,\n });\n }\n /* c8 ignore stop @preserve */\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n // skip whitespace literals (the separator before \"AM\") — only a\n // no-space suffix like ja-JP's \"月\" should get folded in\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Two entries rendering identically means parse()'s reverse lookup\n// (indexOf) can never tell them apart. Weekday collisions already surface\n// via parse()'s dayOfWeek cross-check, but with a confusing same-string\n// error; months have no equivalent cross-check, so a collision there would\n// otherwise resolve silently to the wrong month. Catching both here, once\n// at build time, gives one clear error instead.\nfunction assertNoCollision(names: string[], label: string, locale: string): void {\n const seen = new Map<string, number>();\n for (let i = 0; i < names.length; i++) {\n const prior = seen.get(names[i]!);\n if (prior !== undefined) {\n // Not migrated to a typed error: this function is shared between\n // getLocaleVocab's Intl-derived path (data-path error, would be a\n // good InvalidLocaleError candidate) and assertValidVocab's\n // registration-time check (out of scope for this pass — see the\n // localeVocab.ts registration-error follow-up). Splitting this into\n // two near-duplicate functions just to route error types\n // differently isn't worth it for one throw; revisit together with\n // the registration-error work instead.\n throw new Error(\n `temporal-fmt: locale \"${locale}\" renders ${label} index ${prior} and ${i} identically ` +\n `(\"${names[i]}\"). parse() can't reliably tell these apart for this locale/token, so this ` +\n `combination isn't supported.`\n );\n }\n seen.set(names[i]!, i);\n }\n}\n\n// Exposed for tokens.ts: when a custom vocab is registered for this\n// locale, format()'s locale-aware tokens (MMMM/MMM/EEEE/EEE/a) read\n// straight from the registered array instead of going through\n// Intl.DateTimeFormat. Without this override, format() would silently\n// keep producing Intl's strings while parse() matched against the\n// registered vocab — the two would round-trip-fail.\nexport function getCustomVocab(locale: string): LocaleVocab | undefined {\n const cacheKey = canonicalCacheKey(locale);\n return customVocabs.get(cacheKey);\n}\n\nexport function getLocaleVocab(locale: string): LocaleVocab {\n // Validate before building vocab: a malformed tag used to surface as a\n // raw RangeError from the first new Intl.DateTimeFormat below.\n assertValidLocaleTag(locale);\n const cacheKey = canonicalCacheKey(locale);\n // Registered vocabs take precedence over the Intl-derived one — this\n // is the override mechanism registerLocaleVocab() promises. Checking\n // here, before the Intl cache lookup, means a registration that\n // happens *after* the first Intl-derived vocab was built still takes\n // effect on the next call.\n const custom = customVocabs.get(cacheKey);\n if (custom) {\n return custom;\n }\n const cached = vocabCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const intlLocale = normalizeLocaleTag(locale);\n const monthLongFmt = new Intl.DateTimeFormat(intlLocale, { month: 'long', timeZone: 'UTC' });\n const monthShortFmt = new Intl.DateTimeFormat(intlLocale, { month: 'short', timeZone: 'UTC' });\n const monthLong: string[] = [];\n const monthShort: string[] = [];\n for (let m = 0; m < 12; m++) {\n const date = new Date(Date.UTC(2020, m, 1));\n monthLong.push(partValue(monthLongFmt, date, 'month'));\n monthShort.push(partValue(monthShortFmt, date, 'month'));\n }\n assertNoCollision(monthLong, 'MMMM month', locale);\n assertNoCollision(monthShort, 'MMM month', locale);\n\n const weekdayLongFmt = new Intl.DateTimeFormat(intlLocale, { weekday: 'long', timeZone: 'UTC' });\n const weekdayShortFmt = new Intl.DateTimeFormat(intlLocale, { weekday: 'short', timeZone: 'UTC' });\n const weekdayLong: string[] = [];\n const weekdayShort: string[] = [];\n // 2024-01-01 is a Monday (UTC) — walk 7 days from there for weekday names\n for (let d = 0; d < 7; d++) {\n const date = new Date(Date.UTC(2024, 0, 1 + d));\n weekdayLong.push(partValue(weekdayLongFmt, date, 'weekday'));\n weekdayShort.push(partValue(weekdayShortFmt, date, 'weekday'));\n }\n // redundant with parse()'s dayOfWeek cross-check, but gives a clearer error\n assertNoCollision(weekdayLong, 'EEEE weekday', locale);\n assertNoCollision(weekdayShort, 'EEE weekday', locale);\n\n const dayPeriodFmt = new Intl.DateTimeFormat(intlLocale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const am = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 1)), 'dayPeriod');\n const pm = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 13)), 'dayPeriod');\n const dayPeriod = [...new Set([am, pm])];\n\n const vocab: LocaleVocab = { monthLong, monthShort, weekdayLong, weekdayShort, dayPeriod };\n if (vocabCache.size >= MAX_VOCAB_CACHE_SIZE) {\n const oldestKey = vocabCache.keys().next().value;\n if (oldestKey !== undefined) vocabCache.delete(oldestKey);\n }\n vocabCache.set(cacheKey, vocab);\n return vocab;\n}"],"mappings":"AA+DO,IAAMA,EAAN,cAA+B,KAAM,CACjC,KACA,MACA,OACA,MACA,SACA,SACA,OACA,OAET,YAAYC,EAAiBC,EAAgC,CAC3D,MAAMD,CAAO,EACb,KAAK,KAAO,mBACZ,KAAK,KAAOC,EAAO,KACnB,KAAK,MAAQA,EAAO,MACpB,KAAK,OAASA,EAAO,OACrB,KAAK,MAAQA,EAAO,MACpB,KAAK,SAAWA,EAAO,SACvB,KAAK,SAAWA,EAAO,SACvB,KAAK,OAASA,EAAO,OACrB,KAAK,OAASA,EAAO,OAIrB,IAAMC,EAAW,MAAsF,kBACnG,OAAOA,GAAY,YACrBA,EAAQ,KAAM,KAAK,WAAW,CAElC,CAIA,QAAqE,CACnE,MAAO,CACL,KAAM,KAAK,KACX,QAAS,KAAK,QACd,KAAM,KAAK,KACX,MAAO,KAAK,MACZ,OAAQ,KAAK,OACb,MAAO,KAAK,MACZ,SAAU,KAAK,SACf,SAAU,KAAK,SACf,OAAQ,KAAK,OACb,OAAQ,KAAK,MACf,CACF,CACF,EAOaC,EAAN,cAAgCJ,CAAiB,CACtD,YAAYE,EAAqE,CAC/E,GAAM,CAAE,QAAAD,EAAS,GAAGI,CAAK,EAAIH,EAC7B,MACED,GAAW,kBAAkBC,EAAO,QAAU,EAAE,uBAAuBA,EAAO,OAAS,KAAKA,EAAO,MAAM,GAAK,EAAE,IAChH,CAAE,KAAM,sBAAuB,GAAGG,CAAK,CACzC,EACA,KAAK,KAAO,mBACd,CACF,EAEaC,EAAN,cAAgCN,CAAiB,CACtD,YAAYE,EAAqE,CAC/E,GAAM,CAAE,QAAAD,EAAS,GAAGI,CAAK,EAAIH,EAC7B,MACED,GAAW,UAAUC,EAAO,OAAS,EAAE,2CA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GAAIvC,EAAW,MAAQQ,EAAsB,CAC3C,IAAMH,EAAYL,EAAW,KAAK,EAAE,KAAK,EAAE,MACvCK,IAAc,QAAWL,EAAW,OAAOK,CAAS,CAC1D,CACA,OAAAL,EAAW,IAAIF,EAAUd,CAAK,EACvBA,CACT","names":["TemporalFmtError","message","fields","capture","FormatSyntaxError","rest","UnknownTokenError","ParseMismatchError","InvalidDateError","InvalidTimeError","InvalidOffsetError","InvalidTimeZoneError","InvalidCalendarError","AmbiguousInputError","InvalidLocaleError","InvalidDurationError","wrapUntypedError","err","context","msg","lowerMsg","customVocabs","MAX_CUSTOM_VOCABS","MAX_LOCALE_TAG_LENGTH","MAX_VOCAB_ENTRY_LENGTH","assertValidVocab","vocab","locale","required","key","length","label","value","entry","i","assertNoCollision","onVocabChanged","subscribeToVocabChanges","listener","registerLocaleVocab","cacheKey","canonicalCacheKey","vocabCache","normalizeLocaleTag","canonicalKeyCache","MAX_CANONICAL_KEY_CACHE","hit","oldestKey","assertValidLocaleTag","InvalidLocaleError","MAX_VOCAB_CACHE_SIZE","partValue","formatter","date","type","parts","index","p","prev","next","names","seen","prior","getCustomVocab","getLocaleVocab","custom","cached","intlLocale","monthLongFmt","monthShortFmt","monthLong","monthShort","m","weekdayLongFmt","weekdayShortFmt","weekdayLong","weekdayShort","d","dayPeriodFmt","am","pm","dayPeriod"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as I,c as L}from"./chunk-3MZLTVP3.js";import{k as x,p as X,q as b,s}from"./chunk-5U5WJ465.js";import{b as p,c as w}from"./chunk-C6ZZ62ET.js";function r(e,t){let n=e<0,o=String(Math.abs(e)).padStart(t,"0");return n?"-"+o:o}r.fraction=function(t,n){let o=t.millisecond*1e6+(t.microsecond??0)*1e3+(t.nanosecond??0);return r(o,9).slice(0,n)};var G="en-US",l=new Map,P=500;function E(e,t){let n=JSON.stringify([b(e),t]),o=l.get(n);if(o)return o;if(l.size>=P){let a=l.keys().next().value;a!==void 0&&l.delete(a)}try{o=new Intl.DateTimeFormat(X(e),t)}catch(a){throw new x({actual:e,reason:a.message})}return l.set(n,o),o}var y;I(()=>{y=void 0});function M(){if(y===void 0){y=!1;try{let e=L();new Intl.DateTimeFormat("en-US",{day:"numeric"}).formatToParts(e.PlainDate.from({year:1970,month:1,day:1})),y=!0}catch{}}return y}function h(e,t,n,o){let a=e?.calendarId,i={...n,calendar:a&&a!=="iso8601"?a:"gregory"},d=e.toLocaleString;if(typeof d!="function"||d===Object.prototype.toLocaleString)throw new Error(`temporal-fmt: locale-aware part "${o}" needs a value that implements toLocaleString (a real Temporal object). A plain field bag cannot render locale-aware names \u2014 pass a Temporal.PlainDate/PlainDateTime/ZonedDateTime.`);if(!M())try{return d.call(e,X(t),i)}catch(u){throw u instanceof RangeError?new x({actual:t,reason:u.message}):u}let{toInstant:F,timeZoneId:D}=e,O=typeof F=="function"&&typeof D=="string",Z=O?e.toInstant():e,$={...i,...O?{timeZone:D}:{}},g=E(t,$).formatToParts(Z),S=g.findIndex(u=>u.type===o);if(S===-1)throw new Error(`temporal-fmt: locale "${t}" produced no "${o}" part for this token. This usually means the Temporal object is missing the field the token needs.`);let f=g[S].value,k=g[S-1],T=g[S+1];return k?.type==="literal"&&!/\s/.test(k.value)&&(f=k.value+f),T?.type==="literal"&&!/\s/.test(T.value)&&(f=f+T.value),f}function W(e,t){let n=s(t);if(n)return e<12?n.dayPeriod[0]:n.dayPeriod[1];let o=new Date(Date.UTC(1970,0,1,e)),i=E(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(o).find(d=>d.type==="dayPeriod");if(!i)throw new Error(`temporal-fmt: locale "${t}" produced no "dayPeriod" part for token "a".`);return i.value}function m(e,t,n,o,a,i){return a&&i!==void 0&&i>=0&&i<a.length?a[i]:h(e,t,n,o)}function c(e,t){if(e==="+00:00"&&(t==="X"||t==="XX"||t==="XXX"))return"Z";if(e.length>6){if(t==="xxx")return e;throw new Error(`temporal-fmt: token "${t}" cannot represent the offset "${e}", which has a seconds component. None of the X/XX/XXX/x/xx tokens support offset seconds; use "xxx" instead, which formats the full offset unchanged.`)}let n=e[0],o=e.slice(1,3),a=e.slice(4,6);switch(t){case"X":case"x":return a==="00"?`${n}${o}`:`${n}${o}${a}`;case"XX":case"xx":return`${n}${o}${a}`;case"XXX":case"xxx":return`${n}${o}:${a}`}}var H=[["yyyy",e=>r(e.year,4),"year"],["yy",e=>{if(e.year<0)throw new Error(`temporal-fmt: token "yy" doesn't support negative years (got ${e.year}), since truncating to 2 digits would make it indistinguishable from a positive year. Use "yyyy" instead.`);return r(e.year%100,2)},"year"],["y",e=>r(e.year,0),"year"],["MMMM",(e,t)=>{let n=s(t);return m(e,t,{month:"long"},"month",n?.monthLong,e.month-1)},"month"],["MMM",(e,t)=>{let n=s(t);return m(e,t,{month:"short"},"month",n?.monthShort,e.month-1)},"month"],["MM",e=>r(e.month,2),"month"],["M",e=>String(e.month),"month"],["dd",e=>r(e.day,2),"day"],["d",e=>String(e.day),"day"],["EEEE",(e,t)=>{let n=s(t);return m(e,t,{weekday:"long"},"weekday",n?.weekdayLong,e.dayOfWeek-1)},"dayOfWeek"],["EEE",(e,t)=>{let n=s(t);return m(e,t,{weekday:"short"},"weekday",n?.weekdayShort,e.dayOfWeek-1)},"dayOfWeek"],["HH",e=>r(e.hour,2),"hour"],["H",e=>String(e.hour),"hour"],["hh",e=>r(e.hour%12||12,2),"hour"],["h",e=>String(e.hour%12||12),"hour"],["mm",e=>r(e.minute,2),"minute"],["m",e=>String(e.minute),"minute"],["ss",e=>r(e.second,2),"second"],["s",e=>String(e.second),"second"],["SSSSSSSSS",e=>r.fraction(e,9),"millisecond"],["SSSSSSSS",e=>r.fraction(e,8),"millisecond"],["SSSSSSS",e=>r.fraction(e,7),"millisecond"],["SSSSSS",e=>r.fraction(e,6),"millisecond"],["SSSSS",e=>r.fraction(e,5),"millisecond"],["SSSS",e=>r.fraction(e,4),"millisecond"],["SSS",e=>r.fraction(e,3),"millisecond"],["SS",e=>r.fraction(e,2),"millisecond"],["S",e=>r.fraction(e,1),"millisecond"],["a",(e,t)=>W(e.hour,t),"hour"],["zzz",e=>e.timeZoneId,"timeZoneId"],["xxx",e=>c(e.offset,"xxx"),"offset"],["xx",e=>c(e.offset,"xx"),"offset"],["X",e=>c(e.offset,"X"),"offset"],["XX",e=>c(e.offset,"XX"),"offset"],["XXX",e=>c(e.offset,"XXX"),"offset"],["x",e=>c(e.offset,"x"),"offset"],["do",e=>{let t=e.day,n=t%10,o=t%100;return o>=11&&o<=13?t+"th":n===1?t+"st":n===2?t+"nd":n===3?t+"rd":t+"th"},"day"],["Q",e=>String(Math.ceil(e.month/3)),"month"],["QQQ",e=>"Q"+Math.ceil(e.month/3),"month"],["ww",e=>{let{week:t}=w(e.year,e.month,e.day,e.dayOfWeek);return r(t,2)},"dayOfWeek"],["RRRR",e=>{let{isoYear:t}=w(e.year,e.month,e.day,e.dayOfWeek);return r(t,4)},"dayOfWeek"],["D",e=>String(p(e.year,e.month,e.day)),"day"],["DD",e=>r(p(e.year,e.month,e.day),2),"day"],["DDD",e=>r(p(e.year,e.month,e.day),3),"day"],["LLLL",(e,t)=>{let n=s(t);return m(e,t,{month:"long"},"month",n?.monthLong,e.month-1)},"month"],["LLL",(e,t)=>{let n=s(t);return m(e,t,{month:"short"},"month",n?.monthShort,e.month-1)},"month"],["cccc",(e,t)=>{let n=s(t);return m(e,t,{weekday:"long"},"weekday",n?.weekdayLong,e.dayOfWeek-1)},"dayOfWeek"],["ccc",(e,t)=>{let n=s(t);return m(e,t,{weekday:"short"},"weekday",n?.weekdayShort,e.dayOfWeek-1)},"dayOfWeek"],["GGGG",(e,t)=>h(e,t,{era:"long"},"era"),"year"],["G",(e,t)=>h(e,t,{era:"short"},"era"),"year"],["zzzz",(e,t)=>h(e,t,{timeZoneName:"longGeneric"},"timeZoneName"),"timeZoneId"],["z",(e,t)=>h(e,t,{timeZoneName:"short"},"timeZoneName"),"timeZoneId"]];export{G as a,H as b};
|
|
2
|
+
//# sourceMappingURL=chunk-GMGZZG6I.js.map
|