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

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.
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@day-kit/date-engine",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Internal date-engine abstraction for @day-kit/core. Not intended for direct use.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/lorof/day-kit.git",
9
+ "directory": "packages/date-engine"
10
+ },
11
+ "homepage": "https://github.com/lorof/day-kit#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/lorof/day-kit/issues"
14
+ },
15
+ "keywords": [
16
+ "calendar",
17
+ "temporal"
18
+ ],
19
+ "engines": {
20
+ "node": ">=20.19"
21
+ },
22
+ "type": "module",
23
+ "sideEffects": false,
24
+ "exports": {
25
+ ".": {
26
+ "@day-kit/source": "./src/index.ts",
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ },
30
+ "./temporal": {
31
+ "@day-kit/source": "./src/temporal/full-engine.ts",
32
+ "types": "./dist/temporal.d.ts",
33
+ "default": "./dist/temporal.js"
34
+ },
35
+ "./temporal-gregorian": {
36
+ "@day-kit/source": "./src/temporal/gregorian-engine.ts",
37
+ "types": "./dist/temporal-gregorian.d.ts",
38
+ "default": "./dist/temporal-gregorian.js"
39
+ },
40
+ "./package.json": "./package.json"
41
+ },
42
+ "files": [
43
+ "dist",
44
+ "src"
45
+ ],
46
+ "dependencies": {
47
+ "temporal-polyfill": "1.0.8"
48
+ },
49
+ "scripts": {
50
+ "build": "tsdown",
51
+ "dev": "tsdown --watch",
52
+ "typecheck": "tsc --noEmit",
53
+ "test": "vitest run"
54
+ }
6
55
  }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Calendar system identifiers known to the library (CLDR / Temporal identifiers).
3
+ *
4
+ * Whether a given identifier is usable depends on the configured date engine.
5
+ * Use `engine.getSupportedCalendarSystems()` for the actual capabilities.
6
+ */
7
+ export type CalendarSystem =
8
+ | 'iso8601'
9
+ | 'gregory'
10
+ | 'buddhist'
11
+ | 'chinese'
12
+ | 'coptic'
13
+ | 'dangi'
14
+ | 'ethiopic'
15
+ | 'ethioaa'
16
+ | 'hebrew'
17
+ | 'indian'
18
+ | 'islamic-civil'
19
+ | 'islamic-tbla'
20
+ | 'islamic-umalqura'
21
+ | 'japanese'
22
+ | 'persian'
23
+ | 'roc'
24
+
25
+ export const knownCalendarSystems: readonly CalendarSystem[] = [
26
+ 'iso8601',
27
+ 'gregory',
28
+ 'buddhist',
29
+ 'chinese',
30
+ 'coptic',
31
+ 'dangi',
32
+ 'ethiopic',
33
+ 'ethioaa',
34
+ 'hebrew',
35
+ 'indian',
36
+ 'islamic-civil',
37
+ 'islamic-tbla',
38
+ 'islamic-umalqura',
39
+ 'japanese',
40
+ 'persian',
41
+ 'roc',
42
+ ]
43
+
44
+ const knownCalendarSystemSet: ReadonlySet<string> = new Set(knownCalendarSystems)
45
+
46
+ export function isKnownCalendarSystem(value: string): value is CalendarSystem {
47
+ return knownCalendarSystemSet.has(value)
48
+ }
@@ -0,0 +1,140 @@
1
+ import type { CalendarSystem } from './calendar-system'
2
+ import type {
3
+ CalendarDateFormatter,
4
+ CalendarDateFormatterOptions,
5
+ InstantFormatter,
6
+ InstantFormatterOptions,
7
+ } from './date-formatter'
8
+ import type {
9
+ CalendarDate,
10
+ CalendarDateChange,
11
+ CalendarDateFields,
12
+ CalendarDateInput,
13
+ CalendarDuration,
14
+ CalendarPeriod,
15
+ DayStart,
16
+ Disambiguation,
17
+ Instant,
18
+ IsoDateFields,
19
+ LocalDateTime,
20
+ LocalTimeResolution,
21
+ Overflow,
22
+ WallClockTime,
23
+ Weekday,
24
+ ZonedDateTimeFields,
25
+ } from './date-types'
26
+
27
+ export interface IsoWeek {
28
+ readonly week: number
29
+ readonly year: number
30
+ }
31
+
32
+ /**
33
+ * The calendar arithmetic contract used by `@day-kit/core`.
34
+ *
35
+ * Every operation is pure. `CalendarDate` and `LocalDateTime` handles are opaque and
36
+ * must only be passed back to the engine that created them.
37
+ * Methods throw `CalendarError` subclasses; they never fall back to Gregorian arithmetic.
38
+ */
39
+ export interface DateEngine {
40
+ /** Implementation identifier, e.g. `temporal-polyfill/full`. */
41
+ readonly name: string
42
+
43
+ // Capabilities
44
+ readonly getSupportedCalendarSystems: () => readonly CalendarSystem[]
45
+ readonly isCalendarSystemSupported: (calendarSystem: string) => calendarSystem is CalendarSystem
46
+ /** Returns the calendar system or throws `CalendarSystemNotSupportedError`. */
47
+ readonly requireCalendarSystem: (calendarSystem: string) => CalendarSystem
48
+ /** Whether the runtime can format this calendar with Intl consistently with the engine. */
49
+ readonly isFormattingSupported: (calendarSystem: CalendarSystem) => boolean
50
+ /** Returns the canonical IANA identifier or throws `InvalidTimeZoneError`. */
51
+ readonly canonicalizeTimeZone: (timeZone: string) => string
52
+
53
+ // Instants and civil days
54
+ /** The current instant from the host clock. Core prefers its injectable clock. */
55
+ readonly now: () => Instant
56
+ /** The civil date that contains `instant` in `timeZone`. */
57
+ readonly toCalendarDate: (
58
+ instant: Instant,
59
+ timeZone: string,
60
+ calendarSystem: CalendarSystem,
61
+ ) => CalendarDate
62
+ /** The first instant of the civil day, with skipped-day detection. */
63
+ readonly getDayStart: (date: CalendarDate, timeZone: string) => DayStart
64
+ /** The calendar date and wall-clock time of an instant. */
65
+ readonly toZonedFields: (
66
+ instant: Instant,
67
+ timeZone: string,
68
+ calendarSystem: CalendarSystem,
69
+ ) => ZonedDateTimeFields
70
+ readonly getOffsetMilliseconds: (instant: Instant, timeZone: string) => number
71
+
72
+ // Construction and conversion
73
+ readonly createDate: (
74
+ input: CalendarDateInput,
75
+ calendarSystem: CalendarSystem,
76
+ overflow?: Overflow,
77
+ ) => CalendarDate
78
+ readonly fromIsoDate: (iso: IsoDateFields, calendarSystem: CalendarSystem) => CalendarDate
79
+ readonly toIsoDate: (date: CalendarDate) => IsoDateFields
80
+ readonly withCalendar: (date: CalendarDate, calendarSystem: CalendarSystem) => CalendarDate
81
+ readonly getCalendarSystem: (date: CalendarDate) => CalendarSystem
82
+ /** Stable identity key including the calendar, e.g. `hebrew:2024-03-01` (ISO date). */
83
+ readonly toKey: (date: CalendarDate) => string
84
+
85
+ // Metadata
86
+ readonly getDateFields: (date: CalendarDate) => CalendarDateFields
87
+ /** ISO-8601 week (computed on the ISO calendar), explicitly ISO. */
88
+ readonly getIsoWeek: (date: CalendarDate) => IsoWeek
89
+
90
+ // Arithmetic and comparison
91
+ readonly add: (
92
+ date: CalendarDate,
93
+ duration: CalendarDuration,
94
+ overflow?: Overflow,
95
+ ) => CalendarDate
96
+ readonly with: (
97
+ date: CalendarDate,
98
+ change: CalendarDateChange,
99
+ overflow?: Overflow,
100
+ ) => CalendarDate
101
+ /** Whole units from `from` to `to` (negative when `to` is earlier). Both must share a calendar for months/years. */
102
+ readonly until: (
103
+ from: CalendarDate,
104
+ to: CalendarDate,
105
+ unit: 'days' | 'months' | 'years',
106
+ ) => number
107
+ readonly compare: (a: CalendarDate, b: CalendarDate) => -1 | 0 | 1
108
+ readonly equals: (a: CalendarDate, b: CalendarDate) => boolean
109
+
110
+ // Calendar periods (half-open)
111
+ readonly startOfWeek: (date: CalendarDate, weekStartsOn: Weekday) => CalendarDate
112
+ readonly startOfMonth: (date: CalendarDate) => CalendarDate
113
+ readonly startOfYear: (date: CalendarDate) => CalendarDate
114
+ readonly getPeriod: (date: CalendarDate, unit: 'day' | 'month' | 'year') => CalendarPeriod
115
+ readonly getWeekPeriod: (date: CalendarDate, weekStartsOn: Weekday) => CalendarPeriod
116
+ /** First day of every month of the date's calendar year, traversing real month boundaries. */
117
+ readonly getMonthsOfYear: (date: CalendarDate) => readonly CalendarDate[]
118
+
119
+ // Wall-clock time
120
+ readonly createLocalDateTime: (date: CalendarDate, time: Partial<WallClockTime>) => LocalDateTime
121
+ readonly resolveLocalDateTime: (local: LocalDateTime, timeZone: string) => LocalTimeResolution
122
+ /** Resolves a wall-clock time; `reject` throws on nonexistent or repeated times. */
123
+ readonly toInstant: (
124
+ local: LocalDateTime,
125
+ timeZone: string,
126
+ disambiguation: Disambiguation,
127
+ ) => Instant
128
+ /** Offset-transition instants in `[start, end)`. */
129
+ readonly getTimeZoneTransitions: (
130
+ timeZone: string,
131
+ start: Instant,
132
+ end: Instant,
133
+ ) => readonly Instant[]
134
+
135
+ // Formatting
136
+ readonly createCalendarDateFormatter: (
137
+ options: CalendarDateFormatterOptions,
138
+ ) => CalendarDateFormatter
139
+ readonly createInstantFormatter: (options: InstantFormatterOptions) => InstantFormatter
140
+ }
@@ -0,0 +1,47 @@
1
+ import type { CalendarSystem } from './calendar-system'
2
+ import type { CalendarDate, Instant } from './date-types'
3
+
4
+ /** Intl options that describe a calendar date (no time, no time zone). */
5
+ export type CalendarDateFormatOptions = Pick<
6
+ Intl.DateTimeFormatOptions,
7
+ 'era' | 'year' | 'month' | 'day' | 'weekday' | 'dateStyle' | 'numberingSystem'
8
+ >
9
+
10
+ /** Intl options for formatting an instant; calendar and time zone are configured separately. */
11
+ export type InstantFormatOptions = Omit<Intl.DateTimeFormatOptions, 'calendar' | 'timeZone'>
12
+
13
+ export interface CalendarDateFormatterOptions {
14
+ readonly locale?: string
15
+ readonly calendarSystem: CalendarSystem
16
+ readonly format: CalendarDateFormatOptions
17
+ }
18
+
19
+ export interface InstantFormatterOptions {
20
+ readonly locale?: string
21
+ readonly calendarSystem: CalendarSystem
22
+ readonly timeZone: string
23
+ readonly format: InstantFormatOptions
24
+ }
25
+
26
+ export interface ResolvedFormatInfo {
27
+ readonly locale: string
28
+ readonly calendarSystem: CalendarSystem
29
+ readonly numberingSystem: string
30
+ }
31
+
32
+ /** Formats calendar dates independently of any time zone. */
33
+ export interface CalendarDateFormatter {
34
+ readonly resolved: ResolvedFormatInfo
35
+ readonly format: (date: CalendarDate) => string
36
+ readonly formatToParts: (date: CalendarDate) => Intl.DateTimeFormatPart[]
37
+ /** Formats an inclusive range of calendar dates, e.g. "Mar 10 – 16, 2024". */
38
+ readonly formatRange: (start: CalendarDate, end: CalendarDate) => string
39
+ }
40
+
41
+ /** Formats instants in a configured calendar system and time zone. */
42
+ export interface InstantFormatter {
43
+ readonly resolved: ResolvedFormatInfo
44
+ readonly format: (instant: Instant) => string
45
+ readonly formatToParts: (instant: Instant) => Intl.DateTimeFormatPart[]
46
+ readonly formatRange: (start: Instant, end: Instant) => string
47
+ }
@@ -0,0 +1,144 @@
1
+ import type { CalendarSystem } from './calendar-system'
2
+
3
+ declare const instantBrand: unique symbol
4
+
5
+ /**
6
+ * An absolute point in time as epoch milliseconds.
7
+ * Instants are plain numbers at runtime: comparison and elapsed arithmetic are exact.
8
+ */
9
+ export type Instant = number & { readonly [instantBrand]: 'Instant' }
10
+
11
+ declare const calendarDateBrand: unique symbol
12
+
13
+ /**
14
+ * A date in a specific calendar system, without time or time zone.
15
+ * Opaque: only the engine that created it can read or transform it.
16
+ */
17
+ export interface CalendarDate {
18
+ readonly [calendarDateBrand]: 'CalendarDate'
19
+ }
20
+
21
+ declare const localDateTimeBrand: unique symbol
22
+
23
+ /**
24
+ * A wall-clock date and time in a specific calendar system, without a time zone.
25
+ * Opaque: only the engine that created it can read or transform it.
26
+ */
27
+ export interface LocalDateTime {
28
+ readonly [localDateTimeBrand]: 'LocalDateTime'
29
+ }
30
+
31
+ /** Day of week: 0 = Sunday … 6 = Saturday (same as `Date#getDay`). */
32
+ export type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6
33
+
34
+ /** How out-of-range calendar fields are handled. */
35
+ export type Overflow = 'constrain' | 'reject'
36
+
37
+ /** How a wall-clock time is mapped to an instant around time-zone transitions. */
38
+ export type Disambiguation = 'compatible' | 'earlier' | 'later' | 'reject'
39
+
40
+ /** A calendar (not elapsed) duration. */
41
+ export interface CalendarDuration {
42
+ readonly years?: number
43
+ readonly months?: number
44
+ readonly weeks?: number
45
+ readonly days?: number
46
+ }
47
+
48
+ export type CalendarPeriodUnit = 'day' | 'week' | 'month' | 'year'
49
+
50
+ /** A half-open calendar period `[start, end)`. */
51
+ export interface CalendarPeriod {
52
+ readonly unit: CalendarPeriodUnit
53
+ readonly start: CalendarDate
54
+ readonly end: CalendarDate
55
+ }
56
+
57
+ /** Calendar-specific metadata of a date. */
58
+ export interface CalendarDateFields {
59
+ readonly calendarSystem: CalendarSystem
60
+ readonly year: number
61
+ /** Ordinal month within the year, starting at 1. Its meaning depends on the year (leap months). */
62
+ readonly month: number
63
+ /** Stable month identity within a calendar, e.g. `M05L` for Hebrew Adar I. */
64
+ readonly monthCode: string
65
+ readonly day: number
66
+ readonly dayOfWeek: Weekday
67
+ readonly dayOfYear: number
68
+ readonly daysInWeek: number
69
+ readonly daysInMonth: number
70
+ readonly daysInYear: number
71
+ readonly monthsInYear: number
72
+ readonly inLeapYear: boolean
73
+ readonly era?: string
74
+ readonly eraYear?: number
75
+ /** Calendar-specific week number. Undefined when the calendar defines none. */
76
+ readonly weekOfYear?: number
77
+ readonly yearOfWeek?: number
78
+ }
79
+
80
+ /** Fields accepted when constructing a calendar date. Validated by the engine. */
81
+ export interface CalendarDateInput {
82
+ readonly year?: number
83
+ readonly era?: string
84
+ readonly eraYear?: number
85
+ readonly month?: number
86
+ readonly monthCode?: string
87
+ readonly day: number
88
+ }
89
+
90
+ /** Changes applied to an existing calendar date. */
91
+ export interface CalendarDateChange {
92
+ readonly year?: number
93
+ readonly month?: number
94
+ readonly monthCode?: string
95
+ readonly day?: number
96
+ }
97
+
98
+ /** Proleptic ISO-8601 (Gregorian) date fields. */
99
+ export interface IsoDateFields {
100
+ readonly year: number
101
+ readonly month: number
102
+ readonly day: number
103
+ }
104
+
105
+ export interface WallClockTime {
106
+ readonly hour: number
107
+ readonly minute: number
108
+ readonly second: number
109
+ readonly millisecond: number
110
+ }
111
+
112
+ /** The calendar date and wall-clock time of an instant in a time zone. */
113
+ export interface ZonedDateTimeFields {
114
+ readonly date: CalendarDate
115
+ readonly time: WallClockTime
116
+ readonly offsetMilliseconds: number
117
+ }
118
+
119
+ /** The first instant of a civil day in a time zone. */
120
+ export interface DayStart {
121
+ readonly instant: Instant
122
+ /**
123
+ * True when the civil day does not exist in the time zone (e.g. 2011-12-30 in Pacific/Apia).
124
+ * `instant` is then the start of the next existing day.
125
+ */
126
+ readonly isSkipped: boolean
127
+ }
128
+
129
+ /** How a wall-clock time maps onto instants in a time zone. */
130
+ export type LocalTimeResolution =
131
+ | { readonly kind: 'unique'; readonly instant: Instant }
132
+ /** The wall-clock time occurs twice (e.g. when clocks are set back). */
133
+ | { readonly kind: 'repeated'; readonly earlier: Instant; readonly later: Instant }
134
+ /**
135
+ * The wall-clock time does not exist (e.g. when clocks are set forward).
136
+ * `earlier` / `later` are the instants the `earlier` / `later` disambiguation would choose.
137
+ */
138
+ | { readonly kind: 'nonexistent'; readonly earlier: Instant; readonly later: Instant }
139
+
140
+ /** A half-open instant interval `[start, end)`. */
141
+ export interface InstantInterval {
142
+ readonly start: Instant
143
+ readonly end: Instant
144
+ }
@@ -0,0 +1,104 @@
1
+ import type { CalendarSystem } from './calendar-system'
2
+
3
+ export type CalendarErrorCode =
4
+ | 'INVALID_DATE'
5
+ | 'DATE_OUT_OF_RANGE'
6
+ | 'CALENDAR_SYSTEM_NOT_SUPPORTED'
7
+ | 'INVALID_TIME_ZONE'
8
+ | 'INVALID_CALENDAR_FIELDS'
9
+ | 'NONEXISTENT_LOCAL_TIME'
10
+ | 'AMBIGUOUS_LOCAL_TIME'
11
+ | 'FORMATTING_NOT_SUPPORTED'
12
+ | 'INVALID_CONFIGURATION'
13
+
14
+ /** Base class of every error thrown by the library. */
15
+ export class CalendarError extends Error {
16
+ readonly code: CalendarErrorCode
17
+
18
+ constructor(code: CalendarErrorCode, message: string, options?: ErrorOptions) {
19
+ super(message, options)
20
+ this.name = 'CalendarError'
21
+ this.code = code
22
+ }
23
+ }
24
+
25
+ export class InvalidDateError extends CalendarError {
26
+ constructor(label: string, options?: ErrorOptions) {
27
+ super('INVALID_DATE', `${label} must be a valid Date instance.`, options)
28
+ this.name = 'InvalidDateError'
29
+ }
30
+ }
31
+
32
+ export class DateRangeError extends CalendarError {
33
+ constructor(message: string, options?: ErrorOptions) {
34
+ super('DATE_OUT_OF_RANGE', message, options)
35
+ this.name = 'DateRangeError'
36
+ }
37
+ }
38
+
39
+ export class CalendarSystemNotSupportedError extends CalendarError {
40
+ readonly calendarSystem: string
41
+ readonly supportedCalendarSystems: readonly CalendarSystem[]
42
+
43
+ constructor(
44
+ calendarSystem: string,
45
+ engineName: string,
46
+ supported: readonly CalendarSystem[],
47
+ options?: ErrorOptions,
48
+ ) {
49
+ super(
50
+ 'CALENDAR_SYSTEM_NOT_SUPPORTED',
51
+ `Calendar system "${calendarSystem}" is not supported by the "${engineName}" date engine. ` +
52
+ `Supported: ${supported.join(', ')}.`,
53
+ options,
54
+ )
55
+ this.name = 'CalendarSystemNotSupportedError'
56
+ this.calendarSystem = calendarSystem
57
+ this.supportedCalendarSystems = supported
58
+ }
59
+ }
60
+
61
+ export class InvalidTimeZoneError extends CalendarError {
62
+ readonly timeZone: string
63
+
64
+ constructor(timeZone: string, options?: ErrorOptions) {
65
+ super('INVALID_TIME_ZONE', `"${timeZone}" is not a supported IANA time zone.`, options)
66
+ this.name = 'InvalidTimeZoneError'
67
+ this.timeZone = timeZone
68
+ }
69
+ }
70
+
71
+ export class InvalidCalendarFieldsError extends CalendarError {
72
+ constructor(message: string, options?: ErrorOptions) {
73
+ super('INVALID_CALENDAR_FIELDS', message, options)
74
+ this.name = 'InvalidCalendarFieldsError'
75
+ }
76
+ }
77
+
78
+ export class NonexistentLocalTimeError extends CalendarError {
79
+ constructor(message: string) {
80
+ super('NONEXISTENT_LOCAL_TIME', message)
81
+ this.name = 'NonexistentLocalTimeError'
82
+ }
83
+ }
84
+
85
+ export class AmbiguousLocalTimeError extends CalendarError {
86
+ constructor(message: string) {
87
+ super('AMBIGUOUS_LOCAL_TIME', message)
88
+ this.name = 'AmbiguousLocalTimeError'
89
+ }
90
+ }
91
+
92
+ export class FormattingNotSupportedError extends CalendarError {
93
+ constructor(message: string) {
94
+ super('FORMATTING_NOT_SUPPORTED', message)
95
+ this.name = 'FormattingNotSupportedError'
96
+ }
97
+ }
98
+
99
+ export class CalendarConfigurationError extends CalendarError {
100
+ constructor(message: string, options?: ErrorOptions) {
101
+ super('INVALID_CONFIGURATION', message, options)
102
+ this.name = 'CalendarConfigurationError'
103
+ }
104
+ }
@@ -0,0 +1,27 @@
1
+ import type { CalendarDateFormatOptions } from '../contracts/date-formatter'
2
+
3
+ type DateStyle = NonNullable<Intl.DateTimeFormatOptions['dateStyle']>
4
+
5
+ /** Component options equivalent to each `dateStyle`, used when a runtime lacks the style pattern. */
6
+ const dateStyleComponents: Readonly<Record<DateStyle, Intl.DateTimeFormatOptions>> = {
7
+ full: { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' },
8
+ long: { year: 'numeric', month: 'long', day: 'numeric' },
9
+ medium: { year: 'numeric', month: 'short', day: 'numeric' },
10
+ short: { year: 'numeric', month: 'numeric', day: 'numeric' },
11
+ }
12
+
13
+ const timePartTypes: ReadonlySet<string> = new Set(['hour', 'minute', 'second', 'dayPeriod'])
14
+
15
+ /**
16
+ * Whether a date-only format produced time parts: the runtime fell back to a generic pattern
17
+ * (observed in Chromium for `he` + `hebrew` + `dateStyle`, which prints "57870617 12:00 PM").
18
+ */
19
+ export function hasUnexpectedTimeParts(parts: readonly Intl.DateTimeFormatPart[]): boolean {
20
+ return parts.some((part) => timePartTypes.has(part.type))
21
+ }
22
+
23
+ /** Replaces `dateStyle` with equivalent component options; other options are kept. */
24
+ export function withoutDateStyle(options: CalendarDateFormatOptions): CalendarDateFormatOptions {
25
+ const { dateStyle, ...rest } = options
26
+ return dateStyle === undefined ? options : { ...dateStyleComponents[dateStyle], ...rest }
27
+ }