UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

894 lines (892 loc) • 32.2 kB
import { Temporal } from "./temporal.js"; import { computationCalendarId, computationYearBias } from "./calendarSystemIds.js"; import { isRangeHandled } from "./rangeHooks.js"; import { digitRuns, digitsOf, referenceFor, withoutYear } from "./weekYearText.js"; // src/internal/weekYearRange.ts const ANY_DIGIT = /\p{Nd}/u; const MINUS = /* @__PURE__ */ new Set([ "-", "−", "‐", "‑", "‒", "–", "﹣", "-" ]); const BIDI = /* @__PURE__ */ new Set([ "‎", "‏", "؜" ]); const RELATED = /* @__PURE__ */ new Set(["chinese", "dangi"]); const MAX_ENVS = 64; /** The most moments one environment keeps per kind; they are the caller's, so the map starts again. */ const MAX_MOMENTS = 1024; let envs = /* @__PURE__ */ new Map(); let verdicts = /* @__PURE__ */ new WeakMap(); /** Forget every verdict and environment (a replaced `Intl`, a test seam). */ function forgetWeekYearRange() { envs = /* @__PURE__ */ new Map(); verdicts = /* @__PURE__ */ new WeakMap(); } /** `map.set`, emptying the map first once it holds `MAX_MOMENTS` entries. */ function remember(map, key, value) { if (map.size >= 1024) map.clear(); map.set(key, value); } /** The text a negative number carries before its digits, as ECMA-402 FormatNumeric prints it. */ function negativePrefix(locale, numberingSystem) { const text = new Intl.NumberFormat(locale, { numberingSystem, useGrouping: false }).format(-1); return text.slice(0, text.search(ANY_DIGIT)); } /** The first day of the week of a locale (1 = Monday), when the engine says. */ function firstDayOf(locale) { try { const intlLocale = new Intl.Locale(locale); return (typeof intlLocale.getWeekInfo === "function" ? intlLocale.getWeekInfo() : intlLocale.weekInfo)?.firstDay; } catch { return; } } function envOf(formatter) { const resolved = formatter.resolvedOptions(); const weekday = resolved.weekday !== void 0 || resolved.dateStyle !== void 0; const key = `${resolved.locale}|${resolved.calendar}|${resolved.numberingSystem}|${resolved.timeZone}|${weekday}`; const known = envs.get(key); if (known !== void 0) return known; const { calendar, numberingSystem, timeZone } = resolved; const base = { calendar, numberingSystem, timeZone }; const digitList = digitsOf(numberingSystem); const digitValue = /* @__PURE__ */ new Map(); digitList.forEach((digit, value) => digitValue.set(digit, value)); const env = { weekday, calendar, temporalCalendar: computationCalendarId(calendar), yearBias: computationYearBias(calendar), timeZone, numberingSystem, digits: new Set(digitList), digitValue, zero: digitList[0] ?? "0", reference: referenceFor(calendar, numberingSystem, timeZone).format, eraFormat: new Intl.DateTimeFormat("und", { ...base, era: "short", year: "numeric" }), monthDayFormat: new Intl.DateTimeFormat("und", { ...base, month: "numeric", day: "numeric" }), monthDay: /* @__PURE__ */ new Map(), eras: /* @__PURE__ */ new Map(), years: /* @__PURE__ */ new Map(), minusSign: negativePrefix(resolved.locale, numberingSystem), referenceMinus: negativePrefix("und", numberingSystem), firstDay: firstDayOf(resolved.locale) }; if (envs.size >= MAX_ENVS) envs.clear(); envs.set(key, env); return env; } /** The value of one digit character: its place in the numbering system, else in its Unicode block. */ function digitValueOf(character, env) { const known = env.digitValue.get(character); if (known !== void 0) return known; const codePoint = character.codePointAt(0) ?? 0; let steps = 0; while (steps < 10 && ANY_DIGIT.test(String.fromCodePoint(codePoint - steps - 1))) steps++; return steps % 10; } function runsOf(text, env) { return digitRuns(text, env.digits).map((run) => { const characters = [...run.text]; return { ...run, count: characters.length, value: characters.reduce((sum, character) => sum * 10 + digitValueOf(character, env), 0) }; }); } const isSignish = (character) => MINUS.has(character) || BIDI.has(character); /** How many copies of the minus text `minus` end at position `at`. */ function zoneCount(text, at, minus) { let count = 0; while (minus.length > 0 && at - minus.length * (count + 1) >= 0 && text.slice(at - minus.length * (count + 1), at - minus.length * count) === minus) count++; return count; } const range = (formatter, start, end) => formatter.formatRange(start, end); function monthDayText(ms, env) { let text = env.monthDay.get(ms); if (text === void 0) { text = env.monthDayFormat.format(ms); remember(env.monthDay, ms, text); } return text; } function eraText(ms, env) { let text = env.eras.get(ms); if (text === void 0) { text = env.eraFormat.format(ms); remember(env.eras, ms, text); } return text; } /** * The era in an era-and-year text: the year and any sign removed. A digit inside a word stays, as * it is part of the era's name (UTS #35 Part 4 §8, `G`), so the placeholder eras `ERA0` and `ERA1` * that ICU data without coptic or ethiopic era names prints are two eras, not one. */ const maskEra = (text, env) => [...withoutYear(text, env.digits)].filter((c) => !isSignish(c)).join(""); /** ICU's calendar year at `ms`, the source the single repair uses. */ function refYear(ms, env) { let year = env.years.get(ms); if (year === void 0) { const text = env.reference.format(ms); const run = runsOf(text, env)[0]; year = run === void 0 ? { digits: "", count: 0, value: 0, negative: false } : { digits: run.text, count: run.count, value: run.value, negative: zoneCount(text, run.start, env.referenceMinus) > 0 }; remember(env.years, ms, year); } return year; } const zonedOf = (ms, env) => Temporal.Instant.fromEpochMilliseconds(ms).toZonedDateTimeISO(env.timeZone).withCalendar(env.temporalCalendar); /** * Move a moment by `k` calendar years, keeping month code, day and wall time. `exact` (used to * locate year runs) also keeps the weekday and ICU's own month and day, so only year fields can * change; the loose form (used to read a pattern's literals) keeps only the time. */ function computeShift(ms, k, env, exact, keepWeekday) { const zoned = zonedOf(ms, env); let moved; try { moved = zoned.with({ year: zoned.year + k, monthCode: zoned.monthCode, day: zoned.day }, { overflow: exact ? "reject" : "constrain", disambiguation: "compatible", offset: "ignore" }); } catch { return null; } if (moved.hour !== zoned.hour || moved.minute !== zoned.minute || moved.second !== zoned.second || moved.millisecond !== zoned.millisecond) return null; if (!exact) return moved.epochMilliseconds; const want = monthDayText(ms, env); for (const adjust of [ 0, -1, 1, -2, 2 ]) { const candidate = adjust === 0 ? moved : moved.add({ days: adjust }); if (keepWeekday && candidate.dayOfWeek !== zoned.dayOfWeek) continue; if (monthDayText(candidate.epochMilliseconds, env) === want) return candidate.epochMilliseconds; } return null; } /** `computeShift` answers, kept per environment: they depend on its calendar and zone only. */ const shiftCache = /* @__PURE__ */ new WeakMap(); /** `computeShift`, remembered: every formatter of an environment probes the same moments. */ function shiftYears(ms, k, env, exact, keepWeekday) { let byKey = shiftCache.get(env); if (byKey === void 0) { byKey = /* @__PURE__ */ new Map(); shiftCache.set(env, byKey); } const key = `${ms}|${k}|${exact}|${keepWeekday}`; const known = byKey.get(key); if (known !== void 0 || byKey.has(key)) return known ?? null; const moved = computeShift(ms, k, env, exact, keepWeekday); remember(byKey, key, moved); return moved; } const K_ORDER = [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 60, 120, 180, 240, 360, 420, 480, 540, 660, 720, 780, 840, 960, 1020, 1080, 1140, 1260, 1320, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 ]; const kCandidates = (direction) => [...K_ORDER.map((k) => direction * k), ...K_ORDER.map((k) => -direction * k)]; /** A year in the calendar and in ISO 8601 at `ms`. */ function yearsOf(ms, env) { const zoned = zonedOf(ms, env); return { calendar: zoned.year - env.yearBias, iso: zoned.withCalendar("iso8601").year }; } /** Digit runs of one text with the placeholder `\0` in place of the runs at `indexes`. */ function masked(text, runs, indexes) { let out = ""; let position = 0; for (const index of indexes) { const run = runs[index]; if (run !== void 0) { out += text.slice(position, run.start) + "\0"; position = run.end; } } return out + text.slice(position); } function changedRuns(before, after) { const changed = []; before.forEach((run, index) => { if (run.text !== after[index]?.text) changed.push(index); }); return changed; } /** The glued form of a year in front of another numeric field (ha `yyyyMM`). */ function movedGlued(before, after, k) { const size = Math.abs(k); for (let m = 1; m <= 2 && m < Math.min(before.count, after.count); m++) { const first = [...before.text]; const second = [...after.text]; if (first.slice(-m).join("") !== second.slice(-m).join("")) continue; const shift = Math.abs(Math.floor(after.value / 10 ** m) - Math.floor(before.value / 10 ** m)); if (Math.abs(shift - size) <= 1) return true; } return false; } /** * Whether a run moved as a year under a shift of `k` years: by `k` (era years count down, a * week-year may differ by one), modulo 100 for a two-digit run, modulo 60 for a sexagenary number. */ function movedLikeYear(before, after, k, env) { if (after.value === before.value) return false; if (RELATED.has(env.calendar) && k % 60 !== 0 && before.value >= 1 && before.value <= 60 && after.value >= 1 && after.value <= 60) { const wrapped = ((after.value - before.value) % 60 + 60) % 60; if ([ k - 1, k, k + 1 ].some((want) => wrapped === (want % 60 + 60) % 60)) return true; } if (Math.abs(Math.abs(after.value - before.value) - Math.abs(k)) <= 1) return true; if (movedGlued(before, after, k)) return true; if (before.count <= 2 && after.count <= 2) { const wrapped = ((after.value - before.value) % 100 + 100) % 100; return [ k - 1, k, k + 1, -k - 1, -k, -k + 1 ].some((want) => wrapped === (want % 100 + 100) % 100); } return false; } const unlettered = (text) => text.replace(/[\p{L}\p{M}]+/gu, ""); /** * A shift by a multiple of 60 keeps a sexagenary year number, so an unchanged text there could * hide one. A small shift changes it: when the digit runs all stay the same under one (letters, * such as a year name or weekday, may change), no digit run depends on the year. */ function noDigitYear(formatter, before, env, reshift) { for (let k = 2; k <= 12; k++) { const pair = reshift(k); if (pair === null) continue; const after = runsOf(range(formatter, pair[0], pair[1]), env); if (after.length !== before.length) continue; return changedRuns(before, after).length === 0; } return false; } /** * One shifted trial: same run count, same text outside the runs that changed, and every run that * changed moved like a year. */ function trial(formatter, original, start, end, env, k, reshift) { const text = range(formatter, start, end); const runs = runsOf(text, env); if (runs.length !== original.runs.length) return null; const changed = changedRuns(original.runs, runs); if (changed.length === 0 && RELATED.has(env.calendar) && k % 60 === 0 && !noDigitYear(formatter, original.runs, env, reshift)) return null; if (unlettered(masked(original.text, original.runs, changed)) !== unlettered(masked(text, runs, changed))) return null; return changed.every((index) => { const before = original.runs[index]; const after = runs[index]; return before !== void 0 && after !== void 0 && movedLikeYear(before, after, k, env); }) ? { runs, changed } : null; } /** * A printed weekday must stay put under small shifts, since a weekday digit (vi "Thứ 4") moving by * up to 6 could pass for a two-digit year moved by k. Under a multiple of 60 that is not a * multiple of 100 it cannot: no rule in `movedLikeYear` accepts a change of -6..6 there. */ const keepsWeekday = (k) => k % 60 !== 0; const yearRunsOf = (found, owner, shiftedMs) => found.changed.map((index) => ({ index, owner, shiftedText: found.runs[index]?.text ?? "", shiftedMs })); /** Locate the year runs when both endpoints are in one era: both move together. */ function locateTogether(formatter, original, a, b, env, both) { const ya = yearsOf(a, env); const direction = ya.calendar <= 0 || ya.iso <= 0 ? -1 : 1; for (const k of kCandidates(direction)) { const shiftedStart = shiftYears(a, k, env, true, keepsWeekday(k)); if (shiftedStart === null) continue; const shiftedEnd = shiftYears(b, k, env, true, keepsWeekday(k)); if (shiftedEnd === null) continue; const found = trial(formatter, original, shiftedStart, shiftedEnd, env, k, both); if (found !== null) return yearRunsOf(found, "a", shiftedStart); } return null; } /** * Locate one endpoint's year runs by moving that endpoint alone, away from the other; `side` is * the direction of the move (the start goes back, the end goes forward). */ function locateAlone(formatter, original, a, b, env, owner) { const own = owner === "a" ? a : b; const other = owner === "a" ? b : a; const direction = owner === "a" ? -1 : 1; const pair = (moved) => owner === "a" ? [moved, b] : [a, moved]; for (const k of kCandidates(direction)) { const moved = shiftYears(own, k, env, true, keepsWeekday(k)); if (moved === null || eraText(moved, env) === eraText(other, env)) continue; const alone = (kk) => { const shifted = shiftYears(own, direction * kk, env, true, false); return shifted === null || eraText(shifted, env) === eraText(other, env) ? null : pair(shifted); }; const [from, to] = pair(moved); const found = trial(formatter, original, from, to, env, k, alone); if (found !== null) return { runs: yearRunsOf(found, owner, moved), changed: found.changed }; } return null; } /** The year runs of `formatRange(a, b)`, or `null` when no shift keeps the pattern. */ function locate(formatter, a, b, env, text = range(formatter, a, b)) { const runs = runsOf(text, env); const original = { text, runs }; const both = (k) => { const start = shiftYears(a, k, env, true, false); const end = shiftYears(b, k, env, true, false); return start === null || end === null ? null : [start, end]; }; const none = () => noDigitYear(formatter, runs, env, both) ? { text, runs, years: [] } : null; if (eraText(a, env) === eraText(b, env)) { const years = locateTogether(formatter, original, a, b, env, both); return years === null ? none() : { text, runs, years }; } const first = locateAlone(formatter, original, a, b, env, "a"); if (first === null) return none(); const second = locateAlone(formatter, original, a, b, env, "b"); if (second === null) return none(); if (first.changed.some((index) => second.changed.includes(index))) return none(); return { text, runs, years: [...first.runs, ...second.runs].sort((x, y) => x.index - y.index) }; } /** * Week-years lie within one of the extended or ISO year, so both >= 1 means no value below 0. */ function surelyPositive(ms, env) { const years = yearsOf(ms, env); return years.calendar >= 1 && years.iso >= 1 && !refYear(ms, env).negative; } /** * The pattern's skeleton: the punctuation between consecutive digit runs, with letters, marks, * spaces and bidi marks left out, and the minus copies before each year run (those are what is * being measured). */ function skeleton(text, runs, yearIndexes, env) { const out = []; for (let index = 1; index < runs.length; index++) { const previous = runs[index - 1]; const current = runs[index]; if (previous === void 0 || current === void 0) continue; let literal = text.slice(previous.end, current.start); if (yearIndexes.has(index)) { const copies = zoneCount(text, current.start, env.minusSign); literal = literal.slice(0, literal.length - copies * env.minusSign.length); } out.push(literal.replace(/[\p{L}\p{M}]+\.?/gu, "").replace(/[\p{Z}\s‎‏؜]+/gu, "")); } return out.join("#"); } function farRange(formatter, located, a, b, env) { const ya = yearsOf(a, env); const yb = yearsOf(b, env); const k0 = 2e3 - Math.min(ya.iso, ya.calendar, yb.iso, yb.calendar); const weekday = (ms) => zonedOf(ms, env).dayOfWeek; let pick = null; for (let k = k0; k < k0 + 400 && pick === null; k++) { const start = shiftYears(a, k, env, false, false); const end = shiftYears(b, k, env, false, false); if (start !== null && end !== null && weekday(start) === weekday(a) && weekday(end) === weekday(b)) pick = [start, end]; } if (pick === null) { const start = shiftYears(a, k0, env, false, false); const end = shiftYears(b, k0, env, false, false); if (start !== null && end !== null) pick = [start, end]; } if (pick === null || !surelyPositive(pick[0], env) || !surelyPositive(pick[1], env)) return null; const text = range(formatter, pick[0], pick[1]); const runs = runsOf(text, env); const yearIndexes = new Set(located.years.map((year) => year.index)); return runs.length === located.runs.length && skeleton(text, runs, yearIndexes, env) === skeleton(located.text, located.runs, yearIndexes, env) ? { text, runs } : null; } /** The copies of the minus text before a run that belong to the pattern, not to the number. */ function literalCount(formatter, located, year, a, b, env, cache) { const mine = located.years.filter((entry) => entry.owner === year.owner).map((entry) => entry.index); const other = located.years.filter((entry) => entry.owner !== year.owner).map((entry) => entry.index); if (mine.length === other.length && surelyPositive(year.owner === "a" ? b : a, env)) { const run = located.runs[other[mine.indexOf(year.index)] ?? -1]; return run === void 0 ? null : zoneCount(located.text, run.start, env.minusSign); } if (cache.far === void 0) cache.far = farRange(formatter, located, a, b, env); const run = cache.far?.runs[year.index]; return cache.far === null || run === void 0 ? null : zoneCount(cache.far.text, run.start, env.minusSign); } function signOf(formatter, located, year, a, b, env, cache, digitsMatch) { const run = located.runs[year.index]; if (run === void 0) return null; const minus = env.minusSign; const copies = zoneCount(located.text, run.start, minus); if (copies === 0) return { negative: false, length: 0 }; const ms = year.owner === "a" ? a : b; const ref = refYear(ms, env); if (ref.negative && run.text === ref.digits) return { negative: true, length: minus.length }; if (surelyPositive(ms, env)) return { negative: false, length: 0 }; const literal = literalCount(formatter, located, year, a, b, env, cache); if (literal !== null) { if (copies - literal === 0) return { negative: false, length: 0 }; return copies - literal === 1 ? { negative: true, length: minus.length } : null; } if (digitsMatch) return null; const window = weekYearWindow(ms, env); const positive = window.has(run.value); const negative = window.has(-run.value); if (positive === negative) return null; return negative ? { negative: true, length: minus.length } : { negative: false, length: 0 }; } /** The values a week-year can take at `ms`: within one of the extended or the ISO year. */ function weekYearWindow(ms, env) { const years = yearsOf(ms, env); return /* @__PURE__ */ new Set([ years.calendar - 1, years.calendar, years.calendar + 1, years.iso - 1, years.iso, years.iso + 1 ]); } /** The last two digits of a year's digits, padded. */ function lastTwo(digits, env) { const characters = [...digits]; return characters.length >= 2 ? characters.slice(-2).join("") : env.zero + characters.join(""); } /** * Sexagenary position of ICU's related year (chinese, dangi): year 4 CE is jia-zi, position 1. * Taken from ICU's own year, since ICU and Temporal can place a lunar new year a day apart. */ const cyclic = (ref) => ((ref.value - 4) % 60 + 60) % 60 + 1; /** Whether a year glued to another numeric field (brx `d/My`) shows `ref` in this run. */ function gluedMatch(run, ref, y, env, two) { const ref1 = refYear(y.shiftedMs, env); const forms = [[lastTwo(ref.digits, env), lastTwo(ref1.digits, env)]]; if (!two) forms.unshift([ref.digits, ref1.digits]); return forms.some(([digits, shifted]) => { if (run.text.length <= digits.length) return false; return run.text.endsWith(digits) && y.shiftedText === run.text.slice(0, run.text.length - digits.length) + shifted || run.text.startsWith(digits) && y.shiftedText === shifted + run.text.slice(digits.length); }); } /** * Whether the run holds ICU's calendar year. `two`: the formatter asked for year "2-digit", whose * output ECMA-402 FormatDateTimePattern cuts to two digits; an ICU week-year field keeps its own * width there ("1617" for "17"), which is wrong as well. */ function digitsMatch(run, ref, env, y, two) { if (run.text === ref.digits) return !(two && run.count > 2); if (run.count === 2 && run.text === lastTwo(ref.digits, env)) return true; if (y !== void 0 && gluedMatch(run, ref, y, env, two)) return true; if (RELATED.has(env.calendar)) { const position = cyclic(ref); return run.value === position || run.count === 2 && run.value === position % 100; } return false; } /** Check one range: the located year runs, and which of them do not hold the calendar year. */ function checkRange(formatter, a, b, options, env) { const located = locate(formatter, a, b, env); if (located === null) return null; const cache = {}; const wrong = []; const two = options.year === "2-digit" && !RELATED.has(env.calendar); for (const year of located.years) { const ms = year.owner === "a" ? a : b; const run = located.runs[year.index]; if (run === void 0) return null; const ref = refYear(ms, env); const matches = digitsMatch(run, ref, env, year, two); const sign = signOf(formatter, located, year, a, b, env, cache, matches); if (sign === null) return null; if (!(sign.negative === ref.negative && matches)) wrong.push({ run, sign, ref, ms }); } return { located, wrong }; } const atDate = (date, env, time = "12:00") => date.toZonedDateTime({ timeZone: env.timeZone, plainTime: time }).epochMilliseconds; /** The weekday offsets (1..6 from the first day of the week) of year starts, one date for each. */ function yearStarts(env, anchor) { const byOffset = /* @__PURE__ */ new Map(); for (let year = anchor + 1; year <= anchor + 80 && byOffset.size < 6; year++) { let first = Temporal.PlainDate.from({ calendar: env.temporalCalendar, year, monthCode: "M01", day: 1 }); for (let steps = 0; refYear(atDate(first, env), env).digits === refYear(atDate(first.subtract({ days: 1 }), env), env).digits && steps < 4; steps++) first = first.add({ days: 1 }); const offset = (first.dayOfWeek - (env.firstDay ?? 1) + 7) % 7; if (offset !== 0 && !byOffset.has(offset)) byOffset.set(offset, first); } return byOffset; } /** Which year-start offsets to probe: two just after a week start (`L`) and two just before (`H`). */ function pickedOffsets(offsets, hasFirstDay) { if (!hasFirstDay) return offsets.flatMap((o) => [`L${o}`, `H${o}`]); const unique = (keys) => [...new Set(keys)]; const low = offsets.find((o) => o >= 1); const lower = offsets.find((o) => o >= 2); const high = [...offsets].reverse().find((o) => o <= 6); const higher = [...offsets].reverse().find((o) => o <= 5); return unique([...[low, lower].flatMap((o) => o === void 0 ? [] : [`L${o}`]), ...[high, higher].flatMap((o) => o === void 0 ? [] : [`H${o}`])]); } /** The day, month, year and time ranges on one side of a year boundary. */ function sideProbes(first, side, env) { const last = first.subtract({ days: 1 }); const at = (date, time) => atDate(date, env, time); if (side === "L") return [ [at(last.subtract({ days: 1 })), at(last)], [at(last.subtract({ months: 1 })), at(last)], [at(last), at(first)], [at(last.subtract({ years: 1 })), at(last)], [at(last, "10:00"), at(last, "15:00")], [at(last, "10:00"), at(last, "10:30")] ]; return [ [at(first), at(first.add({ days: 1 }))], [at(first), at(first.add({ months: 1 }))], [at(last), at(first)], [at(first), at(first.add({ years: 1 }))], [at(first, "10:00"), at(first, "15:00")], [at(first, "10:00"), at(first, "10:30")] ]; } /** Probes in an earlier era (Temporal and ICU both see an era change), and across the era. */ function earlierEraProbes(anchor, env, picked, starts) { const here = atDate(Temporal.PlainDate.from({ calendar: env.temporalCalendar, year: anchor, monthCode: "M06", day: 1 }), env); for (const step of [ 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584 ]) { if (env.calendar.startsWith("islamic") && anchor - step < 1) continue; let earlier; try { earlier = Temporal.PlainDate.from({ calendar: env.temporalCalendar, year: anchor - step, monthCode: "M06", day: 1 }); } catch { continue; } const start = atDate(earlier, env); if (maskEra(eraText(start, env), env) === maskEra(eraText(here, env), env)) continue; const across = picked.flatMap((key) => { const first = starts.get(Number(key.slice(1))); return first === void 0 ? [] : [[start, atDate(key.startsWith("L") ? first.subtract({ days: 1 }) : first, env)]]; }); return [ [start, atDate(earlier.add({ days: 1 }), env)], [start, atDate(earlier.add({ months: 1 }), env)], [start, atDate(earlier.add({ years: 1 }), env)], [atDate(earlier, env, "10:00"), atDate(earlier, env, "15:00")], [atDate(earlier, env, "10:00"), atDate(earlier, env, "10:30")], ...across ]; } return []; } /** * The probe ranges of a calendar: year boundaries from 2024 on at weekday offsets 1 to 6 from the * locale's first day of the week, where `Y` and `y` differ, with day, month, year and time ranges * on both sides; and day, month, year, time and cross-era ranges in an earlier era. */ function computeProbes(env) { const anchor = Temporal.PlainDate.from("2024-07-01").withCalendar(env.temporalCalendar).year; const starts = yearStarts(env, anchor); const picked = pickedOffsets([...starts.keys()].sort((x, y) => x - y), env.firstDay !== void 0); return [...picked.flatMap((key) => { const first = starts.get(Number(key.slice(1))); return first === void 0 ? [] : sideProbes(first, key.startsWith("L") ? "L" : "H", env); }), ...earlierEraProbes(anchor, env, picked, starts)]; } /** The probes of an environment, built once: they depend on its calendar, zone and locale only. */ const probeCache = /* @__PURE__ */ new WeakMap(); function probes(env) { let list = probeCache.get(env); if (list === void 0) { list = computeProbes(env); probeCache.set(env, list); } return list; } /** * Whether the formatter's range pattern prints a week-based year where the calendar year is meant * (defect D24 in ranges). A digit run is a year run when it moves exactly as a year under a shift * of one or both endpoints by k years; each is compared with ICU's calendar year for its * endpoint, signed with the locale's minus, and under `year: "2-digit"` only the last two digits * (chinese and dangi print the related year at full width). A formatter whose range text holds no * decimal year is not flagged. A probe whose year runs cannot be located counts as flagged. * * Computed once per formatter, on its first range call; only `format` and `formatRange` are called. * * @param formatter the formatter whose range text is read * @param options the options it was built with * @returns `true` when its range text needs `repairRangeYear` * * @example rangeYearVerdict(new Intl.DateTimeFormat("en", { year: "numeric", month: "short" }), { year: "numeric", month: "short" }) // false * @example rangeYearVerdict(new Intl.DateTimeFormat("my-u-ca-buddhist", { year: "numeric", month: "short", day: "numeric" }), { year: "numeric", month: "short", day: "numeric" }) // true */ function rangeYearVerdict(formatter, options) { const known = verdicts.get(formatter); if (known !== void 0) return known; let flagged; try { const env = envOf(formatter); flagged = false; for (const [a, b] of probes(env)) { const checked = checkRange(formatter, a, b, options, env); if (checked === null || checked.wrong.length > 0) { flagged = true; break; } } } catch { flagged = false; } verdicts.set(formatter, flagged); return flagged; } /** How a year run is written: full, or the last two digits. */ function styleFor(run, options, env) { if (RELATED.has(env.calendar)) return run.count === 2 ? "two" : "full"; if (options.year === "2-digit") return "two"; if (options.year === "numeric") return "full"; return run.count === 2 ? "two" : "full"; } /** Whether the run holds one whole week-year value (within one of the extended or ISO year). */ function isWholeWeekYear(wrong, env) { const window = weekYearWindow(wrong.ms, env); const value = wrong.sign.negative ? -wrong.run.value : wrong.run.value; return window.has(value) || wrong.run.count === 2 && [...window].some((candidate) => candidate < 0 === wrong.sign.negative && Math.abs(candidate) % 100 === wrong.run.value); } /** Whether the polyfill can project the instant onto the formatter's calendar. */ const readable = (ms, env) => { try { return Number.isFinite(yearsOf(ms, env).calendar); } catch { return false; } }; /** * The range text with each week-based year run replaced by the endpoint's calendar year: ICU's * year, signed with the locale's minus, in the formatter's numbering system, ungrouped, at the * width printed (full, or the last two digits). Only the runs found wrong change, and every other * character is kept. * * @param formatter the formatter that prints the range * @param options the options it was built with * @param startMs the start of the range, in epoch milliseconds * @param endMs the end of the range, in epoch milliseconds * @returns the repaired text, or `null` when the year runs cannot be located or a run is not one * whole week-year value * * @example repairRangeYear(new Intl.DateTimeFormat("kok-u-ca-japanese", { year: "numeric", month: "numeric", day: "numeric", timeZone: "UTC" }), { year: "numeric", month: "numeric", day: "numeric", timeZone: "UTC" }, Date.UTC(2018, 11, 27), Date.UTC(2019, 11, 27)) // the end year is 1 (Reiwa), not 2019 */ function repairRangeYear(formatter, options, startMs, endMs) { try { const env = envOf(formatter); if (!readable(startMs, env) || !readable(endMs, env)) return formatter.formatRange(startMs, endMs); const checked = checkRange(formatter, startMs, endMs, options, env); if (checked === null) return null; if (!checked.wrong.every((wrong) => isWholeWeekYear(wrong, env))) return null; let out = checked.located.text; for (const wrong of checked.wrong.toSorted((x, y) => y.run.start - x.run.start)) { const digits = styleFor(wrong.run, options, env) === "two" ? lastTwo(wrong.ref.digits, env) : wrong.ref.digits; const sign = wrong.ref.negative ? env.minusSign : ""; out = out.slice(0, wrong.run.start - wrong.sign.length) + sign + digits + out.slice(wrong.run.end); } return out; } catch { return null; } } /** * The formatter's range text with the calendar year where the engine prints the week-year: the * one call every library `formatRange` goes through. The verdict is computed on the formatter's * first call and kept; a formatter that is not flagged answers with the engine's own text, and a * stand-in that repairs its own range is called as it is. * * @returns the text, or `null` when a flagged formatter's year runs cannot be repaired */ function formatRangeChecked(formatter, options, startMs, endMs) { if (isRangeHandled(formatter) || !rangeYearVerdict(formatter, options)) return formatter.formatRange(startMs, endMs); return repairRangeYear(formatter, options, startMs, endMs); } export { MAX_MOMENTS, forgetWeekYearRange, formatRangeChecked, rangeYearVerdict, repairRangeYear };