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.

216 lines (214 loc) • 10.2 kB
import { isIslamicCalendarResolutionCompatNeeded } from "./temporalCompat/capabilities.js"; import { plainOptionEntries } from "./plainOptionEntries.js"; import { canonicalLocaleTags } from "./resolveLocale.js"; import { forgetWeekYearVerdicts, guardDateTimeFormat } from "./weekYearGuard.js"; import { repairYearPrinting, widenRelatedYear } from "./yearPrinting.js"; import { repairCopticEra } from "./copticEra.js"; import { repairIslamicEpochEra } from "./islamicEpochEra.js"; import { refuseLunisolarDate } from "./lunisolarRefusal.js"; import { repairEraYearNumerals } from "./japaneseNumerals.js"; // src/internal/formatterCache.ts /** At most this many formatters (or checked argument sets) per kind; past it the kind's map clears. */ const MAX_ENTRIES_PER_KIND = 256; const formatters = /* @__PURE__ */ new Map(); const checked = /* @__PURE__ */ new Map(); /** The `Intl[kind]` constructor each kind's entries were built with. */ const builtWith = /* @__PURE__ */ new Map(); /** * Forget a kind's formatters and checked argument sets when `Intl[kind]` is no longer the * constructor they were built with (a polyfill loaded later, a test stub), so every answer comes * from the constructor installed now. */ function forgetIfReplaced(kind) { const current = Intl[kind]; if (builtWith.get(kind) !== current) { formatters.delete(kind); checked.delete(kind); builtWith.set(kind, current); } } /** The options to build with: widened (D28) when the formatter's calendar is chinese or dangi. */ function widened(native, options) { try { return widenRelatedYear(options, native.resolvedOptions().calendar); } catch { return options; } } /** * A date formatter with the week-year guard (D23, D24) and no year repair (D25 to D27, but for the era-year numerals under the guard): its parts * are the engine's own, as a caller that reads the engine's era needs them (D18, `islamicEra.ts`). * Not cached; the caller keeps it. * * @param locale BCP 47 locale * @param options the formatter's options, built by GMT code * @returns the guarded formatter * * @example guardedDateTimeFormat("en-u-ca-islamic-civil", { era: "short", timeZone: "UTC" }).formatToParts(0) // the engine's parts */ function guardedDateTimeFormat(locale, options) { const native = new Intl.DateTimeFormat(locale, options); const built = options.year === "2-digit" ? widened(native, options) : options; return guardDateTimeFormat(repairEraYearNumerals(built === options ? native : new Intl.DateTimeFormat(locale, built), built), built); } /** * The locale tag as D30 needs it: a `ca` keyword of `islamic` becomes `islamic-tbla`, and one of * `islamic-rgsa` is taken out (with its `-u` when it was the last keyword). Other keywords stay. */ function islamicTag(tag) { if (!/islamic/i.test(tag)) return tag; try { const { calendar } = new Intl.Locale(tag); if (calendar === "islamic") return new Intl.Locale(tag, { calendar: "islamic-tbla" }).toString(); if (calendar === "islamic-rgsa") return tag.replace(/-ca-islamic-rgsa(?![\da-z])/i, "").replace(/-u(?=$|-[\da-wyz]-|-x-)/i, ""); } catch {} return tag; } /** * The locales and options a date formatter is built with, after D30: `islamic` becomes * `islamic-tbla` and `islamic-rgsa` is dropped, where the engine resolves either one (Intl * era/monthCode CreateDateTimeFormat; tc39/proposal-intl-era-monthcode#99). */ function islamicResolved(locale, options) { if (!isIslamicCalendarResolutionCompatNeeded()) return [locale, options]; let nextOptions = options; if (options.calendar === "islamic") nextOptions = { ...options, calendar: "islamic-tbla" }; else if (options.calendar === "islamic-rgsa") { nextOptions = { ...options }; delete nextOptions.calendar; } return [Array.isArray(locale) ? locale.map(islamicTag) : typeof locale === "string" ? islamicTag(locale) : locale, nextOptions]; } /** * @param refuseDates whether a chinese or dangi date formatter (compat D33) throws. The argument * check passes `false`: it builds from the caller's own options, which a time-only function * completes later (`formatTime`), so only the formatter a function formats with is refused. So * does a formatter whose date parts are thrown away (`joinDateTimeConnector`). */ function construct(kind, locale, options, refuseDates = true) { switch (kind) { case "DateTimeFormat": { const [built, builtOptions] = islamicResolved(locale, options); const guarded = guardedDateTimeFormat(built, builtOptions); if (refuseDates) refuseLunisolarDate(guarded); return repairIslamicEpochEra(repairCopticEra(repairYearPrinting(guarded, builtOptions, (twin) => cachedFormatter("DateTimeFormat", built, twin)), builtOptions), builtOptions); } case "NumberFormat": return new Intl.NumberFormat(locale, options); case "ListFormat": return new Intl.ListFormat(locale, options); case "RelativeTimeFormat": return new Intl.RelativeTimeFormat(locale, options); } } /** * Whether a canonical locale list can be part of a cache key: a string, or a non-empty array. * `undefined` and `[]` answer from the process default locale, which can change. */ function isCacheableLocale(locale) { return typeof locale === "string" || Array.isArray(locale) && locale.length > 0; } /** Whether these entries carry a `timeZone` string. */ function hasZoneString(entries) { return entries.some(([name, value]) => name === "timeZone" && typeof value === "string"); } /** * The cache key for these arguments, or `null` when they must be constructed fresh. The * locale is already canonical (see `canonicalLocale`). * * @param zoneRequired whether the options must carry a `timeZone` string: a `DateTimeFormat` * without one answers from the process default zone, which can change. */ function cacheKey(kind, locale, options, zoneRequired) { if (!isCacheableLocale(locale)) return null; const entries = plainOptionEntries(options); if (entries === null || zoneRequired && !hasZoneString(entries)) return null; return kind + JSON.stringify([locale, entries]); } /** * The locale list as `Intl` canonicalizes it (ECMA-402 CanonicalizeLocaleList): an array is read * once, here, through `Intl.getCanonicalLocales`, so the key and the constructor see the same * strings even when the array is a Proxy that answers each read differently, and a bad list * throws before the options are read, as in the constructors. A value that is not `undefined`, * a string or an array throws `TypeError`, which every caller turns into its sentinel. So does a list with an * entry that is not a string. */ function canonicalLocale(locale) { return typeof locale === "string" || locale === void 0 ? locale : canonicalLocaleTags(locale); } /** * A shared, read-only formatter for these arguments; built on the first call with them. * * A formatter's output is fixed by its constructor arguments and the host's locale data. A * `DateTimeFormat` also reads the default locale and default time zone, so it is cached only * with a `locale` string (or array of strings) and a `timeZone` string; any other argument * set is constructed fresh, exactly as `new Intl[kind](locale, options)` would. A construction * failure throws and is never cached. A formatter is kept only while `Intl[kind]` is the * constructor that built it. * * @param kind which `Intl` formatter class to build * @param locale BCP 47 locale or locales, or `undefined` for the runtime default * @param options the formatter's options, built by GMT code * @param refuseDates whether a date formatter is refused where compat D33 refuses it; * `false` only for a formatter whose date parts the caller throws away (`joinDateTimeConnector`) * @returns the formatter * * @example cachedFormatter("DateTimeFormat", "en-GB", { timeZone: "UTC" }).format(0) // "01/01/1970" * @example cachedFormatter("ListFormat", "en", { type: "conjunction" }).format(["a", "b"]) // "a and b" * @example cachedFormatter("DateTimeFormat", "not a locale", { timeZone: "UTC" }) // throws RangeError */ function cachedFormatter(kind, locale, options, refuseDates = true) { locale = canonicalLocale(locale); const cacheable = cacheKey(kind, locale, options, kind === "DateTimeFormat"); const key = cacheable === null || refuseDates ? cacheable : `${cacheable}!dates`; if (key === null) return construct(kind, locale, options, refuseDates); forgetIfReplaced(kind); let byKey = formatters.get(kind); const hit = byKey?.get(key); if (hit !== void 0) return hit; const built = construct(kind, locale, options, refuseDates); if (byKey === void 0) { byKey = /* @__PURE__ */ new Map(); formatters.set(kind, byKey); } else if (byKey.size >= MAX_ENTRIES_PER_KIND) byKey.clear(); byKey.set(key, built); return built; } /** * Construct once to raise the error `Intl` raises for these arguments; a repeat is a no-op. * * Whether construction throws does not depend on the default zone, so the arguments need no * `timeZone`. Only a success is remembered; an invalid call throws every time. * * @param kind which `Intl` formatter class to build * @param locale BCP 47 locale or locales, or `undefined` for the runtime default * @param options the formatter's options, built by GMT code * * @example checkFormatterArguments("DateTimeFormat", "en-GB", { dateStyle: "long" }) // returns * @example checkFormatterArguments("DateTimeFormat", "en-GB", { dateStyle: "huge" }) // throws RangeError */ function checkFormatterArguments(kind, locale, options) { locale = canonicalLocale(locale); const key = cacheKey(kind, locale, options, false); if (key === null) { construct(kind, locale, options, false); return; } forgetIfReplaced(kind); let seen = checked.get(kind); if (seen?.has(key)) return; construct(kind, locale, options, false); if (seen === void 0) { seen = /* @__PURE__ */ new Set(); checked.set(kind, seen); } else if (seen.size >= MAX_ENTRIES_PER_KIND) seen.clear(); seen.add(key); } /** Test seam: forget every cached formatter and every checked argument set. */ function clearFormatterCache() { formatters.clear(); checked.clear(); builtWith.clear(); forgetWeekYearVerdicts(); } export { cachedFormatter, checkFormatterArguments, clearFormatterCache, guardedDateTimeFormat };