@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.
201 lines (199 loc) • 8.09 kB
JavaScript
import { plainOptionEntries } from "./plainOptionEntries.js";
import { DATE_KEYS, TIME_KEYS, verdictKey } from "./patternKey.js";
import { nowInstant } from "./temporalCompat/clock.js";
import { forgetRanges, markRangeHandled, rangeHooks } from "./rangeHooks.js";
import { analyse, anchorYear, checkYearRuns, dateIn, digitRuns, forgetWeekYearText, patchYearParts, referenceFor, referenceYear, repairText, yearRunIndexes } from "./weekYearText.js";
import { createNameMask, createPartsSynth } from "./weekYearSynth.js";
// src/internal/weekYearGuard.ts
/** ECMA-402 CreateDateTimeFormat reads these to decide whether to add the date defaults. */
const FIELD_KEYS = [
"weekday",
"year",
"month",
"day",
"dayPeriod",
"hour",
"minute",
"second",
"fractionalSecondDigits",
"dateStyle",
"timeStyle"
];
/** At most this many verdicts; past it the map clears. */
const MAX_VERDICTS = 256;
const verdicts = /* @__PURE__ */ new Map();
let verdictsBuiltWith;
/** Forget every verdict (the `Intl.DateTimeFormat` constructor was replaced, a test seam). */
function forgetWeekYearVerdicts() {
verdicts.clear();
verdictsBuiltWith = void 0;
forgetWeekYearText();
forgetRanges();
}
/**
* Whether the formatter can print a year at all (ECMA-402 CreateDateTimeFormat, the `needDefaults`
* step with required ~any~ and defaults ~date~: `era` is not one of the fields it checks, so
* `{ era }` alone gets year, month and day).
*/
function printsYear(options) {
return options.year !== void 0 || options.dateStyle !== void 0 || FIELD_KEYS.every((key) => options[key] === void 0);
}
/** The noon of a date in UTC, as epoch milliseconds. */
function noonUtc(date) {
return date.toZonedDateTime({
timeZone: "UTC",
plainTime: "12:00"
}).epochMilliseconds;
}
/**
* The first day of calendar year `year` as the reference (ICU's own calendar) counts it: month 1
* day 1 by Temporal, moved by at most four days until the reference's year changes there.
*/
function yearStart(reference, calendar, year) {
const at = (date) => referenceYear(reference, noonUtc(date));
const middle = at(dateIn(calendar, year, 1, 15));
let start = dateIn(calendar, year, 1, 1);
for (let step = 0; step < 4; step++) {
const previous = start.subtract({ days: 1 });
if (at(previous) !== at(start)) break;
start = at(start) === middle ? previous : start.add({ days: 1 });
}
return start;
}
/**
* Whether the year runs of a formatter hold a year other than the calendar year at a year
* boundary: read from `format` alone, on the formatter or a UTC twin.
*
* @param format the formatter's (or its twin's) `format`
*/
function isWeekYear(format, calendar, numberingSystem) {
const reference = referenceFor(calendar, numberingSystem, "UTC");
const digits = new Set(new Intl.NumberFormat("und", {
numberingSystem,
useGrouping: false
}).format(1234567890));
const runsAt = (date) => digitRuns(format(noonUtc(date)), digits);
const yearRuns = yearRunIndexes(calendar, runsAt);
if (yearRuns === null || yearRuns.length === 0) return false;
const first = anchorYear(calendar);
for (let year = first + 1; year <= first + 3; year++) {
const start = yearStart(reference, calendar, year);
const last = start.subtract({ days: 1 });
for (const [date, inside] of [[start, start.add({ days: 14 })], [last, last.subtract({ days: 14 })]]) {
const at = runsAt(date);
const mid = runsAt(inside);
if (at.length === mid.length && !checkYearRuns(yearRuns, at, mid, referenceYear(reference, noonUtc(date)), referenceYear(reference, noonUtc(inside)))) return true;
}
}
return false;
}
/** The formatter's own, or a UTC date-only twin when a time field or a zone would move digits. */
function textSource(formatter, options, resolved) {
if (resolved.timeZone === "UTC" && TIME_KEYS.every((key) => options[key] === void 0)) return formatter;
const twin = {
calendar: resolved.calendar,
numberingSystem: resolved.numberingSystem,
timeZone: "UTC"
};
for (const key of DATE_KEYS) if (options[key] !== void 0) Object.assign(twin, { [key]: options[key] });
return new Intl.DateTimeFormat(resolved.locale, twin);
}
/** Whether the text of this pattern prints a year other than the calendar year, remembered per pattern. */
function isFlagged(formatter, options, resolved) {
if (verdictsBuiltWith !== Intl.DateTimeFormat) {
verdicts.clear();
verdictsBuiltWith = Intl.DateTimeFormat;
}
const key = verdictKey(options, resolved);
const known = verdicts.get(key);
if (known !== void 0) return known;
const source = textSource(formatter, options, resolved);
const flagged = isWeekYear((ms) => source.format(ms), resolved.calendar, resolved.numberingSystem);
if (verdicts.size >= MAX_VERDICTS) verdicts.clear();
verdicts.set(key, flagged);
return flagged;
}
/** A time value as `Intl` reads it: a number, a `Date`, or `undefined` for now. */
function toMilliseconds(date) {
if (typeof date === "number") return date;
return date === void 0 ? nowInstant().epochMilliseconds : Number(date);
}
/** The formatter that stands in for a flagged one; `format` and the parts hold the calendar year. */
function guarded(native, options, resolved, crashes) {
let analysis;
const read = () => {
analysis ??= analyse((ms) => native.format(ms), resolved, createNameMask(options, resolved));
return analysis;
};
const repaired = (ms) => {
const read1 = read();
return read1 === null ? null : repairText(read1, native.format(ms), ms);
};
let synth;
const standIn = {
format(date) {
const ms = toMilliseconds(date);
return repaired(ms)?.text ?? native.format(ms);
},
formatToParts(date) {
const ms = toMilliseconds(date);
const text = repaired(ms);
if (text === null) return [];
if (!crashes && options.dateStyle === void 0) {
const patched = patchYearParts(native.formatToParts(ms), text);
if (patched !== null) return patched;
}
const known = read();
if (known === null) return [];
synth ??= createPartsSynth(options, resolved, known, repaired);
return synth(ms) ?? [];
},
formatRange(start, end) {
const a = toMilliseconds(start);
const b = toMilliseconds(end);
const hooks = rangeHooks();
return (hooks ? hooks.checked(native, options, a, b) : native.formatRange(a, b)) ?? "";
},
formatRangeToParts() {
throw new TypeError("formatRangeToParts is not available on a formatter that can print the week-year (CORE-112)");
},
resolvedOptions() {
const own = native.resolvedOptions();
const known = read();
if (own.year !== void 0 || known === null) return own;
return {
...own,
year: known.styles[0]?.kind === "two" ? "2-digit" : "numeric"
};
}
};
markRangeHandled(standIn);
return standIn;
}
/**
* The formatter itself when its pattern cannot print the week-of-year year (defects D23, D24),
* else a formatter whose year is the calendar year and whose parts never reach the engine's `Y`
* field.
*
* @param formatter the formatter just built
* @param callerOptions the options it was built with; options with a getter are left unguarded
* @returns the formatter, or its stand-in
*
* @example guardDateTimeFormat(new Intl.DateTimeFormat("en", { year: "numeric" }), { year: "numeric" }) // the same formatter
* @example guardDateTimeFormat(new Intl.DateTimeFormat("gd", { year: "numeric", month: "short", timeZone: "UTC" }), { year: "numeric", month: "short", timeZone: "UTC" }).format(Date.UTC(2024, 11, 30)) // "Dùbh 2024"
*/
function guardDateTimeFormat(formatter, callerOptions) {
const entries = plainOptionEntries(callerOptions);
if (entries === null) return formatter;
const options = Object.fromEntries(entries);
if (!printsYear(options)) return formatter;
try {
const resolved = formatter.resolvedOptions();
const crashes = options.dateStyle === void 0 && resolved.year === void 0 && resolved.calendar !== "chinese" && resolved.calendar !== "dangi";
if (!crashes && !isFlagged(formatter, options, resolved)) return formatter;
return guarded(formatter, options, resolved, crashes);
} catch {
return formatter;
}
}
export { forgetWeekYearVerdicts, guardDateTimeFormat };