@day-kit/date-engine 0.0.0-stage → 1.0.1

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,437 @@
1
+ import type { Temporal } from 'temporal-polyfill/implementation'
2
+ import {
3
+ isKnownCalendarSystem,
4
+ knownCalendarSystems,
5
+ type CalendarSystem,
6
+ } from '../contracts/calendar-system'
7
+ import type { DateEngine } from '../contracts/date-engine'
8
+ import type {
9
+ CalendarDate,
10
+ CalendarDateFields,
11
+ CalendarPeriod,
12
+ Instant,
13
+ LocalDateTime,
14
+ Overflow,
15
+ Weekday,
16
+ } from '../contracts/date-types'
17
+ import {
18
+ AmbiguousLocalTimeError,
19
+ CalendarSystemNotSupportedError,
20
+ DateRangeError,
21
+ InvalidCalendarFieldsError,
22
+ InvalidTimeZoneError,
23
+ NonexistentLocalTimeError,
24
+ } from '../contracts/errors'
25
+ import { createIntlFormatters } from '../formatting/intl-formatters'
26
+ import { weekdayFromIsoNumber } from '../formatting/locale-info'
27
+ import { instantFromEpochMilliseconds, maxEpochMilliseconds } from '../operations/instant'
28
+
29
+ /** The Temporal namespace shape shared by polyfill entrypoints and native Temporal. */
30
+ export type TemporalNamespace = typeof Temporal
31
+
32
+ export interface TemporalEngineConfig {
33
+ readonly name: string
34
+ readonly Temporal: TemporalNamespace
35
+ }
36
+
37
+ const maxTransitionsPerQuery = 10_000
38
+
39
+ // Opaque handle conversion. This is the only place where handles meet Temporal objects.
40
+ function toDateHandle(date: Temporal.PlainDate): CalendarDate {
41
+ return date as unknown as CalendarDate
42
+ }
43
+
44
+ function fromDateHandle(date: CalendarDate): Temporal.PlainDate {
45
+ return date as unknown as Temporal.PlainDate
46
+ }
47
+
48
+ function toLocalHandle(local: Temporal.PlainDateTime): LocalDateTime {
49
+ return local as unknown as LocalDateTime
50
+ }
51
+
52
+ function fromLocalHandle(local: LocalDateTime): Temporal.PlainDateTime {
53
+ return local as unknown as Temporal.PlainDateTime
54
+ }
55
+
56
+ function sign(value: number): -1 | 0 | 1 {
57
+ if (value < 0) return -1
58
+ if (value > 0) return 1
59
+ return 0
60
+ }
61
+
62
+ function isRangeError(error: unknown): error is RangeError {
63
+ return error instanceof RangeError
64
+ }
65
+
66
+ /**
67
+ * Creates a `DateEngine` backed by a Temporal namespace.
68
+ * Used with `temporal-polyfill/full/implementation` and `temporal-polyfill/implementation`;
69
+ * the conformance suite also runs it against native Temporal to prepare the migration.
70
+ */
71
+ export function createTemporalEngine(config: TemporalEngineConfig): DateEngine {
72
+ const { Temporal: T, name } = config
73
+ let supported: readonly CalendarSystem[] | undefined
74
+ let supportedSet: ReadonlySet<string> | undefined
75
+ const canonicalTimeZones = new Map<string, string>()
76
+
77
+ function probeCalendarSystems(): readonly CalendarSystem[] {
78
+ const result: CalendarSystem[] = []
79
+ const reference = T.PlainDate.from({ year: 2000, month: 1, day: 1 })
80
+ for (const calendarSystem of knownCalendarSystems) {
81
+ try {
82
+ const converted = reference.withCalendar(calendarSystem)
83
+ // Read a calendar-specific field so that lazily loaded calendar data is exercised.
84
+ if (converted.monthCode.length > 0 && converted.calendarId === calendarSystem) {
85
+ result.push(calendarSystem)
86
+ }
87
+ } catch (error) {
88
+ if (!isRangeError(error)) throw error
89
+ }
90
+ }
91
+ return result
92
+ }
93
+
94
+ function getSupported(): readonly CalendarSystem[] {
95
+ supported ??= probeCalendarSystems()
96
+ return supported
97
+ }
98
+
99
+ function isSupported(calendarSystem: string): calendarSystem is CalendarSystem {
100
+ supportedSet ??= new Set(getSupported())
101
+ return supportedSet.has(calendarSystem)
102
+ }
103
+
104
+ function requireCalendarSystem(calendarSystem: string): CalendarSystem {
105
+ if (isSupported(calendarSystem)) return calendarSystem
106
+ throw new CalendarSystemNotSupportedError(calendarSystem, name, getSupported())
107
+ }
108
+
109
+ function canonicalizeTimeZone(timeZone: string): string {
110
+ const cached = canonicalTimeZones.get(timeZone)
111
+ if (cached !== undefined) return cached
112
+ try {
113
+ const canonical = T.Instant.fromEpochMilliseconds(0).toZonedDateTimeISO(timeZone).timeZoneId
114
+ canonicalTimeZones.set(timeZone, canonical)
115
+ return canonical
116
+ } catch (error) {
117
+ throw new InvalidTimeZoneError(timeZone, { cause: error })
118
+ }
119
+ }
120
+
121
+ function zoned(instant: Instant, timeZone: string): Temporal.ZonedDateTime {
122
+ try {
123
+ return T.Instant.fromEpochMilliseconds(instant).toZonedDateTimeISO(timeZone)
124
+ } catch (error) {
125
+ if (isRangeError(error)) {
126
+ canonicalizeTimeZone(timeZone)
127
+ throw new DateRangeError(`Instant ${instant} is outside the supported range.`, {
128
+ cause: error,
129
+ })
130
+ }
131
+ throw error
132
+ }
133
+ }
134
+
135
+ function toInstant(epochMilliseconds: number): Instant {
136
+ return instantFromEpochMilliseconds(epochMilliseconds)
137
+ }
138
+
139
+ function guardRange<T>(operation: string, compute: () => T): T {
140
+ try {
141
+ return compute()
142
+ } catch (error) {
143
+ if (isRangeError(error)) {
144
+ throw new DateRangeError(`${operation} produced a date outside the supported range.`, {
145
+ cause: error,
146
+ })
147
+ }
148
+ throw error
149
+ }
150
+ }
151
+
152
+ function guardFields<T>(compute: () => T): T {
153
+ try {
154
+ return compute()
155
+ } catch (error) {
156
+ if (isRangeError(error) || error instanceof TypeError) {
157
+ throw new InvalidCalendarFieldsError(error.message, { cause: error })
158
+ }
159
+ throw error
160
+ }
161
+ }
162
+
163
+ function calendarOf(date: Temporal.PlainDate): CalendarSystem {
164
+ const id = date.calendarId
165
+ if (isKnownCalendarSystem(id)) return id
166
+ throw new CalendarSystemNotSupportedError(id, name, getSupported())
167
+ }
168
+
169
+ function startOfWeek(date: Temporal.PlainDate, weekStartsOn: Weekday): Temporal.PlainDate {
170
+ const daysInWeek = date.daysInWeek
171
+ const dayOfWeek = weekdayFromIsoNumber(date.dayOfWeek)
172
+ const offset = (dayOfWeek - weekStartsOn + daysInWeek) % daysInWeek
173
+ return guardRange('startOfWeek', () => date.subtract({ days: offset }))
174
+ }
175
+
176
+ function startOfMonth(date: Temporal.PlainDate): Temporal.PlainDate {
177
+ return date.with({ day: 1 })
178
+ }
179
+
180
+ function startOfYear(date: Temporal.PlainDate): Temporal.PlainDate {
181
+ return date.with({ month: 1, day: 1 })
182
+ }
183
+
184
+ function period(
185
+ unit: CalendarPeriod['unit'],
186
+ start: Temporal.PlainDate,
187
+ end: Temporal.PlainDate,
188
+ ): CalendarPeriod {
189
+ return { unit, start: toDateHandle(start), end: toDateHandle(end) }
190
+ }
191
+
192
+ const formatters = createIntlFormatters({
193
+ name,
194
+ requireCalendarSystem,
195
+ canonicalizeTimeZone,
196
+ toIsoDate: (date) => {
197
+ const plain = fromDateHandle(date).withCalendar('iso8601')
198
+ return { year: plain.year, month: plain.month, day: plain.day }
199
+ },
200
+ })
201
+
202
+ const engine: DateEngine = {
203
+ name,
204
+
205
+ getSupportedCalendarSystems: getSupported,
206
+ isCalendarSystemSupported: isSupported,
207
+ requireCalendarSystem,
208
+ isFormattingSupported: (calendarSystem) =>
209
+ isSupported(calendarSystem) && formatters.isFormattingSupported(calendarSystem),
210
+ canonicalizeTimeZone,
211
+
212
+ now: () => toInstant(T.Now.instant().epochMilliseconds),
213
+
214
+ toCalendarDate(instant, timeZone, calendarSystem) {
215
+ const calendar = requireCalendarSystem(calendarSystem)
216
+ return toDateHandle(zoned(instant, timeZone).toPlainDate().withCalendar(calendar))
217
+ },
218
+
219
+ getDayStart(date, timeZone) {
220
+ const plain = fromDateHandle(date)
221
+ const start = guardRange('getDayStart', () => plain.toZonedDateTime({ timeZone }))
222
+ const startDate = start.toPlainDate()
223
+ return {
224
+ instant: toInstant(start.epochMilliseconds),
225
+ isSkipped: !startDate.equals(plain),
226
+ }
227
+ },
228
+
229
+ toZonedFields(instant, timeZone, calendarSystem) {
230
+ const calendar = requireCalendarSystem(calendarSystem)
231
+ const value = zoned(instant, timeZone).withCalendar(calendar)
232
+ return {
233
+ date: toDateHandle(value.toPlainDate()),
234
+ time: {
235
+ hour: value.hour,
236
+ minute: value.minute,
237
+ second: value.second,
238
+ millisecond: value.millisecond,
239
+ },
240
+ offsetMilliseconds: value.offsetNanoseconds / 1e6,
241
+ }
242
+ },
243
+
244
+ getOffsetMilliseconds: (instant, timeZone) => zoned(instant, timeZone).offsetNanoseconds / 1e6,
245
+
246
+ createDate(input, calendarSystem, overflow: Overflow = 'reject') {
247
+ const calendar = requireCalendarSystem(calendarSystem)
248
+ return toDateHandle(guardFields(() => T.PlainDate.from({ ...input, calendar }, { overflow })))
249
+ },
250
+
251
+ fromIsoDate(iso, calendarSystem) {
252
+ const calendar = requireCalendarSystem(calendarSystem)
253
+ return toDateHandle(
254
+ guardFields(() =>
255
+ T.PlainDate.from(
256
+ { year: iso.year, month: iso.month, day: iso.day },
257
+ { overflow: 'reject' },
258
+ ).withCalendar(calendar),
259
+ ),
260
+ )
261
+ },
262
+
263
+ toIsoDate(date) {
264
+ const plain = fromDateHandle(date).withCalendar('iso8601')
265
+ return { year: plain.year, month: plain.month, day: plain.day }
266
+ },
267
+
268
+ withCalendar: (date, calendarSystem) =>
269
+ toDateHandle(fromDateHandle(date).withCalendar(requireCalendarSystem(calendarSystem))),
270
+
271
+ getCalendarSystem: (date) => calendarOf(fromDateHandle(date)),
272
+
273
+ toKey(date) {
274
+ const plain = fromDateHandle(date)
275
+ return `${plain.calendarId}:${plain.toString({ calendarName: 'never' })}`
276
+ },
277
+
278
+ getDateFields(date) {
279
+ const plain = fromDateHandle(date)
280
+ const fields: CalendarDateFields = {
281
+ calendarSystem: calendarOf(plain),
282
+ year: plain.year,
283
+ month: plain.month,
284
+ monthCode: plain.monthCode,
285
+ day: plain.day,
286
+ dayOfWeek: weekdayFromIsoNumber(plain.dayOfWeek),
287
+ dayOfYear: plain.dayOfYear,
288
+ daysInWeek: plain.daysInWeek,
289
+ daysInMonth: plain.daysInMonth,
290
+ daysInYear: plain.daysInYear,
291
+ monthsInYear: plain.monthsInYear,
292
+ inLeapYear: plain.inLeapYear,
293
+ ...(plain.era === undefined ? {} : { era: plain.era }),
294
+ ...(plain.eraYear === undefined ? {} : { eraYear: plain.eraYear }),
295
+ ...(plain.weekOfYear === undefined ? {} : { weekOfYear: plain.weekOfYear }),
296
+ ...(plain.yearOfWeek === undefined ? {} : { yearOfWeek: plain.yearOfWeek }),
297
+ }
298
+ return fields
299
+ },
300
+
301
+ getIsoWeek(date) {
302
+ const iso = fromDateHandle(date).withCalendar('iso8601')
303
+ const { weekOfYear, yearOfWeek } = iso
304
+ if (weekOfYear === undefined || yearOfWeek === undefined) {
305
+ throw new DateRangeError(`ISO week is not defined for ${iso.toString()}.`)
306
+ }
307
+ return { week: weekOfYear, year: yearOfWeek }
308
+ },
309
+
310
+ add: (date, duration, overflow: Overflow = 'constrain') =>
311
+ toDateHandle(guardRange('add', () => fromDateHandle(date).add(duration, { overflow }))),
312
+
313
+ with: (date, change, overflow: Overflow = 'constrain') =>
314
+ toDateHandle(guardFields(() => fromDateHandle(date).with(change, { overflow }))),
315
+
316
+ until(from, to, unit) {
317
+ const duration = fromDateHandle(from).until(fromDateHandle(to), { largestUnit: unit })
318
+ const byUnit = { days: duration.days, months: duration.months, years: duration.years }
319
+ return byUnit[unit]
320
+ },
321
+
322
+ compare: (a, b) => sign(T.PlainDate.compare(fromDateHandle(a), fromDateHandle(b))),
323
+ equals: (a, b) => fromDateHandle(a).equals(fromDateHandle(b)),
324
+
325
+ startOfWeek: (date, weekStartsOn) =>
326
+ toDateHandle(startOfWeek(fromDateHandle(date), weekStartsOn)),
327
+ startOfMonth: (date) => toDateHandle(startOfMonth(fromDateHandle(date))),
328
+ startOfYear: (date) => toDateHandle(startOfYear(fromDateHandle(date))),
329
+
330
+ getPeriod(date, unit) {
331
+ const plain = fromDateHandle(date)
332
+ if (unit === 'day') {
333
+ return period(
334
+ unit,
335
+ plain,
336
+ guardRange('getPeriod', () => plain.add({ days: 1 })),
337
+ )
338
+ }
339
+ if (unit === 'month') {
340
+ const start = startOfMonth(plain)
341
+ return period(
342
+ unit,
343
+ start,
344
+ guardRange('getPeriod', () => start.add({ months: 1 })),
345
+ )
346
+ }
347
+ const start = startOfYear(plain)
348
+ return period(
349
+ unit,
350
+ start,
351
+ guardRange('getPeriod', () => start.add({ years: 1 })),
352
+ )
353
+ },
354
+
355
+ getWeekPeriod(date, weekStartsOn) {
356
+ const start = startOfWeek(fromDateHandle(date), weekStartsOn)
357
+ return period(
358
+ 'week',
359
+ start,
360
+ guardRange('getWeekPeriod', () => start.add({ days: start.daysInWeek })),
361
+ )
362
+ },
363
+
364
+ getMonthsOfYear(date) {
365
+ const first = startOfYear(fromDateHandle(date))
366
+ const nextYear = guardRange('getMonthsOfYear', () => first.add({ years: 1 }))
367
+ const months: CalendarDate[] = []
368
+ for (
369
+ let month = first;
370
+ T.PlainDate.compare(month, nextYear) < 0;
371
+ month = month.add({ months: 1 })
372
+ ) {
373
+ months.push(toDateHandle(month))
374
+ }
375
+ return months
376
+ },
377
+
378
+ createLocalDateTime: (date, time) =>
379
+ toLocalHandle(guardFields(() => fromDateHandle(date).toPlainDateTime(time))),
380
+
381
+ resolveLocalDateTime(local, timeZone) {
382
+ const plain = fromLocalHandle(local)
383
+ const earlier = guardRange('resolveLocalDateTime', () =>
384
+ plain.toZonedDateTime(timeZone, { disambiguation: 'earlier' }),
385
+ )
386
+ const later = guardRange('resolveLocalDateTime', () =>
387
+ plain.toZonedDateTime(timeZone, { disambiguation: 'later' }),
388
+ )
389
+ if (earlier.epochMilliseconds === later.epochMilliseconds) {
390
+ return { kind: 'unique', instant: toInstant(earlier.epochMilliseconds) }
391
+ }
392
+ const kind = earlier.toPlainDateTime().equals(plain) ? 'repeated' : 'nonexistent'
393
+ return {
394
+ kind,
395
+ earlier: toInstant(earlier.epochMilliseconds),
396
+ later: toInstant(later.epochMilliseconds),
397
+ }
398
+ },
399
+
400
+ toInstant(local, timeZone, disambiguation) {
401
+ if (disambiguation === 'reject') {
402
+ const resolution = engine.resolveLocalDateTime(local, timeZone)
403
+ const label = fromLocalHandle(local).toString({ calendarName: 'never' })
404
+ if (resolution.kind === 'nonexistent') {
405
+ throw new NonexistentLocalTimeError(`${label} does not exist in ${timeZone}.`)
406
+ }
407
+ if (resolution.kind === 'repeated') {
408
+ throw new AmbiguousLocalTimeError(`${label} occurs twice in ${timeZone}.`)
409
+ }
410
+ return resolution.instant
411
+ }
412
+ const resolved = guardRange('toInstant', () =>
413
+ fromLocalHandle(local).toZonedDateTime(timeZone, { disambiguation }),
414
+ )
415
+ return toInstant(resolved.epochMilliseconds)
416
+ },
417
+
418
+ getTimeZoneTransitions(timeZone, start, end) {
419
+ const transitions: Instant[] = []
420
+ if (end <= start) return transitions
421
+ // Start one millisecond early so that a transition exactly at `start` is included.
422
+ let cursor = zoned(toInstant(Math.max(start - 1, -maxEpochMilliseconds)), timeZone)
423
+ while (transitions.length < maxTransitionsPerQuery) {
424
+ const next = cursor.getTimeZoneTransition('next')
425
+ if (next === null || next.epochMilliseconds >= end) break
426
+ if (next.epochMilliseconds >= start) transitions.push(toInstant(next.epochMilliseconds))
427
+ cursor = next
428
+ }
429
+ return transitions
430
+ },
431
+
432
+ createCalendarDateFormatter: formatters.createCalendarDateFormatter,
433
+ createInstantFormatter: formatters.createInstantFormatter,
434
+ }
435
+
436
+ return engine
437
+ }
@@ -0,0 +1,11 @@
1
+ import { Temporal } from 'temporal-polyfill/full/implementation'
2
+ import type { DateEngine } from '../contracts/date-engine'
3
+ import { createTemporalEngine } from './create-temporal-engine'
4
+
5
+ /**
6
+ * Date engine with every calendar system supported by temporal-polyfill
7
+ * (`temporal-polyfill/full/implementation`). Never uses or installs a global Temporal.
8
+ */
9
+ export function createTemporalDateEngine(): DateEngine {
10
+ return createTemporalEngine({ name: 'temporal-polyfill/full', Temporal })
11
+ }
@@ -0,0 +1,11 @@
1
+ import { Temporal } from 'temporal-polyfill/implementation'
2
+ import type { DateEngine } from '../contracts/date-engine'
3
+ import { createTemporalEngine } from './create-temporal-engine'
4
+
5
+ /**
6
+ * Smaller date engine that supports only the `iso8601` and `gregory` calendar systems
7
+ * (`temporal-polyfill/implementation`). Other calendars throw `CalendarSystemNotSupportedError`.
8
+ */
9
+ export function createGregorianDateEngine(): DateEngine {
10
+ return createTemporalEngine({ name: 'temporal-polyfill/gregorian', Temporal })
11
+ }