|
| 1 | +const validTimeZoneCache = new Map<string, boolean>(); |
| 2 | +const timestampFormatterCache = new Map<string, Intl.DateTimeFormat>(); |
| 3 | +let hostTimeZone: string | undefined; |
| 4 | + |
1 | 5 | export function isValidTimeZone(tz: string): boolean { |
| 6 | +const cached = validTimeZoneCache.get(tz); |
| 7 | +if (cached !== undefined) { |
| 8 | +return cached; |
| 9 | +} |
| 10 | +let valid = false; |
2 | 11 | try { |
3 | 12 | new Intl.DateTimeFormat("en", { timeZone: tz }).format(); |
4 | | -return true; |
| 13 | +valid = true; |
5 | 14 | } catch { |
6 | | -return false; |
| 15 | +valid = false; |
7 | 16 | } |
| 17 | +validTimeZoneCache.set(tz, valid); |
| 18 | +return valid; |
8 | 19 | } |
9 | 20 | |
10 | 21 | type TimestampStyle = "short" | "medium" | "long"; |
@@ -18,26 +29,33 @@ function resolveEffectiveTimeZone(timeZone?: string): string {
|
18 | 29 | const explicit = timeZone ?? process.env.TZ; |
19 | 30 | return explicit && isValidTimeZone(explicit) |
20 | 31 | ? explicit |
21 | | - : Intl.DateTimeFormat().resolvedOptions().timeZone; |
| 32 | + : (hostTimeZone ??= Intl.DateTimeFormat().resolvedOptions().timeZone); |
22 | 33 | } |
23 | 34 | |
24 | 35 | function formatOffset(offsetRaw: string): string { |
25 | 36 | return offsetRaw === "GMT" ? "+00:00" : offsetRaw.slice(3); |
26 | 37 | } |
27 | 38 | |
28 | 39 | function getTimestampParts(date: Date, timeZone?: string) { |
29 | | -const fmt = new Intl.DateTimeFormat("en", { |
30 | | -timeZone: resolveEffectiveTimeZone(timeZone), |
31 | | -year: "numeric", |
32 | | -month: "2-digit", |
33 | | -day: "2-digit", |
34 | | -hour: "2-digit", |
35 | | -minute: "2-digit", |
36 | | -second: "2-digit", |
37 | | -hour12: false, |
38 | | -fractionalSecondDigits: 3 as 1 | 2 | 3, |
39 | | -timeZoneName: "longOffset", |
40 | | -}); |
| 40 | +const effectiveTimeZone = resolveEffectiveTimeZone(timeZone); |
| 41 | +let fmt = timestampFormatterCache.get(effectiveTimeZone); |
| 42 | +if (!fmt) { |
| 43 | +// Log timestamps are formatted on hot paths; Intl construction is much |
| 44 | +// costlier than formatToParts, while timezone rules remain process-stable. |
| 45 | +fmt = new Intl.DateTimeFormat("en", { |
| 46 | +timeZone: effectiveTimeZone, |
| 47 | +year: "numeric", |
| 48 | +month: "2-digit", |
| 49 | +day: "2-digit", |
| 50 | +hour: "2-digit", |
| 51 | +minute: "2-digit", |
| 52 | +second: "2-digit", |
| 53 | +hour12: false, |
| 54 | +fractionalSecondDigits: 3 as 1 | 2 | 3, |
| 55 | +timeZoneName: "longOffset", |
| 56 | +}); |
| 57 | +timestampFormatterCache.set(effectiveTimeZone, fmt); |
| 58 | +} |
41 | 59 | |
42 | 60 | const parts = Object.fromEntries(fmt.formatToParts(date).map((part) => [part.type, part.value])); |
43 | 61 | return { |
|