@baukit/localization-core 0.7.2 → 0.7.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.
@@ -0,0 +1,171 @@
1
+ import { INVALID_CIVIL_DATE_CODE, parseCivilDate } from './civil-date.js';
2
+
3
+ export type GapPolicy = 'reject' | 'shiftForward';
4
+ export type FoldPolicy = 'earlier' | 'later';
5
+ export type LocalTimeTransition = 'none' | 'gap' | 'fold';
6
+
7
+ export const INVALID_CIVIL_TIME_CODE = 'invalid_civil_time';
8
+ export const INVALID_TIME_ZONE_CODE = 'invalid_time_zone';
9
+ export const NONEXISTENT_LOCAL_TIME_CODE = 'nonexistent_local_time';
10
+
11
+ export type ZonedLocalTimeCode =
12
+ | typeof INVALID_CIVIL_DATE_CODE
13
+ | typeof INVALID_CIVIL_TIME_CODE
14
+ | typeof INVALID_TIME_ZONE_CODE
15
+ | typeof NONEXISTENT_LOCAL_TIME_CODE;
16
+
17
+ export interface ZonedLocalTime {
18
+ readonly civilDate: string;
19
+ readonly civilTime: string;
20
+ readonly timeZone: string;
21
+ readonly gap: GapPolicy;
22
+ readonly fold: FoldPolicy;
23
+ }
24
+
25
+ export type ZonedLocalTimeResult =
26
+ | {
27
+ readonly ok: true;
28
+ readonly epochMilliseconds: number;
29
+ readonly transition: LocalTimeTransition;
30
+ }
31
+ | { readonly ok: false; readonly code: ZonedLocalTimeCode };
32
+
33
+ interface WallClock {
34
+ readonly year: number;
35
+ readonly month: number;
36
+ readonly day: number;
37
+ readonly hour: number;
38
+ readonly minute: number;
39
+ readonly second: number;
40
+ }
41
+
42
+ const CIVIL_TIME_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)(?::([0-5]\d))?$/;
43
+ const OFFSET_TIME_ZONE_PATTERN = /^[+-]/;
44
+ const GAP_POLICIES: readonly string[] = ['reject', 'shiftForward'] satisfies GapPolicy[];
45
+ const FOLD_POLICIES: readonly string[] = ['earlier', 'later'] satisfies FoldPolicy[];
46
+ const HOURS_PER_DAY = 24;
47
+ const MILLISECONDS_PER_DAY = 86_400_000;
48
+ const OFFSET_SAMPLE_DISTANCES = [-MILLISECONDS_PER_DAY, 0, MILLISECONDS_PER_DAY];
49
+
50
+ export function resolveZonedLocalTime(input: ZonedLocalTime): ZonedLocalTimeResult {
51
+ assertPolicies(input.gap, input.fold);
52
+ const date = parseCivilDate(input.civilDate);
53
+ if (!date.ok) {
54
+ return { ok: false, code: INVALID_CIVIL_DATE_CODE };
55
+ }
56
+ const time = CIVIL_TIME_PATTERN.exec(input.civilTime);
57
+ if (time === null) {
58
+ return { ok: false, code: INVALID_CIVIL_TIME_CODE };
59
+ }
60
+ const formatter = zoneFormatter(input.timeZone);
61
+ if (formatter === null) {
62
+ return { ok: false, code: INVALID_TIME_ZONE_CODE };
63
+ }
64
+
65
+ const [year, month, day] = input.civilDate.split('-').map(Number) as [number, number, number];
66
+ const wall = utcMilliseconds({
67
+ year,
68
+ month,
69
+ day,
70
+ hour: Number(time[1]),
71
+ minute: Number(time[2]),
72
+ second: Number(time[3] ?? 0),
73
+ });
74
+ return resolveWall(formatter, wall, input);
75
+ }
76
+
77
+ function assertPolicies(gap: unknown, fold: unknown): void {
78
+ if (typeof gap !== 'string' || !GAP_POLICIES.includes(gap)) {
79
+ throw new RangeError(`Unknown gap policy: ${String(gap)}`);
80
+ }
81
+ if (typeof fold !== 'string' || !FOLD_POLICIES.includes(fold)) {
82
+ throw new RangeError(`Unknown fold policy: ${String(fold)}`);
83
+ }
84
+ }
85
+
86
+ function resolveWall(
87
+ formatter: Intl.DateTimeFormat,
88
+ wall: number,
89
+ policy: Pick<ZonedLocalTime, 'gap' | 'fold'>,
90
+ ): ZonedLocalTimeResult {
91
+ const candidates = candidateInstants(formatter, wall);
92
+ const earliest = candidates[0];
93
+ const latest = candidates[candidates.length - 1];
94
+ if (earliest === undefined || latest === undefined) {
95
+ return resolveGap(formatter, wall, policy.gap);
96
+ }
97
+ if (earliest === latest) {
98
+ return { ok: true, epochMilliseconds: earliest, transition: 'none' };
99
+ }
100
+ const epochMilliseconds = policy.fold === 'earlier' ? earliest : latest;
101
+ return { ok: true, epochMilliseconds, transition: 'fold' };
102
+ }
103
+
104
+ function resolveGap(
105
+ formatter: Intl.DateTimeFormat,
106
+ wall: number,
107
+ gap: GapPolicy,
108
+ ): ZonedLocalTimeResult {
109
+ if (gap === 'reject') {
110
+ return { ok: false, code: NONEXISTENT_LOCAL_TIME_CODE };
111
+ }
112
+ const offsetBeforeGap = offsetAt(formatter, wall - MILLISECONDS_PER_DAY);
113
+ return { ok: true, epochMilliseconds: wall - offsetBeforeGap, transition: 'gap' };
114
+ }
115
+
116
+ function candidateInstants(formatter: Intl.DateTimeFormat, wall: number): number[] {
117
+ const offsets = new Set(
118
+ OFFSET_SAMPLE_DISTANCES.map((distance) => offsetAt(formatter, wall + distance)),
119
+ );
120
+ return [...offsets]
121
+ .map((offset) => wall - offset)
122
+ .filter((instant) => localWallAt(formatter, instant) === wall)
123
+ .sort((left, right) => left - right);
124
+ }
125
+
126
+ function offsetAt(formatter: Intl.DateTimeFormat, instant: number): number {
127
+ return localWallAt(formatter, instant) - instant;
128
+ }
129
+
130
+ function localWallAt(formatter: Intl.DateTimeFormat, instant: number): number {
131
+ const parts = formatter.formatToParts(new Date(instant));
132
+ const part = (type: Intl.DateTimeFormatPartTypes): number =>
133
+ Number(parts.find((candidate) => candidate.type === type)?.value);
134
+ return utcMilliseconds({
135
+ year: part('year'),
136
+ month: part('month'),
137
+ day: part('day'),
138
+ hour: part('hour') % HOURS_PER_DAY,
139
+ minute: part('minute'),
140
+ second: part('second'),
141
+ });
142
+ }
143
+
144
+ function utcMilliseconds(wall: WallClock): number {
145
+ const date = new Date(0);
146
+ date.setUTCFullYear(wall.year, wall.month - 1, wall.day);
147
+ date.setUTCHours(wall.hour, wall.minute, wall.second, 0);
148
+ return date.getTime();
149
+ }
150
+
151
+ function zoneFormatter(timeZone: string): Intl.DateTimeFormat | null {
152
+ if (OFFSET_TIME_ZONE_PATTERN.test(timeZone)) {
153
+ return null;
154
+ }
155
+ try {
156
+ return new Intl.DateTimeFormat('en-US', {
157
+ timeZone,
158
+ calendar: 'gregory',
159
+ numberingSystem: 'latn',
160
+ hourCycle: 'h23',
161
+ year: 'numeric',
162
+ month: '2-digit',
163
+ day: '2-digit',
164
+ hour: '2-digit',
165
+ minute: '2-digit',
166
+ second: '2-digit',
167
+ });
168
+ } catch {
169
+ return null;
170
+ }
171
+ }